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.
-- 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.
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.
Comments