CDC into Iceberg: the delete files nobody counted
A change stream landing in an Iceberg table with MERGE INTO works on day one and degrades quietly after that. Three merges added three delete files and 1,120 dead records while the row count barely moved. Here is the accounting, and the job that pays it back.
- The shape of a CDC pipeline
- What three merges cost
- What compaction does, and does not, fix
- Building the merge correctly
- Measuring the debt
- Equality deletes, and why Flink pipelines differ
- A maintenance schedule that keeps up
- Choosing the write mode for a CDC table
- Key takeaways
- References
- Trademarks
TL;DR
- Three
MERGE INTOstatements against a merge-on-read table left 5 data files holding 5,960 records and 3 delete files holding 1,120, for a table that returns 4,840 rows. Nearly a fifth of the stored data records are dead weight the reader filters out.- Every merge adds a delete file. The count grows with the number of merges, not the number of changed rows, so a frequent CDC pipeline accumulates them fastest.
rewrite_data_filescollapsed the data side to 1 file of 4,840 records, the live rows exactly, but 2 delete files survived. Compaction of data is not compaction of deletes.- The
filesmetadata table with itscontentcolumn is the monitor.content = 1growing over time is the early warning.- A CDC table without scheduled maintenance does not fail. It gets slower every hour, with no change in row count to explain it.
The shape of a CDC pipeline
Change data capture lands a stream of row-level events (inserts, updates and deletes) from a source database into a table. The usual path is Debezium reading the database log, Kafka carrying the changes, and a Spark job applying them.
The pipeline, and where the delete files come from.
Most pipelines omit the last step, cleaning up the delete files.
MERGE INTO is the statement that applies a changelog, because it expresses all
three operations against a key in one pass:
MERGE INTO local.db.cdc t USING chg s ON t.id = s.id
WHEN MATCHED AND s.op = 'D' THEN DELETE
WHEN MATCHED THEN UPDATE SET t.v = s.v, t.updated_at = s.updated_at
WHEN NOT MATCHED AND s.op <> 'D' THEN INSERT (id, v, updated_at) VALUES (s.id, s.v, s.updated_at)
That statement is the reason CDC on Iceberg is straightforward to build. Making it safe against replayed batches takes one more condition, shown further down. The measurements below show what it does to the files underneath.
What three merges cost
A merge-on-read table loaded with 5,000 rows, then three changelog batches
applied, each touching 400 rows with a fifth of them deletes. Reading the files
metadata table after each step, where content is 0 for data and 1 for position
deletes:
| After | data files / records | delete files / records | rows the query returns |
|---|---|---|---|
| initial load | 2 / 5,000 | none | 5,000 |
| merge #1 | 3 / 5,320 | 1 / 400 | 4,920 |
| merge #2 | 4 / 5,640 | 2 / 760 | 4,880 |
| merge #3 | 5 / 5,960 | 3 / 1,120 | 4,840 |

In the last row, the table answers queries with 4,840 rows. To do that it stores 5,960 records across five data files, and applies 1,120 delete records across three delete files to filter them down. Roughly 19% of the stored records are dead, and every scan pays to exclude them.
The table shows two patterns.
Data records only ever go up. An update in merge-on-read is a delete plus an insert: the new version is appended, the old one is marked deleted. Nothing shrinks at write time.
Delete files grow per merge, not per row. Merge #1 wrote one delete file, merge #2 a second, merge #3 a third. A pipeline running a merge every minute accumulates 1,440 delete files a day regardless of whether each batch changed ten rows or ten thousand.
That second point is the one that makes CDC different from occasional updates. The cost tracks your trigger interval, not your data volume.
What compaction does, and does not, fix
Running the standard data compaction:
CALL local.system.rewrite_data_files(
table => 'db.cdc',
options => map('min-input-files','2'))
after rewrite_data_files: data=1f/4840r pos-del=2f/960r rows=4840
The data side is now exactly right: one file holding 4,840 records, which is precisely the live row count. The rewrite read the data files, applied the delete files, and wrote out only surviving rows. The 1,120 dead records are gone from the data.
But two delete files remain, holding 960 records. They point at data files the rewrite has replaced, so they no longer delete anything, yet the table still lists them. Iceberg has a separate procedure for delete files, and on this table its defaults do nothing: they rewrote 0 files. It cleared both once told to rewrite everything:
CALL local.system.rewrite_position_delete_files(
table => 'db.cdc',
options => map('rewrite-all','true'))
On Iceberg 1.12.0 compaction can do this in the same call. Adding
'remove-dangling-deletes', 'true' to the rewrite_data_files options removed
both delete files (removed_delete_files_count 2). The same option on 1.11.0
removed none.
The distinction is easy to miss and expensive to miss for a long time. A pipeline
that runs rewrite_data_files nightly and calls it maintenance can still pile up
delete files, so check the delete_files table after the job and do not rely on
its result row.
Add the third job, the one that actually reclaims storage:
CALL local.system.expire_snapshots(table => 'db.cdc', retain_last => 10)
Because none of the above deletes anything from disk. Compaction writes new files and leaves the old ones referenced by older snapshots. That accounting is the subject of Apache Iceberg table maintenance.
Building the merge correctly
The deduplication step is where CDC pipelines go wrong, so here it is in full rather than as a fragment.
from pyspark.sql import functions as F, Window
def apply_changelog(batch_df, batch_id):
# 1. collapse to one row per key, newest wins, using the SOURCE's ordering
# column - never wall-clock arrival time, which reorders under retry.
w = Window.partitionBy("id").orderBy(F.col("log_seq").desc())
latest = (batch_df
.withColumn("rn", F.row_number().over(w))
.filter("rn = 1")
.drop("rn"))
# 2. apply it, never letting an older event overwrite or delete a newer row
latest.createOrReplaceTempView("changes")
batch_df.sparkSession.sql("""
MERGE INTO local.db.cdc t USING changes s ON t.id = s.id
WHEN MATCHED AND s.op = 'D' AND s.log_seq > t.log_seq THEN DELETE
WHEN MATCHED AND s.log_seq > t.log_seq THEN UPDATE SET *
WHEN NOT MATCHED AND s.op <> 'D' THEN INSERT *""")
(stream.writeStream
.foreachBatch(apply_changelog)
.option("checkpointLocation", "/work/ckpt_cdc")
.trigger(availableNow=True)
.start())
Four details in that code matter.
s.log_seq > t.log_seq on both matched clauses protects newer rows from
replay. foreachBatch is at-least-once, so a batch can be applied twice after a
failure. The guard is needed on the delete as much as on the update: without it, a
replayed delete with sequence 10 removes a row already at sequence 20. Storing the
source sequence number in the target is what makes the comparison possible, and it
is worth the column. The guard cannot help once the row is gone, so a replayed
older insert after a delete needs soft deletes (keep the row and flag it) if your
source can redeliver that far back.
Ordering by the source’s log_seq, not by ingestion timestamp. Take it from
the source log position in the change event. Arrival order is not guaranteed to
match it after a retry, and using wall-clock time applies an older version over a
newer one.
Collapsing to one row per key is required for correctness. Two source rows that
match the same target row fail with MERGE_CARDINALITY_VIOLATION. Two source rows
for a key that is not yet in the table do not fail: both are inserted, and the
table silently holds a duplicate key.
WHEN NOT MATCHED AND s.op <> 'D' stops a delete for an unknown key from
inserting a tombstone row.
The match condition has to be the real key. If one source row matches several
target rows, MERGE updates or deletes all of them without an error.
Measuring the debt
One query, on a schedule, tells you whether compaction is keeping up:
SELECT
sum(CASE WHEN content = 0 THEN record_count ELSE 0 END) AS data_records,
sum(CASE WHEN content = 1 THEN record_count ELSE 0 END) AS pos_delete_records,
sum(CASE WHEN content = 2 THEN record_count ELSE 0 END) AS eq_delete_records,
round(100.0 * sum(CASE WHEN content > 0 THEN record_count ELSE 0 END)
/ nullif(sum(CASE WHEN content = 0 THEN record_count ELSE 0 END), 0), 1) AS pct_dead
FROM local.db.cdc.files;
pct_dead compares delete records with data records. It is the share of stored
records that scans filter out only while those delete files still point at live
data: after a compaction, clear the leftover delete files before reading it. On the
measured table it reached 19% after three merges. Two thresholds worth
alerting on: above ~10% sustained means compaction is behind; a value that climbs
every day means it is not running at all.
Pair it with a file-count trend, because record share and file count degrade differently:
SELECT content, count(*) AS files, sum(record_count) AS records
FROM local.db.cdc.files
GROUP BY content;
content = 0 is data, 1 is position deletes, 2 is equality deletes. Many small
delete files hurt even when they hold few records. A delete file count that climbs
across days means compaction is not keeping pace with the merge frequency, and the
fix is usually to compact more often rather than to merge less often. Planning time
that grows while the row count is flat points elsewhere, at snapshot and manifest
accumulation.
Equality deletes, and why Flink pipelines differ
Spark writes position deletes: this file, these row positions. Flink CDC writers commonly write equality deletes: rows where these columns equal these values.
The difference is not academic. A position delete is applied by skipping known offsets in one named file. An equality delete is a predicate the reader must evaluate against every data file in scope with a lower sequence number, because it does not know where the matching rows live.
-- which kind is this table accumulating?
SELECT content, count(*) FROM local.db.cdc.files WHERE content > 0 GROUP BY content;
content = 2 rows are equality deletes. A table mixing both, because two engines
write to it, pays both costs and is the hardest case to reason about. If you
control the topology, pick one writer per table.
A maintenance schedule that keeps up
CDC tables need maintenance proportional to merge frequency, not data volume:
-- hourly: collapse the files the last 60 merges produced
CALL local.system.rewrite_data_files(
table => 'db.cdc',
where => 'updated_at >= current_timestamp() - INTERVAL 2 HOURS',
options => map('min-input-files','5'));
-- daily: clear the delete files, which the above does not
CALL local.system.rewrite_position_delete_files(
table => 'db.cdc',
options => map('rewrite-all','true'));
-- daily: reclaim, with retention equal to your recovery window
CALL local.system.expire_snapshots(table => 'db.cdc', retain_last => 24);
The where clause matters on a CDC table. Rewriting the whole table hourly
costs more than the merges did. Scope compaction to the partitions the merges
actually touched. rewrite-all rewrites every position delete file it is given,
which is why it sits in the daily slot here.
Choosing the write mode for a CDC table
The table above is merge-on-read, which is the usual choice for CDC and worth justifying rather than assuming.
Under copy-on-write, each merge rewrites every data file containing an affected row. A changelog touching 400 scattered keys could rewrite most of the table, every minute. That does not keep up, and it is why CDC pipelines choose merge-on-read.
The trade is the one measured above: writes stay cheap, reads carry the delete files until compaction runs. Set it deliberately, per operation:
CREATE TABLE local.db.cdc (...) USING iceberg
TBLPROPERTIES (
'write.merge.mode' = 'merge-on-read',
'write.delete.mode' = 'merge-on-read',
'write.update.mode' = 'merge-on-read')
The full comparison, with the same DELETE measured under both modes, is in copy-on-write or merge-on-read.
Key takeaways
A CDC pipeline on Iceberg is a debt arrangement. Every merge borrows read performance to keep write latency low, and compaction is the repayment.
The borrowing is automatic and the repayment is not, which is why the failure mode
is a table that works perfectly for a month and then gets slow for no visible
reason. Schedule rewrite_data_files, rewrite_position_delete_files and
expire_snapshots when you build the pipeline, and monitor the delete-to-data
ratio so you find out before your users do.
References
- Iceberg maintenance procedures for
rewrite_data_files,rewrite_position_delete_filesandexpire_snapshots - Iceberg writes with Spark for
MERGE INTOsemantics and its restrictions - Iceberg spec: delete formats for position versus equality deletes
- Copy-on-write or merge-on-read for the mode this pipeline depends on
- Streaming into Iceberg for the trigger that decides how often merges happen
Trademarks
Apache Iceberg, Apache Spark, Apache Flink, Apache Kafka, Apache and the Apache feather logo are either registered trademarks or trademarks of The Apache Software Foundation in the United States and other countries. Debezium is a trademark of Red Hat, Inc.
Found this useful?
These posts and tools are free. If one saved you an afternoon, you can buy me a coffee.
Comments
Questions, corrections and reviews are welcome. Sign in with GitHub to post; comments are stored in this site's public GitHub Discussions.