Replaying yesterday's events doubled revenue. How do you make reruns safe?
Question
A daily job aggregates hourly checkout totals into daily_revenue(day, hour, cents). Yesterday (2026-12-02) loaded hour=12 (5000) and hour=13 (3000), but an upstream parser bug dropped hour=14 (4000). Day 2026-12-01 already holds hour=12 (9000).
After fixing the parser, you replay 2026-12-02 with load_day below. Instead of 12000 cents across 3 rows, 2026-12-02 now has 5 rows totaling 20000 cents.
- Why did the replay double-count
8000cents? - Fix
load_dayso re-running2026-12-02any number of times produces3rows and12000cents atomically, without touching2026-12-01. - When do you choose partition overwrite,
MERGE, or an atomic partition swap?
def load_day(db, day, rows): # Bug: replaying a day appends duplicate rows db.executemany( "INSERT INTO daily_revenue (day, hour, cents) VALUES (?, ?, ?)", [(day, h, c) for h, c in rows], ) db.commit()
Show hints (3)
- "SPOT THE APPEND"
The first run already inserted hours
12and13(8000cents). Appending the fixed day adds hours12,13, and14(12000cents) right on top. - "REPLACE ONE SLICE"
Delete only the target
daybefore inserting its recomputed rows, and keep both steps in one transaction so a crash never leaves the day empty. - "CHECK VANISHED ROWS"
Think about an hour that existed in the buggy run but disappears in the fixed run. Partition replace removes it; a plain upsert does not.
Show checked explanation
An append-only INSERT adds the replayed 12000 cents on top of the existing 8000 cents, reaching 20000 cents. Make the load idempotent by replacing only 2026-12-02 inside one transaction (DELETE WHERE day = ? followed by INSERT), or by using dynamic partition overwrite or an atomic partition swap. Reruns then yield 3 rows and 12000 cents every time.
import sqlite3 def load_day(db, day, rows): with db: db.execute("DELETE FROM daily_revenue WHERE day = ?", (day,)) db.executemany("INSERT INTO daily_revenue VALUES (?, ?, ?)", [(day, h, c) for h, c in rows]) conn = sqlite3.connect(":memory:") conn.execute("CREATE TABLE daily_revenue (day TEXT, hour INT, " "cents INT, PRIMARY KEY (day, hour))") conn.execute("INSERT INTO daily_revenue VALUES ('2026-12-01', 12, 9000)") load_day(conn, "2026-12-02", [(12, 5000), (13, 3000)]) for _ in range(2): load_day(conn, "2026-12-02", [(12, 5000), (13, 3000), (14, 4000)]) q = ("SELECT day, COUNT(*), SUM(cents) FROM daily_revenue " "GROUP BY day ORDER BY day") print(conn.execute(q).fetchall())
[('2026-12-01', 1, 9000), ('2026-12-02', 3, 12000)]Author-checked on CPython 3.12.10 and SQLite 3.49.1: reproduced the 20,000-cent append bug, ran the transactional replace solution twice, and tested rollback on failure plus phantom-row cleanup. Checked by an editor other than the author.
Walkthrough
Append-only tables break on the first retry. Run 1 inserted hour=12 (5000) and hour=13 (3000). Without a primary key or slice replacement, Run 2 appended 5000 + 3000 + 4000, inflating 2026-12-02 to 5 rows and 20000 cents.
An idempotent job gives the exact same table state whether you run it once or ten times for the same time window. Wrapping DELETE WHERE day = ? and INSERT inside with db: gives you two guarantees at once:
- Scoped overwrite: Only
2026-12-02changes. Earlier partition2026-12-01(9000cents) is never touched. - Atomicity: If the
INSERTfails halfway through (for example on a bad row or crash), SQLite rolls back theDELETE, so dashboards never see a missing or half-loaded day.
Choosing the right replace pattern in a warehouse or lakehouse:
| Pattern | Scope replaced | Drops phantom rows? | Best fit |
|---|---|---|---|
DELETE + INSERT (1 tx) | Target date/hour slice | Yes | PostgreSQL, SQLite, small warehouse tables |
Dynamic INSERT OVERWRITE | Partitions in input | Yes | Spark or Iceberg daily/hourly partitions |
MERGE (UPSERT) | Matched keys only | Only with delete branch | Sparse late updates across many days |
| Atomic partition swap | Staged replacement | Yes (zero reader gap) | Large tables with strict BI SLAs |
Notice the third column. Suppose buggy Run 1 wrote a phantom hour=15 that does not exist after the fix. Partition overwrite and DELETE + INSERT remove hour=15 automatically. A plain MERGE leaves hour=15 behind unless you add a WHEN NOT MATCHED BY SOURCE THEN DELETE branch scoped to that day.
Common mistakes
- Running
DELETEandINSERTin separate auto-commit statements. If the job crashes between them, dashboards see zero revenue for2026-12-02. - Using Spark's default
STATICpartition overwrite without a partition filter, which can wipe unrelated days like2026-12-01. - Adding a primary key on
(day, hour)and callingINSERT OR IGNORE. That skips updatedcentsvalues and keeps stale numbers from Run 1. - Computing the target day from
CURRENT_DATEinstead of passingdayas a job parameter, which makes yesterday's replay overwrite today.
Follow-up questions
- "What if buggy Run 1 wrote a bogus hour 15 row that disappears in the fixed data?" Replacing the whole
2026-12-02slice removeshour=15cleanly. If you useMERGEinstead, add aWHEN NOT MATCHED BY SOURCE AND target.day = '2026-12-02' THEN DELETEclause so stale rows do not survive. - "What happens if an upstream source really has zero events for a replayed day?" Dynamic
INSERT OVERWRITEin Spark only replaces partitions present in the new input, so an empty input leaves old buggy rows untouched. Use explicitDELETE WHERE day = ?or static partition overwrite for empty days. - "How do you stop two retries of the same day from running at the same time?" Serialize writes per partition key using your orchestrator's task concurrency lock, a database advisory lock, or optimistic snapshot commits in Iceberg so concurrent replays cannot interleave.
What a strong answer covers
Explains why blind APPEND inflates revenue to 20000 cents. Replaces only 2026-12-02 inside one transaction, handles vanished phantom rows, and compares partition overwrite, MERGE, and atomic partition swaps.
Open in interactive practice deck →