Skip to content

Lesson 2 of 9 · 26m

Idempotent Pipelines: Designing for the Retry You Know Will Happen

Make rerunning a pipeline safe by using stable keys, atomic publication, deduplication, and explicit upsert semantics.

Every pipeline retried at the wrong time eventually becomes a data corruption machine. A worker dies after writing but before checkpointing. An orchestrator times out even though the task succeeded. A human reruns yesterday's job because the dashboard looks empty. If reruns create duplicates or partial state, the system is not merely flaky; it is untrustworthy. Idempotence means the same logical execution can happen more than once without changing the final correct result.

The mental model

Do not ask "did this task run?" Ask "did this unit of work commit?" A unit of work should be narrow enough to reason about: one partition, one file, one batch, one mutation with a stable key.

better unit   transform events for 2026-03-14 into partition dt=2026-03-14
best unit     same input, deterministic output, staging write, atomic commit

Stage, validate, then publish

For analytical tables, write into staging first, validate it, and publish inside one transaction:

BEGIN;
DELETE FROM analytics.orders
WHERE dt = DATE '2026-03-14';
INSERT INTO analytics.orders
SELECT *
FROM staging.orders_20260314;
COMMIT;

Use natural keys and upserts

Mutable sinks need a stable identity. In Postgres this often means ON CONFLICT:

INSERT INTO customer_daily_metrics (customer_id, day, revenue, updated_at)
VALUES ($1, $2, $3, now())
ON CONFLICT (customer_id, day)
DO UPDATE SET
  revenue = EXCLUDED.revenue,
  updated_at = now();

Deduplicate at the right boundary

At-least-once delivery means duplicates are normal. Store the delivery identity beside the output or in a ledger:

CREATE TABLE processed_events (
    event_id text PRIMARY KEY,
    processed_at timestamptz NOT NULL DEFAULT now()
);

Side effects are the hard part

Sending email, charging cards, mutating upstream APIs, and emitting downstream events are not automatically idempotent. Require idempotency keys and store them with the workflow state. If the external system cannot deduplicate, isolate the side effect behind a manual gate or a compensating-action design.

Field notes

  • Retrying a non-idempotent job usually makes corruption worse, faster. Do not build automatic retry until write semantics are safe.
  • Delete-and-insert is idempotent only if replacement is atomic or readers tolerate absence. Usually they do not.
  • Window functions and non-deterministic ordering make rerun output drift; pin ordering and input boundaries.
  • Test idempotence by deliberately running the same task twice in CI and comparing row counts, hashes, and downstream effects.

Was this lesson helpful?

Sign in to rate