At-least-once delivery sent duplicate events. How do you deduplicate cleanly?
Question
Your sink table orders(order_id PRIMARY KEY, status, cents, updated_at) already holds one row:
('ord-1', 'paid', 4000, '2026-12-03T10:05:00Z').
Under Kafka at-least-once delivery, raw_batch arrives with a stale out-of-order retry for ord-1, a duplicate ev-11, and a newer refund for ord-2:
| event_id | order_id | status | cents | updated_at |
|---|---|---|---|---|
ev-10 | ord-1 | pending | 4000 | 2026-12-03T10:01:00Z |
ev-11 | ord-2 | paid | 2500 | 2026-12-03T10:02:00Z |
ev-11 | ord-2 | paid | 2500 | 2026-12-03T10:02:00Z |
ev-12 | ord-2 | refunded | 2500 | 2026-12-03T10:06:00Z |
Write SQL to merge raw_batch into orders deterministically without regressing ord-1, then select all rows ordered by order_id.
Show hints (3)
- "COLLAPSE BATCH DUPLICATES"
Rank
raw_batchperorder_idwithROW_NUMBER()ordered byupdated_at DESC, event_id DESCand keep onlyrn = 1. - "GUARD STALE UPDATES"
Use
ON CONFLICT(order_id) DO UPDATE SET ... WHERE excluded.updated_at > orders.updated_atsoev-10(10:01) cannot overwrite10:05. - "SEPARATE LOG VS STATE"
For an immutable event log keyed by
event_id,ON CONFLICT(event_id) DO NOTHINGis enough. Mutable order state needs the timestamp guard.
Show checked explanation
First deduplicate raw_batch per order_id with ROW_NUMBER() ordered by updated_at DESC, event_id DESC. Then run INSERT ... ON CONFLICT(order_id) DO UPDATE guarded by WHERE excluded.updated_at > orders.updated_at. That keeps ord-1 at paid, updates ord-2 to refunded, and ignores duplicate ev-11.
WITH dedup AS ( SELECT event_id, order_id, status, cents, updated_at, ROW_NUMBER() OVER ( PARTITION BY order_id ORDER BY updated_at DESC, event_id DESC ) AS rn FROM raw_batch ) INSERT INTO orders (order_id, status, cents, updated_at) SELECT order_id, status, cents, updated_at FROM dedup WHERE rn = 1 ON CONFLICT(order_id) DO UPDATE SET status = excluded.status, cents = excluded.cents, updated_at = excluded.updated_at WHERE excluded.updated_at > orders.updated_at; SELECT order_id, status, cents, updated_at FROM orders ORDER BY order_id;
order_id | status | cents | updated_at ord-1 | paid | 4000 | 2026-12-03T10:05:00Z ord-2 | refunded | 2500 | 2026-12-03T10:06:00Z
Author-checked on SQLite 3.49.1 and CPython 3.12.10: ran the SQL upsert twice for idempotency, tested append-only DO NOTHING deduplication, compared three broken write modes, and simulated streaming state TTL. Checked by an editor other than the author.
Walkthrough
At-least-once delivery prevents lost events when brokers time out or consumers restart before committing offsets. The cost is duplicates and out-of-order retries in the same batch.
Step 1: Collapse duplicates inside the batch. ROW_NUMBER() partitions raw_batch by order_id and picks one winning row per key (ev-10 for ord-1, ev-12 for ord-2), using event_id DESC as a deterministic tiebreaker. Collapsing the batch first also prevents PostgreSQL's ON CONFLICT DO UPDATE command cannot affect row a second time error when one batch contains two rows for ord-2.
Step 2: Protect newer state on conflict. Comparing excluded.updated_at > orders.updated_at blocks stale retry ev-10 (10:01Z) from rolling ord-1 backward from paid (10:05Z) to pending.
| Target table | Key | Right write rule | Why |
|---|---|---|---|
Immutable event_log | event_id | ON CONFLICT(event_id) DO NOTHING | Drops duplicate ev-11; keeps 3 unique events |
Mutable orders state | order_id | ROW_NUMBER() + guarded DO UPDATE | Keeps newest status; blocks stale ev-10 |
| Streaming deduplicator | event_id + TTL | Bounded state store (for example 24 h) | Caps RAM and checkpoint size |
Why streaming deduplication needs a TTL. A Flink or Kafka Streams job cannot keep every event_id in state forever, or state grows until checkpoints fail or nodes OOM. You expire seen IDs after a TTL longer than your retry window, such as 24 hours. Any duplicate arriving after 24 hours passes the stream filter, so the downstream warehouse table still needs an idempotent primary key or guarded upsert.
Common mistakes
- Using an unguarded
ON CONFLICT(order_id) DO UPDATE. Stale retryev-10(10:01Z) overwritesord-1frompaidback topending. - Using
ON CONFLICT(order_id) DO NOTHINGon a mutable state table. Onceev-11(paid) insertsord-2, the laterev-12(refunded) is silently dropped. - Skipping
ROW_NUMBER()beforeINSERT ... ON CONFLICT DO UPDATE. In PostgreSQL, two rows with the sameorder_idin one batch abort the whole statement. - Omitting a TTL on a streaming dedup operator. Unbounded key state grows forever and eventually breaks checkpoints or memory limits.
Follow-up questions
- "Does enabling Kafka idempotent producers remove the need for sink deduplication?" No. Kafka
enable.idempotence=truestops duplicates caused by producer retries within one producer session. Duplicates still arrive if an upstream API retries a checkout, or if a consumer crashes after writing to the sink and before committing its Kafka offset. - "What if two updates for the same order arrive with the exact same
updated_attimestamp?" Add a monotonic source version or sequence column (likeversionorevent_id) and guard with(excluded.updated_at, excluded.event_id) > (orders.updated_at, orders.event_id)so ordering stays deterministic even on timestamp ties. - "How do you pick the streaming deduplication TTL?" Set it above your 99.9th-percentile retry and replay delay (often 24 to 72 hours), check state size (
events_per_day * days * key_bytes), and rely on warehouse primary keys or partition merges for older backfills.
What a strong answer covers
Collapses batch duplicates deterministically with ROW_NUMBER(), guards DO UPDATE with updated_at so stale retries cannot regress state, separates immutable DO NOTHING logs from mutable tables, and explains streaming TTL trade-offs.
Open in interactive practice deck →