shuffleet
Home
Practice
Problems
Lessons
Plans
Compete
Challenges
Interviews
Leaderboard
Progress
Skills
Analytics
Submissions
Account
Settings

Idempotent loads and MERGE

Intermediate · 4 min read

In two sentences

A load is idempotent when running it twice leaves the same table as running it once. Jobs get retried, re-run after a fix and backfilled, so a pipeline that isn't idempotent eventually doubles your numbers.

See it

A daily job appends yesterday's orders. It fails after writing, the scheduler retries it:

runapproachrows for 04-01 afterwards
onceINSERT1,000 ✓
retriedINSERT2,000 ✗
retrieddelete 04-01, then insert1,000 ✓
retriedMERGE on order_id1,000 ✓

Appending twice doubles the day; replacing or merging leaves the table as one run did

In SQL

Replace a slice. Rebuild the whole day (or partition) every time:

SQL
DELETE FROM daily_orders WHERE order_date = DATE '2026-04-01';
INSERT INTO daily_orders
SELECT ... FROM orders WHERE CAST(order_ts AS date) = DATE '2026-04-01';

If the job dies between the two statements, the day is empty until the next run, but the next run fixes it.

Merge on a key. Insert new rows, update existing ones:

SQL
MERGE INTO customers t
USING (
  -- one row per key, or MERGE fails: dedup the source first
  SELECT * FROM (
    SELECT *, row_number() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) AS rn
    FROM customer_changes
  ) WHERE rn = 1
) s
ON t.customer_id = s.customer_id
WHEN MATCHED AND s.updated_at > t.updated_at THEN
  UPDATE SET email = s.email, country = s.country, updated_at = s.updated_at
WHEN NOT MATCHED THEN
  INSERT (customer_id, email, country, updated_at)
  VALUES (s.customer_id, s.email, s.country, s.updated_at);

The s.updated_at > t.updated_at condition makes a replay of an old batch harmless: older data never overwrites newer.

When to use it

The scheduler passes a date, the job replaces that date's partition, retries reuse the same date; important tables add write-audit-publish

the table is…make it idempotent by…
small (fits a full rebuild in minutes)rebuilding all of it every run: the simplest idempotence there is
derived and sliced by time (daily aggregates, daily snapshots)replacing the slice: delete the day/partition, insert it again
entities with a key, changes arriving incrementallyMERGE on the key, with a version guard (s.updated_at > t.updated_at)
an append-only event logappending only events whose id isn't there yet (MERGE with WHEN NOT MATCHED only)

Start from the top of the table and go down only when you must: a full rebuild has no edge cases; a MERGE has several.

Best practices

  • Every run takes its date as a parameter (the logical date, as Airflow calls it), never now() or current_date. Then a re-run or a backfill computes exactly what the original run did.
  • Write in units that match the partitions. Replacing one day is cheap and safe when the table is partitioned by day.
  • Carry the version on the target row (updated_at, a version number, a log position) so the guard has something to compare.
  • Test it: run twice, compare. In CI or by hand, run the job twice on the same input and check the table didn't change.
  • For tables people depend on, Write-Audit-Publish: write to a staging branch or table, run the checks, publish only if they pass.
  • On Iceberg, frequent small MERGEs leave delete files behind. Plan compaction (Trino: ALTER TABLE ... EXECUTE optimize).

Common mistakes

  • Several source rows for one key. Trino rejects a MERGE where one target row matches more than one source row. Dedup the source first (Deduplication: the latest record per key).
  • Incremental by "rows after the last timestamp". WHERE updated_at > (SELECT max(updated_at) FROM target) skips rows that share the max timestamp but arrived later. Use >= and let the MERGE absorb the overlap.
  • Using now() inside the job. A re-run tomorrow computes a different result. Pass the run's date in as a parameter.
  • Appending to an aggregate. Late events for 04-01 that arrive on 04-03 must recompute 04-01, not add a second 04-01 row.

What an interviewer asks next

  • "What happens if this runs twice? If it crashes halfway?" Answer both, for your exact query.
  • "How do you backfill last month?" With an idempotent job: run it once per day of last month, in any order.

Go further

Maxime Beauchemin's Functional Data Engineering (the creator of Airflow) is the classic on why batch jobs should be pure functions of their inputs. The PyCon talk covers the same ideas in Python.

Practise it

Upsert Daily Customer Changes (SCD Type 1), then Incremental API Ingestion That Doesn't Skip Records at the Cursor (hard).