Field notes · ClickHouse

Deduplicating CDC data in ClickHouse without FINAL on every query

Why streamed CDC data ends up with duplicates, why ReplacingMergeTree and FINAL are not the whole answer on big tables, and the scheduled partition dedup that keeps queries cheap.

By Danish Rajpoot · 30 November 2026 · 7 min read

Sooner or later every team that streams change data capture into ClickHouse runs the same query: count() against uniqExact(id) on a table that is supposed to hold one row per record. The two numbers do not match. Someone suggests adding FINAL to every query, the dashboards get slower, and a few weeks later the cluster is doing a lot of work just to hide duplicates that should not be there in the first place.

I build CDC pipelines from MySQL and Postgres through Debezium and Kafka into ClickHouse, and deduplication is one of the first things I design, not something I bolt on later. This is how I think about it.

Why CDC into ClickHouse produces duplicates at all

Duplicates are not a sign that something is broken. They are the normal result of a pipeline that is built to never lose data. Debezium and Kafka give you at-least-once delivery, which means that under the right conditions the same change is delivered more than once. The usual sources:

  1. Connector restarts. When a connector restarts, it resumes from the last committed offset, and anything it read after that offset gets read again.
  2. Consumer retries. If an insert into ClickHouse times out but actually succeeded, a retry writes the same batch twice. Fail-closed delivery, where the consumer does not commit until the write is confirmed, makes this more likely, and that is the right trade-off.
  3. Snapshot and stream overlap. An initial snapshot or a re-snapshot of a table overlaps with the change stream, so the same row arrives once from each.
  4. Updates by design. Every update to a source row is a new event. If the target keeps one row per key, every update is a "duplicate" until something collapses it.

ClickHouse does have insert deduplication for replicated tables, but it only catches identical blocks that are retried exactly as they were. It does nothing for a row that arrives in two different batches, and nothing for updates. You still need a real plan.

ReplacingMergeTree: the right engine, with a catch

The standard answer is ReplacingMergeTree. You give it a sorting key that matches the source primary key and, ideally, a version column. When ClickHouse merges data parts in the background, it keeps only the row with the highest version for each key. Newer versions also support an is_deleted column so delete events from Debezium can remove the row during merges instead of leaving a tombstone around forever.

The catch is in the word "merges". Background merges happen when ClickHouse decides to run them, not when you insert. Some parts get merged quickly, some sit for a long time, and there is no guarantee that a given key has been collapsed at the moment someone queries it. Two more details catch people out:

  1. Merges never cross partitions. If two versions of the same key land in different partitions, they will never be merged together. The partition key has to keep every version of a record in the same partition, or dedup simply does not happen.
  2. The version column has to be truly ordered. A source timestamp in seconds can tie when a row is updated twice in quick succession, and then the "winner" is whichever row the merge happens to keep. A version derived from the binlog position or the log sequence number orders changes the way the source applied them.

So ReplacingMergeTree makes duplicates temporary. It does not make them invisible.

Why FINAL on every query does not scale

FINAL tells ClickHouse to do the merge logic at query time: read every candidate part, compare versions per key, and return only the winners. On a small table that is fine. On a large one it is a lot of extra reading and comparing on every single query, and the cost grows with the table, not with the slice the user asked for.

ClickHouse has made FINAL cheaper over the years, and if your tables are modest it may be all you need. On the very large CDC tables I work with, it is too heavy to rely on, especially behind dashboards that fire many queries at once. Paying the dedup cost on every read is paying for the same work again and again.

The same goes for running OPTIMIZE TABLE ... FINAL on the whole table whenever someone complains. It rewrites everything, it competes with inserts and normal merges for disk and CPU, and on a big table it can run for a long time.

What I do instead: a scheduled dedup of yesterday's partition

The approach that has held up for me is simple: do the expensive dedup work once, on a bounded piece of data, on a schedule, and keep queries cheap.

  1. Partition by day on a column that does not change for a given record, so every version of a row lands in the same daily partition.
  2. Let the stream write freely into the current day. Duplicates are allowed to exist there for a while.
  3. Once a day, dedup the previous day's partition (D-1) after it has stopped receiving late events. That is a bounded job: one partition, not the whole table. Depending on the table it is either a targeted optimize on that partition or a rebuild of the partition with only the latest version per key, swapped in when it is complete.
  4. Verify before you trust it. After the job, check that row count equals distinct key count for that partition. If it does not, the job flags it instead of silently moving on.

The result is that everything older than today is clean and cheap to query with no FINAL, and the cost of dedup is a predictable daily job instead of a tax on every query.

This fits event-style and append-heavy CDC tables best, where a record's partition does not move. For tables where the same record keeps changing for months, like a customer or account table, I usually keep a separate current-state table that is small enough to collapse differently, rather than forcing it into the same pattern.

Handling today's data until the job runs

Between dedup runs, the current partition can still contain more than one version of a key. Most reports do not care, because they read closed days. For the ones that need today, there are two honest options:

  1. Collapse at query time only over the recent window, for example with argMax(column, version) grouped by key, or LIMIT 1 BY key after ordering by version. Because it only touches today's partition, it stays cheap.
  2. Expose a view that reads clean history directly and applies the collapse only to the current day, so analysts do not have to remember which is which.

What I avoid is leaving it to each analyst to remember whether a table is deduped. One view, documented once, saves a lot of wrong numbers.

Deletes need their own plan

Debezium emits a delete event and, depending on configuration, a tombstone. If you ignore deletes, the warehouse keeps rows the source no longer has, and your counts drift upward over time. I carry the operation type through as a column, mark deletes explicitly, and make the dedup job and the query-time collapse both respect it. Whether deleted rows are physically removed or kept with a flag is a business choice; what matters is that it is decided, not accidental.

How to tell if your dedup is actually working

A few checks I run on any CDC table in ClickHouse:

  1. Per partition, compare count() with uniqExact(key). Closed partitions should match exactly.
  2. Compare daily distinct keys against the source for the same window. If the warehouse has fewer, you are losing data; if it has more, deletes or keys are wrong.
  3. Spot-check a few keys that were updated many times and confirm the surviving row has the latest values from the source.
  4. Watch the number of active parts per partition. A partition that keeps growing in parts is a sign merges are falling behind.

If your counts already do not match and you are not sure whether it is duplicates or missing rows, I wrote up the usual causes in why your CDC row counts don't match. My free reconciliation SQL generator writes the source-versus-target comparison queries for you, so you can see which side is off before changing anything.

Design it in from the start

Most of the pain comes from choices made in the first week: a partition key that splits versions of the same row, a version column that ties, deletes that are dropped on the floor. Those are cheap to get right on day one and expensive to fix once the table holds years of history. If you are still planning the pipeline, the Kafka CDC sizing calculator helps with the partitions, throughput and retention side.

When to get help

If you already have duplicates in production and slow FINAL queries behind your dashboards, my pipeline health audit looks at your table engines, partition and version keys, delete handling and dedup jobs, and gives you a written, prioritized list of fixes. If you are building the pipeline from scratch, the real-time CDC pipeline package covers MySQL or Postgres through Debezium and Kafka into ClickHouse, with dedup and reconciliation designed in from the start.

Duplicates in a CDC pipeline are normal. Paying to hide them on every query is a choice, and usually not the best one.

Check your source and target counts

Free reconciliation SQL generator. Runs in your browser, nothing is sent anywhere.

Open the generator
Who does the work

One senior engineer, start to finish

I'm Danish Rajpoot (Muhammad Danish Ishfaq), a data architect and principal data engineer with nearly 9 years on data platforms and a master's in computer science from the University of Eastern Finland. I do the work myself and write the handover so your team can run it without me.

Duplicates in your ClickHouse tables?

Send me the table engine, sorting key and partition key of one problem table. I will tell you where I would look first.

A short note is enough: what you have, what is going wrong, and when you need it.

CDC dedupfree reconciliation SQLOpen