· Markdown version

How to backfill two weeks of bad source data without duplicates (Postgres, dbt, Airflow)

Postgres backfill, MERGE, idempotent load, dbt, Airflow

Treat the backfill window as a unit. For each day (or partition) you re-load, replace everything in that window in one transaction, or use a MERGE that also deletes target rows missing from the corrected source. A plain upsert (INSERT ... ON CONFLICT DO UPDATE) fixes changed rows and adds new ones, but rows that should no longer exist (cancelled orders, test records, rows from a bad extract) stay in the table.

Why backfills create duplicates

  • The load is append-only, so re-running a day inserts it a second time.
  • There is no unique key on the target, so nothing stops a second copy.
  • The re-load uses a different window boundary (dates vs timestamps, UTC vs local), so the old and new loads overlap by a few hours.
  • Downstream aggregates were built from the bad days and are never rebuilt.

Pattern 1: replace the window

This uses DELETE and INSERT, so it does not depend on the Postgres version that added MERGE. Run both statements in one transaction. Use a half-open range (>= start, < end) in both statements so the windows match exactly.

BEGIN;
DELETE FROM orders_daily
WHERE order_date >= DATE '2026-10-03' AND order_date < DATE '2026-10-17';

INSERT INTO orders_daily (order_id, order_date, amount)
SELECT order_id, order_date, amount
FROM stg_orders_corrected
WHERE order_date >= DATE '2026-10-03' AND order_date < DATE '2026-10-17';
COMMIT;

Checked on Postgres 17, and the same statements on Postgres 15: a changed row is updated, a new source row is inserted, rows the corrected source dropped are gone, and rows outside the window stay. Source rows outside the window are not inserted. Running it a second time leaves the same rows.

Pattern 2: MERGE with delete (Postgres 17+)

MERGE arrived in Postgres 15. WHEN NOT MATCHED BY SOURCE, WHEN NOT MATCHED BY TARGET, RETURNING, and merge_action() are PostgreSQL 17. Scope the delete to the backfill window. Without that date predicate, a target row outside the source is NOT MATCHED BY SOURCE and would be deleted too.

MERGE INTO orders_daily t
USING (SELECT * FROM stg_orders_corrected
       WHERE order_date >= DATE '2026-10-03' AND order_date < DATE '2026-10-17') s
  ON t.order_id = s.order_id
WHEN MATCHED AND (t.order_date, t.amount) IS DISTINCT FROM (s.order_date, s.amount) THEN
  UPDATE SET order_date = s.order_date, amount = s.amount
WHEN NOT MATCHED BY TARGET THEN
  INSERT (order_id, order_date, amount) VALUES (s.order_id, s.order_date, s.amount)
WHEN NOT MATCHED BY SOURCE
  AND t.order_date >= DATE '2026-10-03' AND t.order_date < DATE '2026-10-17' THEN
  DELETE
RETURNING merge_action(), t.order_id;

On Postgres 17 this ends in the same rows as Pattern 1. RETURNING reports UPDATE, DELETE, and INSERT for the rows that changed. Running it again changes nothing (MERGE 0). Unchanged matches are skipped by the IS DISTINCT FROM predicate, so a retry does not rewrite them.

On Postgres 15 and 16 the statement above is a syntax error at the first BY: syntax error at or near "BY" on WHEN NOT MATCHED BY TARGET. WHEN NOT MATCHED BY SOURCE fails the same way. A MERGE that only adds RETURNING or merge_action(), with no BY clause, fails with syntax error at or near "RETURNING". Plain WHEN MATCHED and WHEN NOT MATCHED (no BY, no RETURNING) does run on 15 and 16. It still cannot delete a target row the corrected source dropped. Use Pattern 1 on those versions.

Pattern 3: upsert, and when it is enough

INSERT ... ON CONFLICT (order_id) DO UPDATE needs a unique index or constraint on the key. It is safe for retries of the same data. It is not enough when the corrected source dropped rows.

INSERT INTO orders_daily (order_id, order_date, amount)
SELECT order_id, order_date, amount
FROM stg_orders_corrected
WHERE order_date >= DATE '2026-10-03' AND order_date < DATE '2026-10-17'
ON CONFLICT (order_id) DO UPDATE
SET order_date = EXCLUDED.order_date,
    amount = EXCLUDED.amount;

Checked on Postgres 15 and 17: the changed row is updated, the new row is inserted, and a second run does not create a duplicate. The two rows that were removed from the corrected source are still in orders_daily. The Postgres docs also note that INSERT ... ON CONFLICT can update when a concurrent insert hits the same key. MERGE does not do that. That difference is from the docs; this page did not reproduce a concurrent race.

In dbt

  • delete+insert with a unique key deletes target rows whose key appears in the incoming batch, then inserts. If that key is the day, a day that is present in the new data is replaced. A day the corrected source dropped entirely is not in the batch, so those target rows stay. That matches Pattern 1 only for keys the new batch still contains.
  • Microbatch (dbt 1.9+) backfills with dbt run --event-time-start "2026-10-03" --event-time-end "2026-10-17". dbt's docs say the two flags are required together, and that event_time, begin, and both flags are treated as UTC. The compiled batch filter in those docs is half-open (>= the batch start and < the next boundary), so line the flags up with that rather than assuming the end flag is the last included day.
  • dbt's docs say dbt-postgres microbatch uses the merge strategy and requires unique_key, and they describe that strategy as "update" or "insert". They also describe microbatch as replacing a batch. Those pages do not say a Postgres merge deletes a target row missing from the batch, so check the compiled SQL before you rely on it. The same docs say Snowflake and Redshift use delete+insert ("insert" or "replace").
  • Rebuild the model and its downstream models for the same window with dbt build --select my_model+. The dbt and Airflow notes on this page follow those projects' docs. They were not executed while this page was written.

In Airflow 3

Airflow's docs for 3.4 use airflow backfill create. --from-date and --to-date are both inclusive, so this stops on 16 October when the SQL window stops before 17 October.

airflow backfill create --dag-id my_dag --from-date 2026-10-03 --to-date 2026-10-16 --reprocess-behavior completed --max-active-runs 2
  • --reprocess-behavior completed is All Runs: create another run when one already exists and is completed or failed. none is missing runs only. failed is missing runs plus failed runs. A logical date whose latest run is queued or still running does not get another run.
  • --max-active-runs limits how many of this backfill's runs are active at once. Airflow's docs say that limit is separate from the DAG's own max_active_runs, and that the scheduler does not otherwise deprioritize those tasks once they are running. It is the main lever for leaving room for scheduled work.
  • --dry-run prints the dates the backfill would consider. Whether a run is created still depends on the reprocess behavior and on the state of existing runs.
  • Backfill only helps if each task is idempotent (Patterns 1 or 2). Otherwise it creates the duplicates again.

Check before and after

-- duplicates on the business key
SELECT order_id, count(*) FROM orders_daily GROUP BY 1 HAVING count(*) > 1;

-- rows per day in and around the window, compare with source counts
SELECT order_date, count(*) FROM orders_daily
WHERE order_date >= DATE '2026-09-28' AND order_date < DATE '2026-10-22'
GROUP BY 1 ORDER BY 1;

A check bounded by >= DATE '2026-10-01' and < DATE '2026-10-20' does not include 30 September or 20 October, so a row sitting on either edge is invisible. The wider bounds above include those days. Compare the daily counts with the corrected source.

Where Row Monitor fits

Row Monitor checks row counts, freshness, and schema on the tables you name, once a day, and alerts in Slack or email when the row count moves past the threshold you set. That is how a double-loaded day usually shows up. Airflow checks are separate and report about every 15 minutes. Prices are in US dollars.

FAQ

Is INSERT ON CONFLICT enough for a backfill?

Only if the corrected source never removes rows. It needs a unique constraint on the key. It updates changed rows and inserts new ones, and a second run does not duplicate that key. Rows the source dropped stay in the table.

Which Postgres version supports MERGE ... WHEN NOT MATCHED BY SOURCE?

Postgres 17 and later. WHEN NOT MATCHED BY TARGET, RETURNING, and merge_action() are also PostgreSQL 17. On Postgres 15 and 16 the statement on this page fails with syntax error at or near "BY", and a MERGE that only adds RETURNING fails with syntax error at or near "RETURNING". Plain WHEN MATCHED and WHEN NOT MATCHED run on 15 and 16, and they do not delete rows missing from the source.

Should I backfill oldest or newest first?

Airflow supports --run-backwards, which runs the newest logical date first. It is not supported when a task has depends_on_past. Order matters when a day depends on an earlier day.

How do I stop a backfill crowding out daily runs in Airflow?

Set --max-active-runs on the backfill. It limits how many of that backfill's runs are active at once, separate from the DAG's own max_active_runs. Once those runs are going, Airflow's docs say the scheduler does not otherwise deprioritize them.