download

Replaying yesterday's events doubled revenue. How do you make reruns safe?

Data engineering~10 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. Why did the replay double-count 8000 cents?
  2. Fix load_day so re-running 2026-12-02 any number of times produces 3 rows and 12000 cents atomically, without touching 2026-12-01.
  3. When do you choose partition overwrite, MERGE, or an atomic partition swap?
"CODE · PYTHON"
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)
  1. "SPOT THE APPEND"

    The first run already inserted hours 12 and 13 (8000 cents). Appending the fixed day adds hours 12, 13, and 14 (12000 cents) right on top.

  2. "REPLACE ONE SLICE"

    Delete only the target day before inserting its recomputed rows, and keep both steps in one transaction so a crash never leaves the day empty.

  3. "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.

"SOLUTION · PYTHON"
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())
"OUTPUT"
[('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-02 changes. Earlier partition 2026-12-01 (9000 cents) is never touched.
  • Atomicity: If the INSERT fails halfway through (for example on a bad row or crash), SQLite rolls back the DELETE, so dashboards never see a missing or half-loaded day.

Choosing the right replace pattern in a warehouse or lakehouse:

PatternScope replacedDrops phantom rows?Best fit
DELETE + INSERT (1 tx)Target date/hour sliceYesPostgreSQL, SQLite, small warehouse tables
Dynamic INSERT OVERWRITEPartitions in inputYesSpark or Iceberg daily/hourly partitions
MERGE (UPSERT)Matched keys onlyOnly with delete branchSparse late updates across many days
Atomic partition swapStaged replacementYes (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 DELETE and INSERT in separate auto-commit statements. If the job crashes between them, dashboards see zero revenue for 2026-12-02.
  • Using Spark's default STATIC partition overwrite without a partition filter, which can wipe unrelated days like 2026-12-01.
  • Adding a primary key on (day, hour) and calling INSERT OR IGNORE. That skips updated cents values and keeps stale numbers from Run 1.
  • Computing the target day from CURRENT_DATE instead of passing day as 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-02 slice removes hour=15 cleanly. If you use MERGE instead, add a WHEN NOT MATCHED BY SOURCE AND target.day = '2026-12-02' THEN DELETE clause so stale rows do not survive.
  • "What happens if an upstream source really has zero events for a replayed day?" Dynamic INSERT OVERWRITE in Spark only replaces partitions present in the new input, so an empty input leaves old buggy rows untouched. Use explicit DELETE 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 →

Original OfferVibe question. Apache Spark: INSERT OVERWRITE · Apache Iceberg: Spark Writes · PostgreSQL: MERGE · SQLite: Transactions.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.