Idempotent At-Least-Once Ingest

Concepts covered: Idempotency

Every ingestion consumer does 2 things per batch, whatever it reads from: it writes the records to the sink, and it saves its position (an offset for a queue, an LSN for a replication slot, a file name when it reads a folder of files) so it can resume after a restart. A crash can land between the 2 steps, and their order decides what that crash costs.

Write, then save position
  • Crash in between: the batch is read again
  • Cost: duplicate records in the sink
  • Called at-least-once delivery
Save position, then write
  • Crash in between: the batch is never written
  • Cost: records silently missing
  • Called at-most-once delivery

Ingestion picks at-least-once, because a duplicate can be found and removed while a missing record leaves no trace. A restarted CDC connector rereads changes after its last confirmed LSN, a queue redelivers anything unacknowledged, and a retried API page returns rows already loaded. The sink can turn each of these repeats into a no-op in 3 ways.

Dedupe by key

When each record carries a stable id, keep a single row per id. A queue event usually has a producer-assigned event_id. A CDC change is identified by its primary key plus its LSN: a replay repeats both, while 2 real updates to order 1001 have different LSNs. Dedupe each staged batch before it touches the target.

LSNs appear here as small integers. Real ones are 64-bit log positions that Postgres prints as 2 hex numbers, such as 0/16B3748.

SELECT
  order_id,
  lsn,
  op,
  total
FROM (
  SELECT
    order_id,
    lsn,
    op,
    total,
    ROW_NUMBER() OVER (PARTITION BY order_id, lsn ORDER BY received_at) AS rn
  FROM staged_order_changes
) AS ranked
WHERE rn = 1

Uniqueness enforced at the sink

Staging dedupe only catches repeats inside a batch. A replay that arrives tomorrow lands in a different batch, so the lasting guarantee has to live in the target: a uniqueness rule on the record id that rejects or skips a second copy. An operational database enforces it with a primary key or unique index. Many warehouses accept a primary key declaration without enforcing it, so the load enforces it with an anti-join against rows already stored.

INSERT INTO order_changes
SELECT
  s.order_id,
  s.lsn,
  s.op,
  s.total
FROM deduped_order_changes AS s
LEFT JOIN order_changes AS t
  ON s.order_id = t.order_id
  AND s.lsn = t.lsn
WHERE t.order_id IS NULL

A current-state table, with a row per order, also needs a version rule: upsert by order_id, and apply a change only when its LSN is higher than the stored one. A replay of the 10:03 change (total 13000) arriving after the 10:08 change (total 13500) compares lower and is skipped, so the replica keeps 13500 instead of rolling back. Apply a delete as a tombstone, a row flagged deleted that keeps the delete's LSN; otherwise a late replay of an older update to 1002 finds no stored row and revives the order. Purge tombstones once replays can no longer arrive.

Content-hash ids

Some sources give you no id: a partner's daily CSV, an API that returns rows without keys. Build one by hashing the fields that make a record what it is. The same input then always produces the same id, on the first load and on every retry, and the sink's uniqueness rule does the rest.

SELECT
  to_hex(sha256(to_utf8(concat(file_name, '|', CAST(line_number AS VARCHAR), '|', raw_line)))) AS row_id,
  file_name,
  line_number,
  raw_line
FROM staged_partner_files

Include whatever differs between 2 genuinely different records, and nothing that differs between 2 deliveries of the same record.

Hash inputSame file retried2 identical purchases on different linesVerdict
`raw_line`Same idSame id, a purchase lostToo few inputs
`raw_line` + `ingested_at`New id, duplicate loadedDifferent idsToo many inputs
`file_name` + `line_number` + `raw_line`Same idDifferent idsRight

The third row holds while the partner never resends a file under the same name with its lines reordered. If they do, ask them for a row id.

A consumer reads a queue, writes each batch to the warehouse with an anti-join on event_id, then acknowledges the batch. A teammate proposes acknowledging before the write to stop redeliveries. What does the change do?

About this lesson

This section is part of the Ingestion Patterns: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.