Idempotent Reruns: Intermediate
Partition overwrite
Use it when the destination is partitioned by the same column that scopes the run, usually a date column ds, and each run computes the full contents of a single partition. The write swaps the old partition for the new one as a unit. The run for ds = '2026-03-14' produces 41,200 rows. A retry produces the same 41,200 rows and installs them in place of the first attempt's. Every other partition stays as it was.
MERGE on a key
Use it when the destination holds a row per entity and those rows change over time, such as dim_listing with a row per listing_id. The run's unit is the set of listings that changed. MERGE joins incoming rows to the table on the key. A matched key updates its row, and an unmatched key inserts a new row. Replaying the same 500 changes leaves the table identical, for 2 reasons. Setting a column to the value it already holds changes nothing. And every key now exists, so no insert fires.
An hourly job reads the bookings that changed in the last hour. It writes them to fact_bookings, which is partitioned by ds, using partition overwrite. What does each run do to the partitions it touches?
DELETE-then-INSERT
Use it when a run owns a set of rows you can name with a predicate, but that set does not line up with a partition. fact_payouts is partitioned by payout_month because readers query by month, while the pipeline runs daily. Overwriting the March partition from a daily run would erase the other 30 days of March. Instead, the run deletes the rows it owns, those whose payout_date is its day, and inserts the recomputed rows. A retry deletes the same set, including anything the failed attempt left behind, and inserts it again.
Two conditions keep it safe. First, the DELETE predicate and the INSERT filter must name the same rows. Say the delete matches on payout_date, the insert on created_at, and a payout is created March 14, dated March 15. Every run of March 14 inserts another copy its delete never matches. The March 15 run deletes every copy, inserts none back, and the payout vanishes. Second, a failure between the 2 statements leaves March 14 empty until the rerun, which the last section addresses.
| Pattern | Destination shape | Unit of work | Cost per run | Breaks when |
|---|---|---|---|---|
| Partition overwrite | Partitioned by the run's date | A complete partition | Rewrites the whole partition | The run holds part of a partition |
| MERGE | A row per entity key | Changed rows | Joins batch to target | The key repeats in source or target |
| DELETE-then-INSERT | Partitioned coarser than the run, or not at all | Rows matching a predicate | Delete scan plus insert | Delete and insert filters disagree |
A daily run computes a day's host earnings. host_earnings holds a row per host per day and is partitioned by earnings_month. Which write keeps a rerun of a single day idempotent?
| Key kind | Example | Origin | Safe for MERGE when |
|---|---|---|---|
| Natural | `booking_code` | Assigned by the booking app | The source never reuses or reassigns it |
| Surrogate | `booking_key` | Generated by the pipeline | It is computed from the natural key the same way on every run |
| Composite | (`booking_code`, `night_date`) | Several source columns together | The set names a single row at the table's grain |
Natural keys
Surrogate keys
A surrogate key is a value the pipeline assigns. Pipelines often use one to replace a long string or to join several sources under a single ID. It goes wrong when the pipeline generates it fresh on each run. If the job calls uuid() and merges on the result, every retry produces keys the table has never seen. Nothing matches, and every row is inserted again.
| booking_key | booking_code | amount_usd |
|---|---|---|
| 9f2c41 | HMX41 | 212.00 |
| c71a08 | HMX42 | 95.50 |
| booking_key | booking_code | amount_usd |
|---|---|---|
| 9f2c41 | HMX41 | 212.00 |
| c71a08 | HMX42 | 95.50 |
| 3be9d2 | HMX41 | 212.00 |
| e0457f | HMX42 | 95.50 |
The fix is a deterministic surrogate: a hash of the natural key. The same booking_code hashes to the same value on every run, so retries and later recomputations land on the rows they already wrote.
Composite keys
When a single column cannot name a row, combine several. A table of booked nights holds a row per booking per night. A 3-night stay therefore has 3 rows sharing booking_code, and the key is (booking_code, night_date). Getting the set wrong in either direction makes reruns misbehave. With too few columns, distinct rows collapse onto a single row, and each one overwrites the last. With too many, such as adding updated_at, every change to a booking looks like a new row, and the table grows with every edit.
Enforcing uniqueness
The second sort column matters. If 2 copies share an updated_at, ordering by that column alone leaves the choice to the engine, and the winner can differ between runs. ingest_offset differs between the copies, so the same row wins every time.
The staging batch holds 2 rows for booking HMX42. They were emitted within the same second, with equal updated_at and different amount_usd. The dedupe orders by updated_at DESC only. What can a rerun do?
- Merge on a key that exists in the source before the pipeline touches it
- Hash the natural key when a surrogate is needed
- Deduplicate the batch with a tie-breaking second sort column
- Merge on a uuid() or sequence generated during the run
- Put changing columns like updated_at in the key
- Key on values a person can edit, such as email
dim_booking should hold a row per booking. Its MERGE matches on (booking_code, updated_at). A booking is created on Monday and edited 3 times later that week. How many rows does that booking have by Sunday?
- ▸
current_date,now()orcurrent_timestampanywhere in a filter, join or computed column - ▸Reading the newest file in a folder instead of the file for the run's date
- ▸Joining a dimension as it looks today when the run describes a past day
- ▸A
processed_atcolumn stamped by the run, if any reader depends on its value
This job writes yesterday's bookings per listing into a ds partition. It always reads whole days, yet a recomputation of last month comes out wrong. Which change fixes it?
Event time and processing time
| booking_code | booked_at (event) | landed_at (processing) | Day by event time | Day by processing time |
|---|---|---|---|---|
| HMX41 | 2026-03-14 10:12 | 2026-03-14 10:12 | March 14 | March 14 |
| HMX57 | 2026-03-14 23:58 | 2026-03-15 00:07 | March 14 | March 15 |
| HMX63 | 2026-03-14 18:30 | 2026-03-15 06:45 | March 14 | March 15 |
A report of bookings made on March 14 means event time, so it groups on booked_at. Grouping on landed_at would credit HMX57 and HMX63 to March 15, and the totals would shift with every slow export. Selecting rows is a second choice. Event-time bounds, as in the query above, read March 14's raw rows, late arrivals included. landed_at bounds read only rows new since the last run, but those can span several event days, so the run must rewrite each event-time partition they touch.
booked_at and landed_at, and never use a bare ts or timestamp. A reader of the query should see which kind of time each filter uses without opening the source documentation.Finance asks for the number of bookings made per day. A transform groups by date(landed_at). On the night an upstream export runs 6 hours late, what happens to the totals?
A backfill runs the pipeline for a range of past logical dates. Two reasons start most backfills: a gap where runs never happened, and a logic fix that makes past output wrong. Take the second. A currency conversion bug inflated agg_daily_revenue for every day from 2026-01-01 through 2026-03-31. After the fix ships, those 90 logical dates have to run again with the corrected code.
The range expands into 90 runs, one per logical date. Each run replaces its own partition, and 8 runs execute at a time.
Why only idempotent pipelines survive it
| Flaw in the pipeline | What the 90-day backfill leaves behind |
|---|---|
| Appends instead of replacing | Every day holds the old inflated rows plus the corrected rows, more than twice the true revenue |
| Filters relative to the clock | Each run reads the 24 hours before its start, so 90 partitions hold overlapping recent slices |
| Merges on a `uuid()` key | Every row is inserted again under a new key, next to its old copy |
| DELETE and INSERT filters disagree | Rows the delete misses survive, so old values linger beside new values |
| Idempotent writes, explicit time bounds, unique keys | Each partition is replaced with its corrected contents, and nothing else changes |
A pipeline reads the 24 hours before current_timestamp and writes into its run's ds partition by partition overwrite. In June, it backfills 2026-01-01 to 2026-03-31. What do the 90 partitions hold afterwards?
Order and parallelism
Before starting the range
- ▸Confirm every table the run writes uses one of the 3 replace patterns
- ▸Search the code for
current_date,now()andcurrent_timestamp - ▸Check that the raw data for the whole range still exists and has not aged out
- ▸Run a single day, compare it with the old output, then launch the rest
- ▸List the tables built from
agg_daily_revenue, because they need the same range rerun afterwards - ▸Tell the dashboard's readers which dates will change and when
guest_lifetime_value for day N adds day N's spend to the value stored for day N-1. You backfill January after a fix. How should the 31 runs execute?
The nightly run for ds = '2026-03-14' writes 3 tables in order: fact_bookings, then agg_daily_revenue built from it, then host_payout_summary built from both. At 02:31 the third task fails on a lost connection. The first 2 tables hold fresh March 14 data. The third still holds whatever an earlier attempt for that day left, or nothing.
Each build task replaces the 2026-03-14 partition of the table after it. Build payouts reads both earlier tables, and it's where the run failed.
| Table | After the failure at 02:31 | After the rerun at 06:10 |
|---|---|---|
| fact_bookings | March 14 replaced, 41,200 rows | Replaced again with the same 41,200 rows |
| agg_daily_revenue | March 14 replaced | Replaced again with identical totals |
| host_payout_summary | Earlier contents for March 14 | March 14 replaced for the first time this run |
The window between failure and rerun
Convergence fixes the end state. It does nothing for readers between 02:31 and 06:10. A dashboard that joins agg_daily_revenue to host_payout_summary shows corrected revenue next to stale payouts, and an analyst who exports it at 05:00 ships numbers that never existed together. Publishing last or writing a completion marker closes that window.
Publish last
A completion marker
The run's last task writes a row to run_status saying March 14 is complete. It uses MERGE on ds, so a rerun updates that row instead of adding a second one. Downstream jobs wait for the row, and readers filter on it. On a rerun or backfill, the marker already says complete from the earlier success, so the rerun's first task must set it to running before touching any table. Otherwise readers trust March 14 while its tables change underneath them.
A run builds 3 tables in staging, publishes them by partition overwrite, and then writes the complete marker. On the day's first run, the publish succeeds for 2 tables and fails on the third. What do readers who filter on the marker see for that day?
A single appending write breaks the run
The run is idempotent only if every write in it is. A step that appends a row to payout_events on each run, or calls the payments service to pay hosts, turns a safe rerun into duplicate events or double payouts. Key each such write on the logical date and the step, and MERGE on that key. Send that key with each payment call so the service skips repeats. A local log of sent keys leaves a gap: a crash between payment and log write pays the host twice. The advanced lesson builds this out.
A run writes fact_bookings by partition overwrite. It then MERGEs dim_guest on a uuid() generated each run, and finally marks the day complete in run_status. The marker task fails, and the whole run is retried. What is true after the retry succeeds?
> Picture the Airbnb currency fix from the opening. Ninety days, 2026-01-01 through 2026-03-31, of fact_bookings, agg_daily_revenue and host_payout_summary must be recomputed before finance closes the quarter. The engineer first audits each table's write pattern. The audit turns up a uuid() key on a guest table and a current_date in the revenue filter, and the engineer fixes both. Next, they rerun March 14 alone and compare it with the old output. Then they launch the range 8 runs at a time, with publish-last staging and a run_status marker keeping half-finished days off the finance dashboard.
uuid() generated per run duplicates every row on retry.Make every write, read and key give the same answer twice, so retries and backfills repair data.
- Category
- Pipeline Architecture
- Difficulty
- intermediate
- Duration
- 32 minutes
- Challenges
- 10 hands-on challenges
Topics covered: Three Idempotent Write Patterns, Choosing a Business Key, Reads Can Be Non-Idempotent Too, The Backfill Operation, Idempotency Across Several Tables
Lesson Sections
- Three Idempotent Write Patterns
The beginner lesson closed on a single rule: replace, don't append. Which way to replace depends on the destination table's shape: is it partitioned by the column that scopes the run, keyed by an entity ID, or neither? It also depends on a single run's unit of work, which is either a complete day of data or a batch of rows that changed since the previous run. Partition overwrite It is safe only when the run holds the whole partition. Suppose a run carries only the 300 bookings that changed since
- Choosing a Business Key
A MERGE is idempotent only when each incoming row finds the target row that stands for the same real-world thing, or finds nothing. The columns that do the finding are the business key. These are the values that identify a booking, a listing or a guest night, whatever the table's grain is. Natural keys A natural key comes from the source system, so a rerun sees the same value the first run saw. The risk sits in the source: a key that can change or be reused. An email address fails both ways. Gue
- Reads Can Be Non-Idempotent Too
A partition overwrite or a MERGE guarantees that the write replaces. It says nothing about what it replaces the data with. If the query returns different rows when it runs again, the rerun faithfully installs a different answer. A run is idempotent only when its inputs are fixed, and the most common moving input is the clock. The scheduled run starts at 02:00 on March 15 and covers the day leading up to that moment. It fails, and the on-call engineer retries it at 09:40. The retry's window slide
- The Backfill Operation
Why only idempotent pipelines survive it All 90 partitions already hold data from runs that succeeded. A backfill is therefore 90 reruns at once, and every flaw a single retry would expose shows up 90 times. Each earlier section of this lesson predicts a failure. Order and parallelism When each run reads only its own day's inputs and writes only its own partition, the 90 runs are independent. They can run in any order and several at once, limited by the cluster and by the source systems they rea
- Idempotency Across Several Tables
The rerun converges if each table's write is idempotent by itself and scoped to the run's logical date: tables 1 and 2 are replaced with identical contents, and table 3 catches up. Retrying only the failed task also works, provided the tables it reads still hold this run's output. Rerunning the whole run is the safer default whenever an upstream table might have changed in between. The window between failure and rerun Publish last Each task writes to a staging copy of its table, scoped to the ru