download

At-least-once delivery sent duplicate events. How do you deduplicate cleanly?

Data engineering~10 minReviewed 3 Dec 2026Free · No sign-in

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_idorder_idstatuscentsupdated_at
ev-10ord-1pending40002026-12-03T10:01:00Z
ev-11ord-2paid25002026-12-03T10:02:00Z
ev-11ord-2paid25002026-12-03T10:02:00Z
ev-12ord-2refunded25002026-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)
  1. "COLLAPSE BATCH DUPLICATES"

    Rank raw_batch per order_id with ROW_NUMBER() ordered by updated_at DESC, event_id DESC and keep only rn = 1.

  2. "GUARD STALE UPDATES"

    Use ON CONFLICT(order_id) DO UPDATE SET ... WHERE excluded.updated_at > orders.updated_at so ev-10 (10:01) cannot overwrite 10:05.

  3. "SEPARATE LOG VS STATE"

    For an immutable event log keyed by event_id, ON CONFLICT(event_id) DO NOTHING is 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.

"SOLUTION · SQL"
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;
"OUTPUT"
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 tableKeyRight write ruleWhy
Immutable event_logevent_idON CONFLICT(event_id) DO NOTHINGDrops duplicate ev-11; keeps 3 unique events
Mutable orders stateorder_idROW_NUMBER() + guarded DO UPDATEKeeps newest status; blocks stale ev-10
Streaming deduplicatorevent_id + TTLBounded 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 retry ev-10 (10:01Z) overwrites ord-1 from paid back to pending.
  • Using ON CONFLICT(order_id) DO NOTHING on a mutable state table. Once ev-11 (paid) inserts ord-2, the later ev-12 (refunded) is silently dropped.
  • Skipping ROW_NUMBER() before INSERT ... ON CONFLICT DO UPDATE. In PostgreSQL, two rows with the same order_id in 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=true stops 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_at timestamp?" Add a monotonic source version or sequence column (like version or event_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 →

Original OfferVibe question. SQLite: UPSERT · SQLite: Window Functions · PostgreSQL: INSERT ON CONFLICT · Apache Kafka: Message Delivery Semantics.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.