How Gainsight generates 3x more closed-won dollars per SE hour See how→

Postgres for the app, ClickHouse for the questions we can’t predict

Two databases. Different jobs.
Written by
Phil Gates-IdemPhil Gates-Idem
Published on
November 23, 2026
Read time
15 min

Sales teams ask hard questions of their data. “How many open deals do we have?” is easy to answer. “Which deals in stage 3, broken down by owner, haven’t had a customer meeting in two weeks, and how does that compare with last quarter?” is harder. That question spans CRM records, calendar events, and tasks, and reaches into history: what the pipeline looked like on a day that has already passed.

Helping account executives (AEs), sales engineers (SEs), sales managers, RevOps, and revenue leaders get those answers is a core part of what Opine does. Our application runs on Postgres, and Postgres runs it well. The queries that scan history and join across multiple tools run on ClickHouse. This post explains why we split the workload, where Postgres still beats ClickHouse in our benchmarks, and how we turn Postgres data into a day-by-day history customers can query through ClickHouse.

Two kinds of analytics

We ran everything on Postgres for as long as we could. One database is simpler to run, back up, and reason about. We stayed there until keeping analytics on it took more upkeep than running a second database. Then we moved analytics to ClickHouse in two waves, to meet two very different needs.

The predictable kind. These are the reports we build into the product. Team Trends and Deal Activity show meeting and activity metrics. The Sales Funnel, Win/Loss, and Technical Process reports show how deals and proofs of concept (POCs) move. We write those queries ourselves and know their shapes in advance, and for a while Postgres served them.

As the calendar tables grew with every calendar a customer connected, each report became a tuning project. Matching calendar events to deals became one of the heaviest I/O consumers on our RDS database. We rewrote two of those queries, deal matching and Team Trends, and kept them in Postgres. On 3 million synthetic events, the rewrite took the deal-matching query from 56 seconds to about 3. On 1 million synthetic events, the Team Trends query went from one we killed after 16 minutes to about 5.5 seconds. Each fix bought time, and every new report needed another one. Today, Team Trends runs on ClickHouse, and over the last 30 days its median in production was about 2 seconds, with a 95th percentile under 5 seconds, on far more data than the synthetic test. These reports scan and aggregate many rows and a handful of columns. A columnar engine is built for exactly that, and ClickHouse is simply faster at it.

The unpredictable kind. Opine SQL lets customers and their AI agents write their own SQL against their data. In the typical customer organization, more than 90% of Opine SQL queries are now written by agents. Nobody can predict those queries. They join whatever they like, filter on any custom CRM field, and often reach back months. You can’t build an index or a rollup for a query nobody has written yet. This is where Postgres runs out of options.

Why ClickHouse?

Fast reads and fast writes brought us to ClickHouse. On the read side, it scans and aggregates the few columns a question needs across millions of rows, and the benchmark below shows how far ahead of Postgres that puts it. On the write side, it takes in large batches quickly. Our snapshot pipelines depend on that: every end-of-day snapshot writes a full copy of every deal for every customer, and intraday snapshots run through the working day. Performance is why we initially chose ClickHouse, and several other capabilities made it an even stronger fit.

ClickHouse is open source, so we develop against the same database we run. Every engineer runs a real ClickHouse server in development, and our integration tests run against one too. Production runs on ClickHouse Cloud with the same SQL and the same DDL. A query that misbehaves in production can be reproduced locally.

The SQL dialect is built for analytics. GROUP BY ALL saves repeating a long select list. argMax picks the value from the latest version of a row in a single aggregate, and argMaxIf adds a condition. Lambdas and array functions work on lists in place. Typed query parameters such as {org:Int32} keep values out of the SQL text, and parameterized views let a saved query take arguments like a table function. The Opine SQL compiler relies on those last two.

The compression is strong. In our benchmark, a synthetic year of daily deal snapshots took 101 GiB in ClickHouse (using its open-source default LZ4 codec with no per-column tuning) and 397 GiB in Postgres. ClickHouse Cloud defaults to ZSTD, which usually compresses further. Less data on disk also means fewer bytes for every query to read.

ClickHouse reads and writes files where they live. CRM exports land in S3, and one INSERT … SELECT FROM s3() loads them. Scheduled customer exports go the other way. We wrap a compiled Opine SQL query in INSERT INTO FUNCTION s3(...), and ClickHouse streams Parquet, CSV, or JSON straight to the customer’s own storage.

Postgres data arrives through ClickPipes, ClickHouse Cloud’s managed ingestion service. It reads change data from our RDS database and keeps the replica tables current, with no replication code of our own.

Every query is easy to measure after it runs. ClickHouse records each one in system.query_log, with the rows and bytes it read, its peak memory, and its duration. Most of our performance work starts there.

Access control lives in the database too. Per-organization users, row policies, and settings profiles give us a second layer of tenant isolation that ClickHouse enforces itself.

Comparing ClickHouse to Postgres

Plenty of teams have moved analytics from Postgres to ClickHouse and written about their gains, including GitLab, Lago, and Helicone. Rather than take those results on faith or rely on engineering folklore, we wanted our own benchmarks on the query shapes Opine SQL actually runs.

The comparison setup

  • Engines: Postgres 18.4 and ClickHouse 26.6, both open-source builds in Docker containers on one workstation with a local NVMe SSD. The containers had identical CPU and memory limits and were pinned to the same cores. They never ran a query at the same time.
  • Data: Synthetic and deterministic. No customer data was used. Ten tenants share the tables, each with 365 daily snapshots. A “mid” tenant has 20,000 deals, and a “large” one has 250,000.
  • Queries: The ClickHouse queries came straight out of the real Opine SQL compiler. The Postgres versions are hand translations with the same tenant and snapshot filtering.
  • Correctness: Every query returned identical results on both engines.
  • Fairness to Postgres: We gave it the tuning a competent engineer would: monthly partitions, B-tree indexes, VACUUM (FREEZE, ANALYZE), extended statistics, and a planner override where its default plan was pathological. We also ran it on more than one schema, because the schema question matters (see below).

Local containers, cloud production

We ran the benchmark on one workstation. In production, Postgres runs on Amazon RDS and ClickHouse runs on ClickHouse Cloud. The Postgres versions match: RDS runs the same version 18.4. ClickHouse Cloud runs version 26.8, two releases past the benchmark’s 26.6, because our service follows the fast release channel. The bigger difference is the storage under each engine.

Open-source ClickHouse keeps a table’s data parts and metadata on the server’s own disk. Its MergeTree engines work that way, and our benchmark tables used plain MergeTree on the local SSD. ClickHouse Cloud uses the SharedMergeTree engine family instead. ClickHouse describes it as a cloud-native replacement for the ReplicatedMergeTree engines. SharedMergeTree keeps the data in object storage such as S3 and the metadata in ClickHouse Keeper. Replicas share that single copy and don’t need to communicate with each other.

Our DDL doesn’t mention any of this. We write ENGINE = ReplacingMergeTree, and ClickHouse Cloud substitutes the matching Shared* engine when it creates the table. Our CDC replica tables run as SharedReplacingMergeTree in production. The same DDL runs as ReplacingMergeTree in local development.

The storage difference matters most for the cold numbers. A cold query on ClickHouse Cloud fetches its columns from object storage, which has higher latency than a local NVMe drive. ClickHouse Cloud then caches that data on its compute nodes for the next query. Postgres on RDS doesn’t read from a local drive either. It keeps its data on network-attached storage. Treat the absolute times below as local measurements. The ratios come mostly from how many bytes each engine has to read, and the row or column layout that sets that number is the same in production.

History questions: where the gap is enormous

These are the questions that reach back in time, such as “What was the open pipeline value per day for the last year?” or “How did the stage mix change over the last quarter?” Both engines read the same table here: one wide row per deal per day.

Results show warm median execution times (ClickHouse speedup in parentheses):

QueryMid tenant: Postgres / ClickHouseLarge tenant: Postgres / ClickHouse
Open pipeline by day, 365 days4.6 s / 20 ms (230×)121 s / 66 ms (1,838×)
Stage mix by day, 365 days6.0 s / 68 ms (88×)129 s / 570 ms (227×)
Distinct deals per stage, 365 days11 s / 83 ms (132×)233 s / 924 ms (253×)
Forecast calibration, 90 days1.7 s / 27 ms (62×)44 s / 262 ms (166×)
Custom CRM field (JSON) by day, 90 days2.6 s / 129 ms (20×)65 s / 960 ms (68×)

Across all five history queries, ClickHouse was 20× to 230× faster for the mid tenant and 68× to 1,838× faster for the large one. For the large tenant, four of the five took Postgres longer than Opine SQL’s 45-second interactive timeout. ClickHouse answered every one in less than a second.

The gap comes down to how much data each engine has to touch. For “open pipeline by day, last year” on the large tenant, Postgres read about 141 GB of pages, while ClickHouse read about 0.56 GB of column data. Each snapshot row is about 5 KB wide, and the query needs 3 of its roughly 240 columns. A row store has to read the whole row to get at those three values; a column store reads only the three columns.

A covering index built specifically for that query brought Postgres from 121 seconds down to 4.5 seconds. That’s still about 70× slower than ClickHouse, and the index helps exactly one query shape. It does nothing for the next ad-hoc question a user thinks to ask.

Current-state questions: much closer

Most dashboards ask about now: average deal size by stage or the top companies by pipeline value. For these, we compared three setups:

  1. Postgres reading the same wide snapshot table as ClickHouse.
  2. Postgres reading normalized tables shaped like our real application schema, with joins instead of one wide row.
  3. ClickHouse reading the wide snapshot table.

Results show warm median execution times (cold in parentheses):

QueryTenantPostgres, wide tablePostgres, normalizedClickHouse, wide table
Average deal size by stageMid20 ms (47 ms)33 ms (693 ms)6 ms (31 ms)
Average deal size by stageLarge141 ms (297 ms)46 ms (200 ms)9 ms (32 ms)
Top 10 companies by valueMid23 ms (56 ms)34 ms (492 ms)6 ms (30 ms)
Top 10 companies by valueLarge309 ms (563 ms)227 ms (426 ms)13 ms (38 ms)
Custom CRM field filter, top 20Mid137 ms (165 ms)96 ms (431 ms)11 ms (32 ms)
Custom CRM field filter, top 20Large628 ms (828 ms)215 ms (359 ms)22 ms (50 ms)
Meetings per deal stage, weeklyLarge1.4 s (2.0 s)can’t answer142 ms (204 ms)
One deal by IDMid0.3 ms (9.8 ms)0.5 ms (14 ms)4 ms (30 ms)
One deal by IDLarge0.2 ms (9.6 ms)0.5 ms (14 ms)4 ms (33 ms)

Our application uses the normalized schema. Against it, ClickHouse was 5× to 17× faster warm and 6× to 22× faster cold on these dashboard-style aggregates. The normalized tables beat the wide table for the large tenant because their rows are much narrower. For the mid tenant, the normalized tables were slower when cold because its rows are scattered across tables shared with other customers. Clustering those tables by the tenant fixed it. Our normalized Postgres can’t answer the calendar question at all because the links between meetings and deals are computed only in ClickHouse.

Two results cut the other way. Postgres still wins the single-deal lookup by 7× to 8× warm. And when we added one index tailored to the custom-field query, normalized Postgres answered it in less than half a millisecond, which was faster than ClickHouse. An index is the right tool to use when you know the question in advance.

Where Postgres wins

Looking up one deal by ID in the wide table took Postgres 0.3 ms against 4 ms for ClickHouse. One deal’s year-long timeline was 10× to 38× faster on Postgres too. A B-tree index finds a handful of rows almost instantly, and ClickHouse is built for scanning columns. Point lookups are the work an application does frequently and a primary reason Opine itself still runs on Postgres.

Transactions are the other reason Opine stays on Postgres. When a user saves a change that touches several tables, Postgres commits all of it or none of it, and foreign keys and unique constraints reject bad rows before they land. More than 100 of our repository modules rely on that.

ClickHouse offers much less here. An INSERT into one partition of one table is atomic, but there’s no BEGIN and COMMIT across statements, and ClickHouse’s experimental transactions aren’t supported in ClickHouse Cloud. Our analytics don’t need them. Every row is already committed in Postgres before ClickPipes copies it, so the consistency decisions happen upstream. The replica tables add each change as a new version of the row and let the latest win instead of updating in place. And the snapshot pipeline publishes each run with a final status row: readers see a snapshot only after its last step succeeds. A half-written run is never visible.

The schema caveat

Nobody would design a Postgres schema the way we stored the history tables, with a full copy of every deal every day. A Postgres-native design would store only the changes, as rows with valid-from and valid-to dates. Since only about 0.6% of rows change on a given day, that would be 30× to 100× smaller and would close much of the history gap. The cost is that every “as of this day” question becomes an interval join. Our compiler would have to write it correctly for every history table and every customer query. We didn’t benchmark that design.

The wide daily snapshot is the design that makes history easy to query. A columnar engine is what makes it affordable.

Wide, denormalized snapshots

Denormalizing for analytics is well-trodden ground. The general argument is short: fewer joins, faster scans. What surprised us is how much a column store changes the trade-offs.

  • Width is almost free. Our deal snapshot has about 240 columns: the deal, its company, its pipeline and stage names, its participants, its CRM fields as JSON, and an AI summary. In Postgres, every extra column makes every row bigger, and every scan pays for it. In ClickHouse, a query pays only for the columns it reads. That lets us put everything a question might need on one row without slowing down the questions that don’t need it.
  • Time travel becomes a filter. Each daily snapshot holds the full state of every deal on that day. “What did the pipeline look like on March 3?” becomes a WHERE clause on that day’s snapshot.
  • Simpler SQL for people and agents. One wide row means fewer joins to get wrong, whoever writes the query.
  • Uniform scoping. Every table carries the organization and snapshot it belongs to, which keeps tenant scoping consistent everywhere.

The architecture

Data moves in one direction. Application and CRM data flow into ClickHouse, two pipelines reshape it there, and the in-app reports and Opine SQL read the result.

Postgres stays the system of record. The application writes to Amazon RDS Postgres, as it always has. ClickPipes streams those changes into replica tables in ClickHouse over private connectivity. The replica tables use ReplacingMergeTree, so the latest version of each row wins. ClickPipes pushes a batch of changes at least once a minute. Over one recent day, the median change reached ClickHouse about 35 seconds after the application wrote it, and the 95th percentile about a minute later.

CRM data arrives in bulk. CRM exports land in S3, and ClickHouse loads them into raw tables with INSERT … SELECT FROM s3().

The org snapshot pipeline does the denormalizing. A series of INSERT … SELECT steps joins the replica and CRM tables into the wide snapshot tables. Intraday snapshots run every two hours for every customer, and the end-of-day snapshot becomes that day’s permanent history. That interval sets how fresh reports and Opine SQL results are, more than CDC lag does: queries read the latest snapshot, so their data can be a little more than two hours old. We accept that because each snapshot is a consistent picture of the whole organization at one moment. The steps run in buckets that retry independently, and one failure doesn’t restart the whole run.

The calendar pipeline connects meetings to deals. It deduplicates meetings across calendars and links each one to the deals and accounts it belongs to, with a confidence score.

The schema lives in code. ClickHouse table definitions are generated from the same schema as our Postgres models, and drift detection keeps the two databases from silently diverging.

Time travel over CRM history

Every end-of-day snapshot is kept. We don’t roll old snapshots up into weekly or monthly ones. At the current rate, a day of end-of-day snapshots adds about 10 GiB to ClickHouse Cloud, compressed about 11× from about 113 GiB of uncompressed column data. That comes to less than 4 TiB a year, held in object storage. The daily volume keeps growing as customers join and as we add tables to the snapshot. In Opine SQL, each table has a _history twin that takes a date range:

SELECT
  toDate(snapshotted_at) AS day,
  sum(deal_converted_amount) AS open_pipeline_value
FROM deal_history(
  startDateInclusive = startOfPeriod('day', -364),
  endDateInclusive = endOfPeriod('day')
)
WHERE deal_closed = 0
GROUP BY ALL
ORDER BY day

Under the hood, deal_history compiles to a filter over a ClickHouse parameterized view. For each day in the range, the view picks the last successful snapshot of the customer’s organization, so a failed snapshot attempt never shows up as a gap or a duplicate:

SELECT
  toDate(o.org_snapshot_started_at) AS org_snapshot_date,
  argMax(o.org_snapshot_id, o.org_snapshot_started_at) AS org_snapshot_id
FROM org_snapshot AS o
WHERE o.organization_id = {organizationId:Int32}
  AND o.org_snapshot_status = 'SUCCESS'
  AND toDate(o.org_snapshot_started_at)
      BETWEEN {startDate:Date} AND {endDate:Date}
GROUP BY org_snapshot_date

That opens up questions that are painful anywhere else. Forecast calibration is a good example. For every deal that closed, what probability did the CRM give it while it was still open, and how often did deals in each probability band actually win? In Opine SQL that’s an argMaxIf over each deal’s history: take the probability from the latest snapshot in which the deal was still open, then group deals by probability band.

A few engineering details made this practical:

  • Partitioning: History tables are partitioned so that a date-range query reads only the partitions it needs.
  • Expiry: Intraday snapshots expire with a TTL using ttl_only_drop_parts, so cleaning them up drops whole parts instead of rewriting data.
  • FINAL and partition pruning: FINAL merges duplicate versions at query time. A compatibility setting had turned off partition pruning for any statement containing FINAL, and no error said so. Turning it back on took one snapshot step from reading about 1,600 ranges across every partition to 10 ranges in a handful of partitions and cut its memory by more than half.

What it enables

The same tables feed everything:

  • In-app reports: Team Trends, Deal Activity, the Sales Funnel, Win/Loss, and Technical Process query the snapshot and calendar tables directly.
  • Opine SQL: The SQL playground, custom dashboards, scheduled exports, the public API, and AI agents all query one curated catalog of about 80 tables over that data.

That raises the obvious follow-up question: If customers and agents can write any SQL they like against a shared, multi-tenant warehouse, how does each query see only what that user is allowed to see? Every query goes through a compiler that scopes it to the user’s organization and permissions, and ClickHouse adds its own safeguard with a database user for each organization.

Lessons learned

  • Stay on one database as long as you can. We kept analytics on Postgres until maintaining it there cost more than running a second database. Adding ClickHouse earlier would have meant running two systems before we needed both.
  • Keep the operational database for operations. Postgres is the right home for the application, and the benchmark showed exactly why: point lookups. Moving analytics off it also kept heavy queries away from the database the product depends on.
  • Pick the data model for the questions, then the engine that makes it affordable. The wide daily snapshot turns a history question into a simple filter, and a column store keeps it cheap to scan.
  • ReplacingMergeTree plus FINAL has costs. Deduplicating at read time is convenient, but it needs care with partition pruning and memory. One compatibility setting silently turned off pruning for every query that used FINAL, and we noticed only when a snapshot step’s memory spiked. We recommend locking the compatibility level with the compatibility setting.

Custom dashboards in Opine run on the tables this post describes. Every chart compiles to an Opine SQL query, so the history and the speed come with it.

Get the latest in your inbox

Get weekly tips & strategies from your friends at Opine to close faster, reduce risk, and grow revenue.

Experience the power of Opine
(Your revenue team will thank you)

We don’t sell Opine, we believe once you see it, it sells itself. Well, that’s what our happy customers tell us anyway.

Book a demo