Deduplicate Late-Arriving CDC Rows with MERGE: A Worked Problem
A CDC feed sends duplicates and out-of-order changes. Build a MERGE that keeps the latest row per key, ignores late events and is safe to replay.
TL;DR
- Late and duplicate CDC rows need two defences: pick one row per key inside each batch, then only let a change win if it's newer than what the target already has.
- Order by the source's sequence (LSN, SCN, Kafka offset per key,
_commit_version), never by arrival time. - Deletes must leave a tombstone that keeps the sequence number. A hard delete lets a late update bring the row back.
- Break ties deterministically, and test the two properties that matter: replaying a batch changes nothing, and a late older row changes nothing.
The problem statement
NorthBridge replicates the customers table from its CRM's database into Databricks using a log-based CDC tool. Each event lands in bronze.crm_customer_cdc with:
| Column | Meaning |
|---|---|
customer_id |
Primary key in the CRM |
op |
I, U or D |
lsn |
Log sequence number from the source database: strictly increasing per commit |
full_name, email, city |
After-image of the row (empty for deletes) |
ingested_at |
When the event landed in bronze |
The feed is at-least-once and not ordered across batches. A network retry can deliver the same event twice; a slow partition can deliver an event an hour after newer events for the same customer.
Task: maintain silver.customers with exactly one row per customer reflecting the latest change by lsn. Replaying any batch must leave the table unchanged. Deleted customers must stay deleted even if an older update arrives later.
Try it before reading on.
Test data
-- Databricks Runtime 16.4 LTS+, Unity Catalog
CREATE OR REPLACE TEMP VIEW batch_42 AS
SELECT * FROM VALUES
('C7', 'U', 105, 'Priya R', 'priya@ex.com', 'Pune', TIMESTAMP'2026-11-13 10:05:00'),
('C7', 'U', 103, 'Priya R', 'priya@ex.com', 'Goa', TIMESTAMP'2026-11-13 10:05:00'),
('C7', 'U', 105, 'Priya R', 'priya@ex.com', 'Pune', TIMESTAMP'2026-11-13 10:05:01'), -- duplicate
('C9', 'D', 88, NULL, NULL, NULL, TIMESTAMP'2026-11-13 10:05:00'),
('C4', 'I', 61, 'Arun K', 'arun@ex.com', 'Madurai', TIMESTAMP'2026-11-13 10:05:00')
AS t(customer_id, op, lsn, full_name, email, city, ingested_at);
CREATE OR REPLACE TEMP VIEW batch_43 AS
SELECT * FROM VALUES
('C7', 'U', 104, 'Priya R', 'priya@ex.com', 'Ooty', TIMESTAMP'2026-11-13 10:20:00'), -- late, older
('C9', 'U', 80, 'Vikram S', 'vik@ex.com', 'Agra', TIMESTAMP'2026-11-13 10:20:00') -- late, before the delete
AS t(customer_id, op, lsn, full_name, email, city, ingested_at);Expected after both batches: C7 in Pune (lsn 105), C9 deleted (lsn 88), C4 in Madurai (lsn 61). The Ooty and Agra rows must have no effect.
Defence one works inside the batch. Defence two works against the target.
Hints
- What does
MERGEdo if two source rows match one target row? - Which column can tell you that an event is older than what's already stored?
- If C9 is physically deleted, what does the Agra update find when it arrives?
Solution
Step 1 — The target keeps the sequence and a tombstone
CREATE TABLE IF NOT EXISTS northbridge.silver.customers (
customer_id STRING NOT NULL,
full_name STRING,
email STRING,
city STRING,
lsn BIGINT NOT NULL, -- last applied change
is_deleted BOOLEAN NOT NULL,
updated_at TIMESTAMP
)
CLUSTER BY (customer_id);lsn on the target is what makes defence two possible. Without it, the target has no memory of how new its data is.
Step 2 — Dedupe inside the batch
CREATE OR REPLACE TEMP VIEW batch_dedup AS
SELECT *
FROM batch_42
QUALIFY ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY lsn DESC,
CASE op WHEN 'D' THEN 0 WHEN 'U' THEN 1 ELSE 2 END, -- tie-break
ingested_at DESC
) = 1;This collapses C7's three rows to the lsn 105 row and removes the exact duplicate. The tie-break matters when two events share an lsn (it happens with some CDC tools when one transaction touches a row twice). A delete winning ties is the safe default.
dropDuplicates(["customer_id"]) is not a substitute: it keeps an arbitrary row.
Step 3 — MERGE with a sequence guard
MERGE INTO northbridge.silver.customers AS t
USING batch_dedup AS s
ON t.customer_id = s.customer_id
-- Newer delete: keep a tombstone
WHEN MATCHED AND s.lsn > t.lsn AND s.op = 'D' THEN UPDATE SET
t.is_deleted = true,
t.lsn = s.lsn,
t.updated_at = s.ingested_at
-- Newer insert or update
WHEN MATCHED AND s.lsn > t.lsn THEN UPDATE SET
t.full_name = s.full_name,
t.email = s.email,
t.city = s.city,
t.is_deleted = false,
t.lsn = s.lsn,
t.updated_at = s.ingested_at
-- First time we see this key (including a delete for a key we never saw)
WHEN NOT MATCHED THEN INSERT
(customer_id, full_name, email, city, lsn, is_deleted, updated_at)
VALUES
(s.customer_id, s.full_name, s.email, s.city, s.lsn, s.op = 'D', s.ingested_at);Walk through it:
- Batch 42. C7 lsn 105 inserts as Pune. C9's delete arrives for a key the target hasn't seen, so it inserts a tombstone with lsn 88. C4 inserts.
- Batch 43. C7 lsn 104 matches, but
104 > 105is false, so neither matched clause fires. Ooty is ignored. C9 lsn 80 matches the tombstone,80 > 88is false, ignored. Agra never resurrects.
Inserting a tombstone for an unseen delete looks odd, but it's what protects you when the delete overtakes the original insert.
Step 4 — Expose a clean view
CREATE OR REPLACE VIEW northbridge.silver.customers_current AS
SELECT customer_id, full_name, email, city, updated_at
FROM northbridge.silver.customers
WHERE NOT is_deleted;Consumers read the view. The tombstones stay in the table as long as late events can still arrive.
Step 5 — The PySpark version, for streaming
# Databricks Runtime 16.4 LTS+, PySpark, delta-spark
from delta.tables import DeltaTable
from pyspark.sql import functions as F, Window
target = DeltaTable.forName(spark, "northbridge.silver.customers")
def apply_cdc(batch_df, batch_id):
op_rank = F.when(F.col("op") == "D", 0).when(F.col("op") == "U", 1).otherwise(2)
w = Window.partitionBy("customer_id").orderBy(F.col("lsn").desc(), op_rank, F.col("ingested_at").desc())
dedup = (batch_df.withColumn("_rn", F.row_number().over(w))
.filter("_rn = 1").drop("_rn"))
(target.alias("t")
.merge(dedup.alias("s"), "t.customer_id = s.customer_id")
.whenMatchedUpdate(
condition="s.lsn > t.lsn AND s.op = 'D'",
set={"is_deleted": "true", "lsn": "s.lsn", "updated_at": "s.ingested_at"})
.whenMatchedUpdate(
condition="s.lsn > t.lsn",
set={"full_name": "s.full_name", "email": "s.email", "city": "s.city",
"is_deleted": "false", "lsn": "s.lsn", "updated_at": "s.ingested_at"})
.whenNotMatchedInsert(values={
"customer_id": "s.customer_id", "full_name": "s.full_name",
"email": "s.email", "city": "s.city", "lsn": "s.lsn",
"is_deleted": "s.op = 'D'", "updated_at": "s.ingested_at"})
.execute())
(spark.readStream.table("northbridge.bronze.crm_customer_cdc")
.writeStream
.foreachBatch(apply_cdc)
.option("checkpointLocation", "/Volumes/northbridge/chk/silver_customers")
.trigger(availableNow=True)
.start())foreachBatch gives at-least-once delivery into the function. If a batch fails after the MERGE commits but before the checkpoint updates, the batch runs again. That's exactly why the MERGE must be idempotent.
Step 6 — Prove it
-- 1. One row per key
SELECT customer_id FROM northbridge.silver.customers
GROUP BY customer_id HAVING COUNT(*) > 1;
-- 2. Replay test: run batch 42 again, then compare to the previous version
SELECT * FROM northbridge.silver.customers
EXCEPT ALL
SELECT * FROM northbridge.silver.customers VERSION AS OF 1; -- version before the replayBoth should return zero rows. Even better, check DESCRIBE HISTORY: the replayed MERGE should show numTargetRowsUpdated = 0 and numTargetRowsInserted = 0.
Variations an interviewer will ask about
"There's no LSN, only an updated_at from the source." Use it, but ask how precise it is. Two changes in the same second tie, and clocks on different source servers drift. Combine it with a tie-breaker, and say out loud that this is weaker than a log sequence.
"Tombstones grow forever." Purge them once late events can no longer arrive: DELETE FROM silver.customers WHERE is_deleted AND updated_at < current_date() - INTERVAL 30 DAYS. The window must be longer than the worst lateness you've measured.
"I need every intermediate version, not just the latest." Then this isn't a dedupe, it's SCD Type 2. See SCD Type 2 with Delta MERGE, or use AUTO CDC ... STORED AS SCD TYPE 2 with SEQUENCE BY lsn in Lakeflow Spark Declarative Pipelines.
"Could AUTO CDC do this whole article?" Yes. AUTO CDC INTO ... KEYS (customer_id) SEQUENCE BY lsn APPLY AS DELETE WHEN op = 'D' handles ordering, duplicates and delete tracking. Hand-writing it is still worth doing once, because you'll need to debug it.
From production: gotchas and lessons
-
Symptom: Deleted customers reappeared a day later with stale data. Cause: The original pipeline used
WHEN MATCHED AND op = 'D' THEN DELETE. A late update found no row and inserted it. Fix: Tombstones with the sequence number, purged only after the lateness window. -
Symptom: The dedupe kept different rows on different runs of the same batch. Cause: Two events had the same
lsnand no tie-break, soROW_NUMBER()picked arbitrarily. Fix: Deterministic tie-breaks in the windowORDER BY. -
Symptom: After a source database migration, every change was ignored. Cause: The new database's LSNs restarted from a lower number. Fix: Store a composite sequence (
source_epoch,lsn) and compare both. Any sequence-based design needs a plan for the sequence resetting.
Performance and cost notes
Clustering on customer_id keeps each MERGE to the files that contain the incoming keys. Ignored late rows still cost a lookup but no rewrite. With deletion vectors on, matched updates mark rows instead of rewriting files, which matters for frequent small CDC batches.
When not to use this
If the source can give you a full snapshot cheaply and the table is small, a snapshot comparison (MERGE with WHEN NOT MATCHED BY SOURCE) is simpler. And if you're already in a declarative pipeline, prefer AUTO CDC.
Checklist
- Target stores the last applied sequence per key
- In-batch dedupe with a deterministic tie-break
- Every matched clause guarded by
s.seq > t.seq - Deletes are tombstones, including deletes for unseen keys
- Tombstone purge window longer than measured lateness
- Replay test and late-row test run in CI
Practice
- Try: Delta Lake Interview Questions: 25 Scenario Problems
- Try: PySpark Interview Questions: 50 Coding and Scenario Problems
- Extend it: add a batch 44 where C9 is re-inserted with lsn 120. What should happen, and does the
MERGEdo it?
Further reading
Keep going
Delta Lake MERGE: Five Upsert Patterns and How to Make Them Fast
The five Delta MERGE patterns (upsert, insert-only, newer-wins, deletes, full sync), the errors that break them, and how to make them fast.
Delta Change Data Feed: CDC Downstream Without Extra Tooling
Enable Change Data Feed and read row-level inserts, updates and deletes by version to refresh downstream Delta tables incrementally.
Handling Late-Arriving Dimensions and Facts in a Lakehouse
Facts that show up before their customer exists, and facts that show up weeks after the event. Inferred members, point-in-time joins and re-keying jobs on Delta Lake, with the trade-offs of each.
One practical note a week
Get new articles, problems and guides in your inbox.
Thanks! You're on the list. (Local demo — no email provider is wired up yet.)