HomeDataClickHouse

ClickHouse · How to add it beside Postgres

Fast reports without breaking your live app

Set up clickhouse postgres cdc so reports read fresh data without slowing your app: WAL capture, the options compared, and the checks that matter.

Don't want to read the whole article?

No problem. We put everything in a 1-minute video, so you get the full idea fast.

By submitting, you agree that Sivaro may contact you about this topic.

Fast reports without breaking your live app
Fast reports without breaking your live app Fast reports without breaking your live app

It's Monday morning and the finance dashboard shows yesterday's totals while orders keep landing. You want ClickHouse reading fresh numbers without pointing your reporting tool at the Postgres primary. The answer: run clickhouse postgres cdc, a sync pipeline that copies each insert, update and delete from Postgres into ClickHouse, so the app keeps working and reports read current data [1][8]. This page is part of the ClickHouse topic map; it proves one part of the map's answer: how to add ClickHouse beside Postgres to get fast dashboards.

In short

  • The mistake most teams make first is polling Postgres with WHERE updated_at > $last: it cannot see deletes, and your updated_at column will lie eventually, so read the WAL instead [8].
  • Postgres already writes every change to its Write-Ahead Log for crash recovery; CDC reads that log through a logical replication slot and turns it into an ordered stream [8].
  • Three common ways plug Postgres CDC into ClickHouse: Debezium with Kafka, ClickHouse's built-in MaterializedPostgreSQL engine, and managed ClickPipes on ClickHouse Cloud [8].
  • Debezium with Kafka gives you the same change stream for your search index, audit log and warehouse, and that fan-out is the main reason teams accept the cost [8].
  • MaterializedPostgreSQL runs CDC inside ClickHouse with no Kafka and no Debezium, but adding or dropping a Postgres column silently stops replication for that table [8].
  • ClickPipes is the managed path: connection string, publication name, slot name and a destination database, with a UI, an OpenAPI and a Terraform provider [8].
  • The result for the business: a report query that takes minutes on Postgres goes to milliseconds on ClickHouse on similar shapes, so dashboards stay fast as data grows [8].

At a glance

Fact Detail
The mechanism Postgres WAL read through a logical replication slot, streamed into ClickHouse [8]
Debezium path Tails the WAL, publishes to Kafka, a sink writes into ClickHouse [8]
Built-in path MaterializedPostgreSQL database engine mirrors tables inside ClickHouse [8]
Managed path ClickPipes on ClickHouse Cloud, built on PeerDB [8]
Debezium latency End-to-end under 2 seconds in a published reference setup [1]
Sync interval (ClickPipes) Keep above 3600 seconds for cost-sensitive users [3]
Silent failure Some simple DDL does not break MaterializedPostgreSQL replication anymore. [8]
Prerequisite setting wal_level=logical on the Postgres source [1]

Why your dashboard can't just query Postgres

Your dashboard can't just query Postgres because analytical scans and your application compete for the same CPU and connections. Postgres is row-oriented and built for OLTP, not for scanning tens of millions of rows for a GROUP BY [8]. A read replica doesn't fix the shape problem: it moves the load, but the storage still reads row by row.

Before: the reporting tool hits the primary, the checkout page slows down, and someone suggests running reports at night.
After: Postgres serves the app, ClickHouse serves the reports, and the two stay in step through a change pipeline.

CDC is the mechanical part. Every insert, update and delete in Postgres gets captured and forwarded somewhere else [8]. The app writes to Postgres as it always did; nobody touches application code [1]. ClickHouse does what it's built for, which is answering questions over large event tables, a use covered in What is ClickHouse Used For?.

How clickhouse postgres cdc actually works

ClickHouse postgres cdc works by reading the Postgres Write-Ahead Log through a logical replication slot and replaying each change into a ClickHouse table. Postgres already writes everything to the WAL for crash recovery; CDC turns that log into an ordered stream you can replay into another system [8]. No polling, no trigger functions on your tables, no scanning for changed rows.

The source describes a production-grade Change Data Capture pipeline that streams INSERT, UPDATE, and DELETE changes from PostgreSQL to ClickHouse in under 2 seconds using Debezium and Kafka [1]

text
Postgres WAL
  → logical replication slot
  → Debezium captures INSERT / UPDATE / DELETE
  → Kafka topic
  → ClickHouse Kafka Engine table
  → Materialized View transforms the row
  → ReplacingMergeTree stores the latest version

Each stage has a job. Debezium reads the WAL through the replication slot and publishes change events into Kafka [8]. ClickHouse's Kafka Engine can continuously consume Kafka topics into a table, with a materialized view transforming and inserting rows into a ReplacingMergeTree table [1]. A materialized view flattens and transforms the row, and a ReplacingMergeTree table keeps the latest version per key [1].

One detail bites people: Debezium's default output wraps every event in a {before, after, source, op} envelope. The ExtractNewRecordState transform flattens it to a simple row, which ClickHouse's JSONEachRow format parses without trouble [1].

The WAL side needs configuration. The source database must run with wal_level=logical, a publication must list the tables you want, and the replication user needs a slot and the right identity settings [1].

On the ClickHouse side, ReplacingMergeTree exists because CDC produces multiple events per row: an insert, then updates [1]. The table deduplicates lazily on the ORDER BY key, so you query with FINAL when you need exact current state [1]. That lazy dedupe is easy to forget, and forgetting it gives you double-counted totals.

A second table shape shows the same idea with an explicit version column: the pair of (table_name)_id and record_version acts as the primary key, so fetching a record id with the highest record_version returns the most recent state [2]. A db_action column tracks whether the row was an insert, update or delete [2]. Either shape works; pick one and stay with it.

Three ways to connect them, and what each one asks of you

There are three common ways to plug Postgres CDC into ClickHouse, and they differ mainly in how many moving parts you own [8]. The table below keeps the trade-offs side by side.

Debezium + Kafka MaterializedPostgreSQL ClickPipes (ClickHouse Cloud)
Where CDC runs Debezium on Kafka Connect, Kafka broker, sink Inside ClickHouse Managed on ClickHouse Cloud, built on PeerDB [8]
Moving parts you run Kafka, Zookeeper, Debezium, sink connector [1][5] ClickHouse has a built-in database engine called MaterializedPostgreSQL that does CDC inside ClickHouse itself [8] The service; you supply connection details
Fan-out to other systems Yes, the same topic feeds search, audit and warehouse [8] No No
DDL change handling Handled by the connector's schema history Table silently stops replicating [8] Managed
Schema change tooling Debezium endpoints manage the connector [2] Manual DETACH / ATTACH [8] UI, OpenAPI, Terraform [8]
Best fit Teams already running Kafka Small setups, few tables, no Kafka Teams on ClickHouse Cloud

The Debezium route is the most documented. Reference repositories put Kafka, Debezium, a sink connector and ClickHouse behind one docker compose up -d, with the Postgres, ClickHouse, Kafka, Zookeeper and Kafka Connect containers all declared together [5][6]. A Debezium connector config is a JSON document posted to the Kafka Connect REST endpoint [2].

The built-in route skips all of that. MaterializedPostgreSQL opens a Postgres replication slot directly and streams WAL changes into mirror tables on the ClickHouse side, with no Kafka, no Debezium and no third process [8]. For a team without a Kafka cluster, that is a real saving in machines and attention.

The managed route is ClickPipes. It does the same job as MaterializedPostgreSQL, read Postgres logical replication and write into ClickHouse, but as a managed pipeline on ClickHouse Cloud, with PeerDB underneath [8]. Setup is a connection string, a publication name, a slot name and a destination database [8]. If a third-party tool is under consideration instead, the 2026 buyer's guide to migration tools covers that comparison.

A fourth path shows up in older guides: a Python script that copies records from the OLTP database to the OLAP one in batches [2]. It works for a one-time backfill. It is not CDC, and it will not keep up with deletes.

Running the pipeline without babysitting it

Running the pipeline without babysitting it

Running the pipeline comes down to three habits: watch the lag, know how to restart a stalled consumer, and never let WAL pile up on the source. A sync pipeline that fails silently is worse than a nightly batch, because people trust the numbers.

Watch the lag, not the dashboards

The health signal for clickhouse postgres cdc is lag, the gap between when a change happened in Postgres and when it landed in ClickHouse. In a reference setup, an end-to-end latency check compares the change timestamp with the ingestion timestamp per row [1]. A lag of zero means ClickHouse is fully caught up [1].

A heartbeat table is the simplest always-on check. Write a row in Postgres every minute with an upsert, add the table to the publication, and define lag on the ClickHouse side as now() - max(ts) from the replicated heartbeat table. Export the result to your metrics backend and alert when it goes stale [8]. That one check catches most stalls before a person notices a wrong number.

Restart a stalled consumer

When rows stop updating in ClickHouse, look at the consumer state first. The Kafka consumer system table shows messages read and the last exception per table; a restart is a DETACH TABLE followed by an ATTACH TABLE on the Kafka engine table [1]. On the Debezium side, the connector REST endpoint exposes a restart call, and the connector log shows the error behind the pause [1].

On the MaterializedPostgreSQL path there is no Kafka consumer to restart. If a table stops replicating after a DDL change, you detach the table permanently, update the materialized_postgresql_tables_list setting and attach it again [8].

Keep WAL from piling up

An inactive replication slot holds WAL on the Postgres primary forever, and the disk fills. Check the slots and their retained WAL with a query against pg_replication_slots; the retained_wal column shows how much a slot is pinning [1]. A slot whose consumer died is the usual cause.

Watch the small things

Timestamps arrive from Debezium as ISO8601 strings such as 2025-08-20T11:14:54.702717Z, so parse them with parseDateTime64BestEffort() in the materialized view [1]. Match the connection details to the real network: in the reference setup, ClickHouse reaches Kafka through the external listener on port 29092, not the internal port [1]. Get those wrong and the pipeline looks healthy while nothing lands.

What drives the cost

Cost in a clickhouse postgres cdc setup comes from three places: the extra processes you run, the retention on the change stream, and how often the destination polls or merges. None of them are ClickHouse's storage bill, so plan for them separately.

The Debezium route's biggest fixed cost is Kafka and its support services. The reference stacks run Zookeeper alongside the Kafka broker, plus Debezium on Kafka Connect [1][5]. That is a cluster to patch, monitor and back up whether or not you have traffic.

On ClickPipes, the sync interval is the lever. ClickPipes polls the source database for changes at that interval, and for cost-sensitive users the documentation recommends keeping the interval high, over 3600 seconds [3]. A higher interval means fewer polls and older data. If your dashboard tolerates an hour of lag, set the interval high and save; if it needs seconds, that saving is off the table.

Retention on the change stream matters too. Kafka stores each table's change events in its own topic [1]. ReplacingMergeTree deduplicates lazily, so always use FINAL for accurate results [1].

Whether ClickHouse itself is free depends on which edition you run; the honest answer on ClickHouse pricing lays out the editions without a sales pitch.

If your budget is fixed and small, and the team is one or two people, the built-in MaterializedPostgreSQL path removes the Kafka bill entirely, at the price of manual schema handling [8].

When this is the wrong choice

ClickHouse postgres cdc is the wrong choice when Postgres already answers your questions fast enough, or when the change stream would need more maintenance than the reports are worth. Four cases where another choice wins:

Your data fits comfortably in Postgres and the slow query is one index away. A row store with a good index answers a report over a few million rows in seconds. Adding a column store and a pipeline to save that query is work without a payoff. Fix the query first.

You need to see every delete immediately in the destination. On the MaterializedPostgreSQL path, an ALTER TABLE on Postgres, adding a column for example, stops replication for that table with no log line, no error and no metric; other tables keep replicating and the slot keeps advancing, so the only signal is that your numbers are wrong [8]. If your team can't own a schema-change checklist, use Debezium or ClickPipes instead, or leave the reporting on Postgres.

Zookeeper, Kafka, Kafka Connect and the sink connector are all containers that can fail [1][5]. If nobody owns them, the Debezium route will rot. Pick ClickPipes if you are on ClickHouse Cloud, or the built-in engine if the table list is small [8].

You need exactly one database for transactional and analytical reads. The map's answer, keep Postgres for the app and add ClickHouse beside it, assumes you can split the two. If a single store is a hard requirement, ClickHouse is not the transactional store you want. For a broader comparison against the other warehouse default, see whether ClickHouse beats Snowflake.

How to check in your own system

Four signs change the answer from "add a pipeline" to "fix something else first." Look for each one before you install anything.

  1. Your report query is the problem, not the store. Run the slow report with EXPLAIN (ANALYZE, BUFFERS) on Postgres this week. If the plan shows a missing index or a bad join order, fix that and stop.
  2. Your reporting load competes with the app. Watch CPU and connection counts on the primary during the report window. Analytical queries cannot run on the same Postgres primary that serves the application without paying for it in CPU and connections; a read replica does not help, so a column store on the side is needed [8].
  3. Your change volume is small. If a full refresh of the reporting tables finishes in minutes, a batch copy may be simpler than CDC. CDC earns its keep when deletes and updates arrive all day.
  4. Your schema changes often. Count ALTER TABLE statements on the replicated tables over the last month. Frequent schema changes rule out the built-in engine unless you own a checklist for it [8].
  5. Your team can own the moving parts. List who would restart a stopped consumer at 2 a.m. If the answer is nobody, choose the path with the fewest processes.

The cheapest check to run this week is WAL headroom and lag, both from read-only queries:

  1. On Postgres, run SHOW wal_level; and confirm the value is logical [1].
  2. Query pg_replication_slots for slot_name, active and the retained WAL size per slot; confirm no slot is inactive [1].
  3. On ClickHouse, tick a row in Postgres and read it back through the destination table with FINAL; the latency column from the reference check shows seconds of lag [1].
  4. Add the heartbeat table and alert when now() - max(ts) crosses your tolerance [8].

If steps one and two pass and step three lags by seconds, the pipeline is doing its job, and the next question is how far the reporting tables can lag before a person notices.

Deletes and updates are where the two halves of the pipeline meet. The _peerdb_is_deleted filter keeps tombstones out of query results on the ClickPipes path, and `ORDER BY ... Debezium publishes change events into Kafka, and a separate sink consumes from Kafka and writes into ClickHouse [8]. Getting those two right is most of what "fresh data" means in practice. A deeper page will cover copying every new order to reports in seconds; another will cover dashboards that stay fast as data grows.

Key terms

Change Data Capture (CDC): CDC is a pipeline that records every insert, update and delete in a source database and replays those changes into another system [8].

Write-Ahead Log (WAL): The WAL is Postgres's crash-recovery log, written before changes are committed; CDC reads it as an ordered stream of changes [8].

CDC reads the Postgres WAL via a logical replication slot and turns it into an ordered stream you can replay into another system [8].

Publication: A publication is the Postgres object that lists which tables a replication slot will send changes for [1].

Debezium: Debezium is an open-source connector that tails the Postgres WAL and publishes each change event to Kafka [7].

Kafka Engine table: A Kafka Engine table is a ClickHouse table that consumes messages from a Kafka topic and passes each one to a materialized view [1].

ReplacingMergeTree: ReplacingMergeTree is a ClickHouse table engine that keeps the latest version of a row per ordering key and deduplicates lazily, so queries need FINAL for exact results [1].

MaterializedPostgreSQL: MaterializedPostgreSQL is a ClickHouse database engine that opens a Postgres replication slot and mirrors selected tables inside ClickHouse without Kafka [8].

ClickPipes is ClickHouse Cloud's managed ingestion service whose Postgres CDC tile reads logical replication; setting up a Postgres CDC pipe requires a direct Postgres connection, and connection poolers such as PgBouncer in transaction mode, RDS Proxy, and Supabase Pooler are not supported [3][8].

FINAL: FINAL is a ClickHouse query modifier that merges duplicate rows at read time, so ReplacingMergeTree answers match the current state [1].

Common questions

What is the simplest way to set up clickhouse postgres cdc?

The simplest path is ClickHouse's built-in MaterializedPostgreSQL engine if you run ClickHouse yourself, because it needs no Kafka and no Debezium [8]. On ClickHouse Cloud, the Postgres CDC tile in ClickPipes is the equivalent: supply a connection string, a publication name, a slot name and a destination database [8]. Both read the Postgres WAL through a logical replication slot, so the source needs wal_level=logical either way [1].

Does CDC slow down my Postgres primary?

CDC adds a replication slot and the work of decoding WAL, not a second copy of every query. The overhead that hurts production is the reporting load itself, which is what the split removes: you cannot run analytical queries on the same primary that serves your application without paying in CPU and connections [8]. Watch retained WAL per slot so a dead consumer never fills the disk [1].

Why are my ClickHouse totals double-counted?

Totals double-count when you query a ReplacingMergeTree table without FINAL. CDC produces several events per row, and the engine deduplicates lazily on the ORDER BY key, so only a FINAL query returns the current state [1]. The same applies to tombstone rows on a managed pipeline: filter them out with the delete flag column [8].

How fast does a change reach ClickHouse with Debezium?

A published Debezium setup streams every insert, update and delete from Postgres into ClickHouse in under 2 seconds, without touching application code [1]. The actual number depends on the Kafka round trip, the consumer's batch settings and the materialized view's parse cost. Measure it per row with the latency comparison of change timestamp against ingestion timestamp [1].

What happens when someone adds a column to a replicated table?

On the built-in MaterializedPostgreSQL path, replication for that table stops silently: no log line, no error, no metric, and the only signal is wrong numbers [8]. The fix is to detach the table permanently, update the tables list setting and attach it again [8]. Debezium connectors can be created and managed through a REST API, with configuration defined in a connector JSON file [2].

Do I need Kafka for CDC from Postgres to ClickHouse?

No. MaterializedPostgreSQL and ClickPipes both read Postgres logical replication without Kafka [8]. Kafka earns its place when the same change stream must also feed a search index, an audit log and the warehouse, which is the main reason teams accept its cost [8].

How do I know the pipeline is keeping up?

Track lag, the delay between a change in Postgres and its arrival in ClickHouse. The heartbeat pattern writes a row every minute with an upsert, and lag becomes now() - max(ts) from the replicated table, exported to your metrics backend with an alert when it goes stale [8]. A direct per-row check compares the change timestamp with the ingestion timestamp and reports a lag of zero when ClickHouse is caught up [1].

Can I run this on my own servers without a managed service?

Yes. A reference stack runs Postgres, Kafka, Zookeeper, Debezium, Kafka Connect and ClickHouse in one Docker Compose file, started with docker compose up -d [5][6]. The built-in MaterializedPostgreSQL engine is even smaller: it needs only the ClickHouse server and a Postgres slot [8]. Either way you own the upgrades, the monitoring and the slot cleanup.

References

References
  1. postgres-kafka-clickhouse-cdc
  2. joelatiam/cdc: Change Data Capture (Postgres)
  3. Ingesting data from Postgres to ClickHouse (using CDC)
  4. CDC Setup from Postgres to ClickHouse
  5. GitHub - leartbeqiraj1/cdc-postgresql-clickhouse
  6. ClickHouse-examples/cdc-postgresql-clickhouse
  7. GitHub - yesyigitcan/cdc-example-postgres-to-clickhouse
  8. Three Ways to Set Up CDC from Postgres to ClickHouse

Want to talk this through?