Run it twice

Part of the free LogicWiz Data Engineering course, Module 6: Batch pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 9:05 on Wednesday. Tess opens the revenue dashboard and 3 June says $1,099.74. The store's own report says $549.87: exactly half. Nothing failed overnight. The log shows that Tuesday night's load timed out just after writing its rows, the scheduler tried it again, and the second try wrote 3 June's sales a second time. Every row is there twice.

You'll learn to

  • Say what idempotent means, and why every load must be
  • Make a rerun harmless: delete-then-insert, merge or overwrite a partition
  • Explain why a scheduler has to retry
  • Name a batch with an idempotency key and a ledger

Learn

Nothing failed. Every row is there twice.

Pipelines run again. A scheduler retries a task that timed out. An engineer reruns last Tuesday after a fix. A backfill reprocesses a month. You cannot stop reruns, so you design for them.

The word for a step that survives them is idempotent: running it twice leaves the same result as running it once. "The same result" means the target table: the same rows, the same totals.

Think of a thermostat. "Set it to 20 degrees" is idempotent: do it five times and it is still 20. "Turn it up by one degree" is not: the result depends on how many times you did it.

The nightly load is the second kind. It is the most natural code there is, INSERT INTO target SELECT ..., and every run adds rows.

A tiny pipeline that loads one day of sales; run it twice in append, delete-then-insert or merge mode and watch the revenue total double or stay right.

Start in append mode and press Run twice: the revenue doubles. Then switch to replace and to merge and do the same.

The append retry, for real

-- The nightly load for 3 June: a plain append
INSERT INTO dw.fact_sales
SELECT i.order_id, i.line_no, o.order_ts::DATE AS order_date, i.qty * i.unit_price AS amount
FROM order_items AS i
JOIN orders AS o ON o.order_id = i.order_id
WHERE o.order_ts::DATE = DATE '2025-06-03';

SELECT COUNT(*) AS lines, SUM(amount) AS revenue
FROM dw.fact_sales;

-- The scheduler retries the same task
INSERT INTO dw.fact_sales
SELECT i.order_id, i.line_no, o.order_ts::DATE AS order_date, i.qty * i.unit_price AS amount
FROM order_items AS i
JOIN orders AS o ON o.order_id = i.order_id
WHERE o.order_ts::DATE = DATE '2025-06-03';

SELECT COUNT(*) AS lines, SUM(amount) AS revenue
FROM dw.fact_sales;

14 lines and $549.87 after one run; 28 lines and $1,099.74 after two. No error, no warning. In Postgres a PRIMARY KEY (order_id, line_no) would make the second run fail loudly. But Snowflake, BigQuery and Databricks let you declare a primary key without enforcing it, so duplicates go straight in. The safety has to come from how you write the load.

Fix 1: delete the day, then insert it

First decide what one run is responsible for. That is its batch: here, every sale placed on 3 June.

Then make each run do two things in one transaction: delete everything in its batch, and insert the batch fresh.

Run it once: it deletes nothing and inserts 14 lines. Run it again: it deletes those 14 and inserts the same 14. Same table.

This is delete-then-insert, the workhorse of batch pipelines. It needs a column that marks the batch (order_date, a load date, a file name), so the delete removes exactly what this run is about to write again, and nothing else.

Delete-then-insert, run twice

-- Run 1
BEGIN;
DELETE FROM dw.fact_sales WHERE order_date = DATE '2025-06-03';
INSERT INTO dw.fact_sales
SELECT i.order_id, i.line_no, o.order_ts::DATE AS order_date, i.qty * i.unit_price AS amount
FROM order_items AS i
JOIN orders AS o ON o.order_id = i.order_id
WHERE o.order_ts::DATE = DATE '2025-06-03';
COMMIT;

-- Run 2: the retry
BEGIN;
DELETE FROM dw.fact_sales WHERE order_date = DATE '2025-06-03';
INSERT INTO dw.fact_sales
SELECT i.order_id, i.line_no, o.order_ts::DATE AS order_date, i.qty * i.unit_price AS amount
FROM order_items AS i
JOIN orders AS o ON o.order_id = i.order_id
WHERE o.order_ts::DATE = DATE '2025-06-03';
COMMIT;

SELECT COUNT(*) AS lines, SUM(amount) AS revenue
FROM dw.fact_sales;

Still 14 lines and $549.87 after two runs. The transaction matters: if the insert fails, the delete is rolled back too, and the old rows are still there.

Fix 2: match each row by its key

The second fix deletes nothing. A merge (also called an upsert) takes each incoming row and looks for a row with the same key, here (order_id, line_no). If it finds one, it updates it. If not, it inserts. Run it twice, and the second run updates the same 14 rows to the same values.

Merge is the right tool when a batch is not a clean slice of the table. Picture a table with one row per order and its status. Order 1012 was placed on 2 June and shipped on 3 June. Its row belongs with 2 June, yet the 3 June file changes it. A merge on the key updates the row wherever it sits. A delete of "3 June" would never touch it.

MERGE, run twice

MERGE INTO dw.fact_sales AS t
USING (
  SELECT i.order_id, i.line_no, o.order_ts::DATE AS order_date, i.qty * i.unit_price AS amount
  FROM order_items AS i
  JOIN orders AS o ON o.order_id = i.order_id
  WHERE o.order_ts::DATE = DATE '2025-06-03'
) AS s
ON t.order_id = s.order_id AND t.line_no = s.line_no
WHEN MATCHED THEN
  UPDATE SET order_date = s.order_date, amount = s.amount
WHEN NOT MATCHED THEN
  INSERT (order_id, line_no, order_date, amount)
  VALUES (s.order_id, s.line_no, s.order_date, s.amount);

-- Run the same MERGE again: every row now matches, so it only updates
MERGE INTO dw.fact_sales AS t
USING (
  SELECT i.order_id, i.line_no, o.order_ts::DATE AS order_date, i.qty * i.unit_price AS amount
  FROM order_items AS i
  JOIN orders AS o ON o.order_id = i.order_id
  WHERE o.order_ts::DATE = DATE '2025-06-03'
) AS s
ON t.order_id = s.order_id AND t.line_no = s.line_no
WHEN MATCHED THEN
  UPDATE SET order_date = s.order_date, amount = s.amount
WHEN NOT MATCHED THEN
  INSERT (order_id, line_no, order_date, amount)
  VALUES (s.order_id, s.line_no, s.order_date, s.amount);

SELECT COUNT(*) AS lines, SUM(amount) AS revenue
FROM dw.fact_sales;

14 lines and $549.87 again. MERGE works in Postgres 15 and later, and in every big warehouse. In Postgres, INSERT ... ON CONFLICT (key) DO UPDATE does the same job when the key has a unique index.

The trap: the slice you delete must be the slice you insert. A job that deletes WHERE order_date = '2025-06-03' but inserts the orders that changed on 3 June leaves some rows undeleted (orders placed on 2 June that shipped on 3 June), and every rerun duplicates them. Use the same filter on the same column for both. And clean the batch itself first: the retry file means 3 June's input already holds every order twice, and MERGE stops with "cannot affect row a second time" when two source rows match one target row.

The same retry, written three ways

The 14 order lines of 3 June are loaded once, then loaded again by a retry: appended, which doubles them, then by delete-then-insert and by a merge on the key, which both leave 14 lines.

  1. Try 1. The batch is the 14 order lines of 3 June, worth $549.87. The table is empty, so 14 lines go in.

  2. Try 2, with a plain INSERT. The scheduler runs the task again. The same 14 lines go in a second time: 28 lines, and revenue says $1,099.74.

  3. Try 2, with delete-then-insert. The run first deletes every 3 June line, then inserts the 14 fresh. The table ends where it started: 14 lines, $549.87.

  4. Try 2, with a merge. Each incoming line finds its row by (order_id, line_no) and updates it to the same values. Nothing is left to insert: 14 lines, $549.87.

The left box never changes: every try gets the same batch. Watch the right box. Only the way the rows are written decides whether a retry doubles the day.

Fix 3: replace the whole folder

In a data lake a table is a folder of files, usually split into one folder per day: orders/load_date=2025-06-03/. Each of those folders is a partition.

The safe move there is delete-then-insert with files: replace the whole folder for the day being loaded. A rerun writes the same folder again, the old files are gone, and nothing doubles. This is a partition overwrite. Spark calls it dynamic partition overwrite; Delta Lake offers replaceWhere.

The DuckDB example below does it by hand: remove the day's folder, then write it again.

Partition overwrite with DuckDB

import duckdb, os, shutil

def load_day(day):
    folder = f'lake/orders/load_date={day}'
    shutil.rmtree(folder, ignore_errors=True)   # replace, never add
    os.makedirs(folder)
    # The day's files include the retry, so drop exact copies first
    duckdb.sql(f"""
        COPY (
            SELECT DISTINCT order_id, customer_id, status, updated_at
            FROM read_csv_auto('landing/orders/{day}*.csv')
        ) TO '{folder}/part-0.parquet' (FORMAT PARQUET)
    """)

def rows_in_lake():
    return duckdb.sql("SELECT COUNT(*) FROM read_parquet('lake/orders/*/*.parquet')").fetchone()[0]

load_day('2025-06-02')
load_day('2025-06-03')
print('after one run each:', rows_in_lake())
load_day('2025-06-03')                          # the scheduler retries 3 June
print('after rerunning 3 June:', rows_in_lake())

8 rows for 2 June plus 7 for 3 June (the 14 landed rows minus the 7 retry copies). The rerun replaces the 3 June folder, so the lake still holds 15. Had each run written a new file name, such as part-<run time>.parquet, the rerun would have added 7 more.

Which fix, when

MethodOne run ownsUse it whenWatch out for
Delete-then-insertA slice: a day, a file, a storeThe batch is a clean slice of the targetDelete exactly the slice you insert
Merge (upsert)Rows with a keyA batch updates rows from older batchesOne source row per key, or MERGE fails
Partition overwriteA folder of filesLake tables split by datePartition by the batch column
Full refreshThe whole tableThe table is smallCost grows with the table

The scheduler was right to retry

Back to Tuesday night. Was the retry a scheduler bug? No.

The first try's COMMIT succeeded. Then the worker was killed, or the connection dropped, or the task hit its timeout, before it could report success. From the scheduler's side, "it committed and I did not hear" looks exactly like "it never ran". The only safe choice is to run it again.

So a scheduler, a queue or a stream can promise to deliver work at least once, never exactly once: some failures always leave the sender unsure. A person rerunning a day is a retry too. The table has to make the second try harmless.

Try 1 committed. Nobody heard.

The scheduler starts a task, the task commits its rows to the warehouse, the success report is lost, the scheduler retries, and the second try deletes and rewrites the same day so the table ends with the same 14 lines.

Read it top to bottom. The red arrow is the report that never arrives. Everything below the dashed line is the retry, and with delete-then-insert it leaves the table as try 1 left it.

"Exactly once" is a result, not a delivery

Tools often promise "exactly-once". Read that carefully. Nobody can deliver work exactly once: you have just seen why.

What they really give is two things together: delivery at least once, plus a write that absorbs repeats. The result is as if each item arrived once. A more honest name is effectively-once.

Kafka, Spark Structured Streaming and payment APIs all work this way. Kafka's own documentation says its exactly-once covers reading, processing and writing inside Kafka; any other destination has to cooperate. Their settings are in the table at the end.

Effectively-once = at-least-once + a write that absorbs repeats

Four steps: the source may deliver a batch more than once, every copy carries the same idempotency key, the target applies each key only once, and the result is as if every batch arrived exactly once.

Read it left to right. The first box is what you get. The last box is what you want. The two in the middle are your job.

Name the work, not the attempt

That name is an idempotency key: a name for one unit of work that every retry computes the same way.

Good keys: the pipeline plus the date it is loading (fact_sales/2025-06-03), a file path plus its checksum, a Kafka topic, partition and offset range, or a business key such as event_id.

The target remembers the keys it has applied in a small table called a ledger. The ledger row is written in the same transaction as the data, so the two commit together or roll back together.

The classic bug is a key that names the attempt: uuid4(), now(), the try number or a sequence value. Each retry gets a new key, so nothing is ever recognised as a repeat.

A ledger: claim the key and write the rows in one statement

-- Try 1 and try 2 run exactly the same statement
WITH claim AS (
  INSERT INTO dw.load_ledger (batch_id) VALUES ('fact_sales/2025-06-03')
  ON CONFLICT (batch_id) DO NOTHING
  RETURNING batch_id
)
INSERT INTO dw.fact_sales
SELECT b.* FROM (SELECT i.order_id, i.line_no, o.order_ts::DATE AS order_date, i.qty * i.unit_price AS amount
FROM order_items AS i
JOIN orders AS o ON o.order_id = i.order_id
WHERE o.order_ts::DATE = DATE '2025-06-03') AS b
WHERE EXISTS (SELECT 1 FROM claim);

WITH claim AS (
  INSERT INTO dw.load_ledger (batch_id) VALUES ('fact_sales/2025-06-03')
  ON CONFLICT (batch_id) DO NOTHING
  RETURNING batch_id
)
INSERT INTO dw.fact_sales
SELECT b.* FROM (SELECT i.order_id, i.line_no, o.order_ts::DATE AS order_date, i.qty * i.unit_price AS amount
FROM order_items AS i
JOIN orders AS o ON o.order_id = i.order_id
WHERE o.order_ts::DATE = DATE '2025-06-03') AS b
WHERE EXISTS (SELECT 1 FROM claim);

SELECT COUNT(*) AS lines, SUM(amount) AS revenue,
  (SELECT COUNT(*) FROM dw.load_ledger) AS ledger_rows
FROM dw.fact_sales;

The first statement claims the key (RETURNING gives one row) and inserts 14 lines. The second finds the key taken, so claim is empty and 0 lines are written. One statement is one transaction, so a crash can never leave the key without the data. A ledger means "apply once": to rebuild a batch on purpose, delete its ledger row in the same transaction as its data.

Remember: you cannot stop a retry. You can only make it harmless: delete-then-insert the batch, merge on the key, or overwrite the partition. Never a plain append.

Writes that change a little on every rerun

Looks harmlessWhy a rerun changes the resultMake it repeatable
SET balance = balance + 10Adds 10 per attemptSet the value: SET balance = <computed total
nextval() surrogate keysNew keys each run, so a merge on them never matchesMerge on the business key; hash it if you need a key
loadedat DEFAULT now()Differs per run (fine), but breaks hash comparisonsLeave lineage columns out of row hashes
ROWNUMBER() with a partial ORDER BYTies break differently on each runAdd a unique tie-breaker
A key from uuid4() or the try numberEvery retry is "new work"Derive the key from the input

Each row is the thermostat problem again: "turn it up by one" hiding inside a pipeline.

Numbers to remember

NameValueWhat it is
MERGEPostgres 15 and laterAlso in every big warehouse, and MERGE INTO on Delta tables
Primary keys in Snowflake, BigQuery, Databricksdeclared, not enforcedA duplicate key goes in without an error
Airflow defaulttaskretries0No retries by default, but almost every team sets retries (for example retries=3) on real DAGs. Airflow's own guidance: make every task idempotent
dbt incremental strategiesappend, delete+insert, mergeThe choices of this lesson, picked per model
Spark partitionOverwriteModedynamicReplaces only the partitions a job writes
Kafka idempotent produceron by default since Kafka 3.0With transactions, gives exactly-once for read-process-write inside Kafka
Kafka isolation.leveldefault readuncommittedConsumers must set readcommitted to get that guarantee
Spark Structured Streamingreplayable source, offsets in the checkpoint, idempotent sinkDelta's txnAppId and txnVersion writer options make a foreachBatch write skip a batch it already committed
Stripe Idempotency-Key headerone key per requestA retried payment request returns the first result instead of charging twice

The story needs none of these. They are where the same idea shows up in the tools you will use.

What changed at SwiftKart

The 3 June load now deletes its day and inserts it again in one transaction. The retry that doubled Tess's revenue leaves the table at 14 lines and $549.87. Tables with one row per order merge on the key. The lake overwrites one day's folder.

Nora adds one test: run every load twice on the same input, then compare row counts, COUNT(*) against COUNT(DISTINCT key), and totals. They must not move.

A safe rerun fixes rows that were written twice. It does nothing for rows that were not there when the run happened. Lesson 6.4 is about data that arrives late.

In one line

A load is idempotent when a rerun changes nothing: delete-then-insert the batch, merge on the key or overwrite the partition, and never append blindly.

Interview corner

What is idempotency, and why does it matter for data pipelines?

A step is idempotent if running it twice leaves the same result as running it once. It matters because reruns are normal: schedulers retry, people rerun after fixes, backfills reprocess history. A non-idempotent load (a plain append) silently doubles data on every retry.

Delete-then-insert or MERGE: how do you choose?

Delete-then-insert when each run owns a clean slice of the target, like one day of sales: delete the slice and write it again in one transaction. MERGE when incoming rows can update rows from earlier batches, like an order placed yesterday that shipped today, matched on its key. In a lake, overwriting the partition is the file-level version of delete-then-insert.

Can a pipeline deliver data exactly once? What does "exactly-once" in Kafka or Spark really mean?

Delivery cannot be exactly-once in general: a sender that loses an acknowledgement cannot tell success from failure, so it must retry, which is at-least-once. What Kafka (idempotent producer, transactions, read_committed consumers) and Spark (replayable source, checkpointed offsets, idempotent sink) give is an exactly-once effect within their scope. End to end, I get effectively-once by making every write absorb repeats: a merge on a business key, delete-then-insert by partition, or an idempotency key such as pipeline plus logical date recorded in a ledger in the same transaction as the data.

How would you test that a pipeline is idempotent?

Run it twice on the same input (and once more after a simulated failure half-way) and compare: row counts, COUNT(*) against COUNT(DISTINCT key), and totals such as revenue must not change. I would make that a test in CI, not a one-off check.