Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 2

Lab: Idempotent Writes and a Safe Backfill

Land 30 days of raw Parquet, see an append job duplicate a day, make it idempotent with an atomic partition overwrite and a MERGE on business keys, then backfill the month in parallel, repair the one failed date and prove with checksums that the result matches a clean run.

Contentsand lesson path

What you will learn

  • Make each run idempotent (partition overwrite or MERGE on business keys) and backfill a historical date range without duplicates or gaps.

Prerequisites: Data Handling, SQL Fundamentals

01. Goal and setup

Pipelines are re-run all the time. A scheduler retries a failed task, an engineer re-runs yesterday after a fix, and a new metric needs last year rebuilt. A job is idempotent when running it once or five times for the same input leaves the target in the same state. A backfill runs a job for a range of past dates. If the job is idempotent, a backfill is routine; if it is not, every re-run is a risk of duplicates or gaps.

In this lab you load 30 days of raw orders into PostgreSQL. You will see the naive version double a day, make the load idempotent in two ways, run a parallel backfill in which one date fails, repair only that date, and prove with a checksum that the table matches a clean single run.

You need the etl-lab container from Bulk Loading Without Row-by-Row Inserts (PostgreSQL 17.11, port 55432) and a Python 3.10+ virtual environment. The lab was tested with Python 3.12, pyarrow 26.0.1 and psycopg 3.3.9.

Terminal
mkdir backfill-lab && cd backfill-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "pyarrow==26.0.1" "psycopg[binary]==3.3.9"
docker exec etl-lab createdb -U postgres sales
export DATABASE_URL=postgresql://postgres:[email protected]:55432/sales
Folder layout at the end of the lab
backfill-lab/
├── make_raw.py           step 1: lands raw Parquet, one folder per day
├── schema.sql            step 2: fact, dimension and staging tables
├── load_day.py           steps 2-4: loads one day
├── stage_customers.sql   step 5: the CRM snapshot
├── merge_customers.sql   step 5: MERGE on the business key
├── backfill.py           step 6: runs load_day for a range of dates
├── checksum.sql          step 6: a fingerprint of the fact table
└── raw/orders/order_date=2026-10-01/part-0.parquet ...

02. Step 1: Land the raw data

The script writes one Parquet file per day under raw/orders/order_date=YYYY-MM-DD/. Each day seeds its own random generator with the date, so the rows for a given day are always the same. On 17 October the partner sent one row without a customer_id; you will meet it during the backfill.

Python · make_raw.py
"""Land 30 days of raw orders as date-partitioned Parquet (seeded, repeatable)."""
import random
import sys
from datetime import date, timedelta
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq

BROKEN_DAY = date(2026, 10, 17)   # the partner sent one bad row on this day


def land(day, fixed):
    rng = random.Random(day.toordinal())          # same rows for a day, every time
    n = rng.randint(80, 120)
    ids = [day.day * 1000 + i for i in range(n)]      # 1000-1119 on 1 October ...
    customers = [rng.randint(1, 50) for _ in range(n)]
    if day == BROKEN_DAY and not fixed:
        customers[7] = None
    amounts = [round(rng.uniform(5, 250), 2) for _ in range(n)]
    table = pa.table({"order_id": ids, "customer_id": customers, "amount": amounts})
    folder = Path("raw/orders") / f"order_date={day}"
    folder.mkdir(parents=True, exist_ok=True)
    pq.write_table(table, folder / "part-0.parquet")
    return n


if __name__ == "__main__":
    fixed = "--fixed" in sys.argv
    days = [date(2026, 10, 1) + timedelta(d) for d in range(30)]
    if "--only" in sys.argv:
        days = [date.fromisoformat(sys.argv[sys.argv.index("--only") + 1])]
    rows = sum(land(day, fixed) for day in days)
    print(f"landed {len(days)} partitions, {rows} rows")
Terminal
python make_raw.py
ls raw/orders | head -3
ls raw/orders | wc -l
Expected output
landed 30 partitions, 3007 rows
order_date=2026-10-01
order_date=2026-10-02
order_date=2026-10-03
30

03. Step 2: See an append job duplicate a day

Create the tables. The fact table has no enforced primary key, which is common in warehouses, so nothing stops duplicates at the database level. Then save load_day.py. Its load_day() function reads one day of raw rows and COPYs them in, inside conn.transaction(): either the whole block commits or none of it does. In append mode it only inserts; in overwrite mode, the default, it first deletes every row for that date. The --crash-after option raises an error part-way through, to simulate a crash.

SQL · schema.sql
SET client_min_messages = warning;
DROP TABLE IF EXISTS fact_orders, dim_customer, stage_customer;
-- Like many warehouse fact tables, this one has no enforced primary key.
CREATE TABLE fact_orders (
  order_date  date          NOT NULL,
  order_id    bigint        NOT NULL,
  customer_id int           NOT NULL,
  amount      numeric(10,2) NOT NULL
);
CREATE TABLE dim_customer (
  source_system text NOT NULL,
  customer_id   int  NOT NULL,
  name          text NOT NULL,
  city          text NOT NULL,
  PRIMARY KEY (source_system, customer_id)
);
-- Each day the CRM snapshot is copied here before it is merged.
CREATE UNLOGGED TABLE stage_customer (LIKE dim_customer);
Python · load_day.py
"""Load one day of raw orders into fact_orders."""
import argparse
import os
from pathlib import Path

import psycopg
import pyarrow.parquet as pq


def read_day(day):
    path = Path("raw/orders") / f"order_date={day}" / "part-0.parquet"
    return pq.read_table(path).to_pylist()


def load_day(conn, day, mode="overwrite", crash_after=None):
    rows = read_day(day)
    with conn.transaction():                        # all or nothing
        if mode == "overwrite":
            conn.execute("DELETE FROM fact_orders WHERE order_date = %s", (day,))
        with conn.cursor().copy("COPY fact_orders FROM STDIN") as copy:
            for i, r in enumerate(rows):
                if crash_after is not None and i == crash_after:
                    raise RuntimeError(f"simulated crash after {i} rows")
                copy.write_row((day, r["order_id"], r["customer_id"], r["amount"]))
    return len(rows)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--date", required=True)
    parser.add_argument("--mode", choices=["append", "overwrite"], default="overwrite")
    parser.add_argument("--crash-after", type=int)
    args = parser.parse_args()
    with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
        n = load_day(conn, args.date, args.mode, args.crash_after)
        total = conn.execute("SELECT count(*) FROM fact_orders"
                             " WHERE order_date = %s", (args.date,)).fetchone()[0]
    print(f"{args.date} {args.mode}: read {n} rows, table now has {total} for that day")
Terminal
docker exec -i etl-lab psql -U postgres -d sales -X -q < schema.sql
python load_day.py --date 2026-10-01 --mode append
python load_day.py --date 2026-10-01 --mode append
Expected output
2026-10-01 append: read 87 rows, table now has 87 for that day
2026-10-01 append: read 87 rows, table now has 174 for that day

The second run, which is exactly what a scheduler retry does, doubled the day. Every report on 1 October is now wrong, and nothing failed to tell you.

04. Step 3: Overwrite the partition atomically

A partition here is the set of rows for one date. The job owns that partition: it is the only process that writes it. Run the default overwrite mode twice.

Terminal
python load_day.py --date 2026-10-01
python load_day.py --date 2026-10-01
Expected output
2026-10-01 overwrite: read 87 rows, table now has 87 for that day
2026-10-01 overwrite: read 87 rows, table now has 87 for that day

The first overwrite also cleaned up the duplicates from step 2, because it deletes everything for the date before inserting. The end state no longer depends on what happened before or how many times the job ran. Warehouses and lakehouses offer the same operation natively, for example INSERT OVERWRITE for a partition in Spark SQL, or an Iceberg overwrite filtered to one partition. The rule stays the same: the job replaces exactly the slice it owns and nothing else.

05. Step 4: Crash in the middle

An overwrite is only safe if the delete and the insert are atomic. If the job deleted the day, crashed, and left the day empty, readers would see a gap. Crash it after 40 rows and count what is left.

Terminal
python load_day.py --date 2026-10-01 --crash-after 40 2>&1 | tail -n 1
docker exec etl-lab psql -U postgres -d sales -X -q \
  -c "SELECT count(*) FROM fact_orders WHERE order_date = '2026-10-01'"
Expected output
RuntimeError: simulated crash after 40 rows
 count 
-------
    87
(1 row)

The exception left the transaction() block, so PostgreSQL rolled back the delete and the 40 copied rows together; other sessions never saw an empty day. One more rule: only one writer per partition at a time. In a test for this lab, two overwrites of the same date that overlapped in time left every row twice. Each transaction deleted the rows it could see, then inserted its own copy, and neither could see the other one's uncommitted rows. Let the scheduler run one task per date, or take a lock per date, for example with pg_advisory_xact_lock.

06. Step 5: MERGE a dimension on its business key

Overwrite fits data that is naturally split by date. A customer dimension is different: each day the CRM sends a snapshot of current customers, and the table must keep one row per customer. Here the idempotent write is a MERGE that matches on the business key, the identifier the source system uses, (source_system, customer_id). The key must be stable across runs: a key generated during the load, or the load time, would never match the previous run, so every re-run would insert duplicates. Rows that match are updated only if something changed, and new keys are inserted. RETURNING merge_action(), new in PostgreSQL 17, shows what each row did. Stage the snapshot, then run the merge twice.

SQL · stage_customers.sql
-- Today's customer snapshot from the CRM.
TRUNCATE stage_customer;
INSERT INTO stage_customer VALUES
  ('crm', 1, 'Ana Lima',   'Porto'),
  ('crm', 2, 'Ben Okafor', 'Leeds'),
  ('crm', 3, 'Chen Wei',   'Lyon');
SQL · merge_customers.sql
MERGE INTO dim_customer AS t
USING stage_customer AS s
   ON t.source_system = s.source_system AND t.customer_id = s.customer_id
WHEN MATCHED AND (t.name, t.city) IS DISTINCT FROM (s.name, s.city) THEN
  UPDATE SET name = s.name, city = s.city
WHEN NOT MATCHED THEN
  INSERT VALUES (s.source_system, s.customer_id, s.name, s.city)
RETURNING merge_action(), t.customer_id, t.city;
Terminal
docker exec -i etl-lab psql -U postgres -d sales -X -q < stage_customers.sql
docker exec -i etl-lab psql -U postgres -d sales -X -q < merge_customers.sql
docker exec -i etl-lab psql -U postgres -d sales -X -q < merge_customers.sql
Expected output
 merge_action | customer_id | city  
--------------+-------------+-------
 INSERT       |           1 | Porto
 INSERT       |           2 | Leeds
 INSERT       |           3 | Lyon
(3 rows)

 merge_action | customer_id | city 
--------------+-------------+------
(0 rows)

The second merge did nothing, which is what idempotent means. Now change one city in the snapshot and merge again; only that customer is updated.

Terminal
docker exec etl-lab psql -U postgres -d sales -X -q \
  -c "UPDATE stage_customer SET city = 'Bristol' WHERE customer_id = 2"
docker exec -i etl-lab psql -U postgres -d sales -X -q < merge_customers.sql
Expected output
 merge_action | customer_id |  city   
--------------+-------------+---------
 UPDATE       |           2 | Bristol
(1 row)

07. Step 6: Backfill October in parallel

A safe backfill reuses the tested daily job instead of a one-off query: each date is loaded by load_day() with its own logical date, its own connection and its own transaction. backfill.py runs at most four dates at once. That limit protects the source and the target; a backfill that opens 365 connections at once can hurt production queries. A failed date is recorded and the others continue, and the exit code is 1 if anything failed, so a scheduler would mark the run as failed. checksum.sql reduces the table to one line: the row count, the total amount, and a fingerprint (the start of an MD5 hash of every id and amount in a fixed order) that changes if any row is missing, repeated or different.

Python · backfill.py
"""Re-run the daily load for a range of dates, a few at a time."""
import argparse
import os
import textwrap
from concurrent.futures import ThreadPoolExecutor
from datetime import date, timedelta

import psycopg

from load_day import load_day


def run_one(day):
    try:
        with psycopg.connect(os.environ["DATABASE_URL"]) as conn:  # one per worker
            return day, load_day(conn, day), None
    except Exception as exc:                                     # report, keep going
        return day, 0, str(exc).splitlines()[0]


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--start", type=date.fromisoformat, required=True)
    parser.add_argument("--end", type=date.fromisoformat, required=True)
    parser.add_argument("--workers", type=int, default=4)      # bounded parallelism
    args = parser.parse_args()
    days = [args.start + timedelta(d) for d in range((args.end - args.start).days + 1)]
    with ThreadPoolExecutor(max_workers=args.workers) as pool:
        results = sorted(pool.map(run_one, days))
    failed = [(d, e) for d, _, e in results if e]
    print(f"{len(results) - len(failed)} dates loaded,"
          f" {sum(n for _, n, _ in results)} rows, {len(failed)} failed")
    for day, error in failed:
        print(textwrap.fill(f"FAILED {day}: {error}", 72, subsequent_indent="    "))
    raise SystemExit(1 if failed else 0)
SQL · checksum.sql
-- One line that changes if any row is missing, duplicated or different.
SELECT count(*) AS rows, sum(amount) AS total,
       left(md5(string_agg(order_id || ':' || amount, ',' ORDER BY order_id)), 12)
         AS fingerprint
FROM fact_orders;
Terminal
python backfill.py --start 2026-10-01 --end 2026-10-30 --workers 4
echo "exit code $?"
docker exec -i etl-lab psql -U postgres -d sales -X -q < checksum.sql
Expected output
29 dates loaded, 2911 rows, 1 failed
FAILED 2026-10-17: null value in column "customer_id" of relation
    "fact_orders" violates not-null constraint
exit code 1
 rows |   total   | fingerprint  
------+-----------+--------------
 2911 | 373209.71 | c72e19b4a0a8
(1 row)

Twenty-nine dates loaded, and 17 October failed on the NOT NULL constraint. Because that date rolled back, it holds no rows rather than half of them; the other dates are unaffected.

08. Step 7: Repair one date and prove the result

Suppose the partner re-sends a corrected file for 17 October. Land it, then re-run the backfill for that one date only.

Terminal
python make_raw.py --fixed --only 2026-10-17
python backfill.py --start 2026-10-17 --end 2026-10-17
docker exec -i etl-lab psql -U postgres -d sales -X -q < checksum.sql
Expected output
landed 1 partitions, 96 rows
1 dates loaded, 96 rows, 0 failed
 rows |   total   | fingerprint  
------+-----------+--------------
 3007 | 385393.58 | 1d35fb5cbd68
(1 row)

Is this table really the same as one built in a single clean run? Run the whole month again in sales, then build it from scratch in a second database, sales_clean, with one worker. The three lines must match.

Terminal
python backfill.py --start 2026-10-01 --end 2026-10-30 --workers 4
docker exec -i etl-lab psql -U postgres -d sales -X -q < checksum.sql

docker exec etl-lab createdb -U postgres sales_clean
docker exec -i etl-lab psql -U postgres -d sales_clean -X -q < schema.sql
DATABASE_URL=postgresql://postgres:[email protected]:55432/sales_clean \
  python backfill.py --start 2026-10-01 --end 2026-10-30 --workers 1
docker exec -i etl-lab psql -U postgres -d sales_clean -X -q < checksum.sql
Expected output (sales, re-run)
30 dates loaded, 3007 rows, 0 failed
 rows |   total   | fingerprint  
------+-----------+--------------
 3007 | 385393.58 | 1d35fb5cbd68
(1 row)
Expected output (sales_clean, single clean run)
30 dates loaded, 3007 rows, 0 failed
 rows |   total   | fingerprint  
------+-----------+--------------
 3007 | 385393.58 | 1d35fb5cbd68
(1 row)

Same count, total and fingerprint: the duplicated day from step 2, the crash in step 4, the failed date and the parallel re-runs left no trace. When you have finished, remove the container with docker rm -f etl-lab.

09. Check your understanding

Practice check · 3 questions

Re-runs and backfills

Each question changes one detail of the lab. Pick the best answer.

Q1. On an empty table, `load_day.py --date 2026-10-05 --mode append --crash-after 40` fails. The scheduler retries the same command without `--crash-after`, and it succeeds. How many rows does 5 October have?
Q2. A backfill list contains 2026-10-05 twice, and two workers load it at the same moment, each with DELETE then COPY in its own transaction. What can happen?
Q3. You remove `AND (t.name, t.city) IS DISTINCT FROM (s.name, s.city)` from the MERGE and run it again with an unchanged snapshot. What does it return?
Practice only: not graded, not saved, not evidence.

10. Apply it

Finish the skill practice with this pattern. Your extractor lands each day of API data in its own raw folder; load each day with an atomic overwrite keyed on its logical date, and merge slowly changing reference data on its business key. Then run the same day twice and a 30-day backfill once, and record the checksum query output after each, next to the output of a single clean run into an empty database. Finally, write the one-page ingestion decision the practice asks for, for a SaaS tool with an existing connector and a nightly partner file drop.

11. Review prompt

Without looking back, explain: what makes a job idempotent; why the delete and insert of a partition overwrite must be in one transaction; when to use a partition overwrite and when a MERGE on a business key; why a backfill should reuse the daily job with bounded parallelism; and how a checksum proves that a repaired table matches a clean run.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check