Skip to content

Data engineering basics · Part 5 of 10

Idempotent pipelines: safe to run twice

An idempotent pipeline gives the same result no matter how many times you run it. That single property makes retries, backfills and recovery safe.

· 2 min read

data-engineeringreliability

Jobs fail halfway, schedulers retry, and people re-run things to fix a bug. If running a pipeline twice produces duplicate rows or double-counted totals, every one of those events becomes a small disaster.

What idempotent means

An operation is idempotent if doing it once or many times leaves the system in the same state. Setting a value to 5 is idempotent. Adding 1 to a counter is not. A pipeline is idempotent when re-running it for the same input and time window yields the same output, with no leftovers.

Why it matters

  • Retries become safe, so you can set automatic retries without fear.
  • Backfills are trivial: re-run last month and the numbers are replaced, not added.
  • Recovery after a crash needs no manual clean-up.

Pattern 1: overwrite a partition

Write each run's output to a location identified by its time window, and replace that location completely.

SQL
-- Delete the window, then insert it again, in one transaction.
BEGIN;
DELETE FROM daily_sales WHERE sale_date = DATE '2026-01-15';
INSERT INTO daily_sales (sale_date, product_id, total)
SELECT DATE '2026-01-15', product_id, sum(amount)
FROM orders
WHERE created_at >= DATE '2026-01-15' AND created_at < DATE '2026-01-16'
GROUP BY product_id;
COMMIT;

Pattern 2: upsert on a natural key

When rows are identified by a key, merge instead of append. The same input updates the same rows.

SQL
INSERT INTO customers (id, email, updated_at)
VALUES (42, '[email protected]', now())
ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email, updated_at = EXCLUDED.updated_at;

Pattern 3: deterministic inputs. Pass the logical time of the run into the job instead of calling "now" inside it. A run for January 15 should always read January 15 data, even when it executes on January 20.

Things that break idempotency

  • Appending without a key or window.
  • Using random values or the current time inside transformations.
  • Sending an email or calling an external API inside the job without a guard.
  • Reading "the latest" data instead of a fixed window.

Takeaway

Design every job so that its output is a pure function of its inputs and its time window. Then failures stop being emergencies and become a rerun.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.