Sub topic 6
Running the Same Load Twice Safely
This chapter assumes you can write basic SQL INSERT and UPDATE statements. It also assumes you have seen the customers table with a unique constraint on (source_system, external_id) and the INSERT ... ON CONFLICT DO UPDATE statement from the previous chapters. The Python example uses the standard sqlite3 module, which needs SQLite 3.24 or newer for ON CONFLICT.
What idempotent means
An operation is idempotent if running it once or running it many times leaves the system in the same final state. For a data load, this means that loading the same batch twice gives the same table contents as loading it once.
Loads get repeated more often than you might expect:
- A job crashes halfway through and the scheduler retries it from the start.
- An operator reruns a load by hand because they are not sure it finished.
- Two scheduled runs overlap because the first took longer than its interval.
- A message queue delivers the same message twice, which most queues allow ("at least once" delivery).
- The source system resends records after an outage.
If your load is not idempotent, each of these produces duplicate rows or wrong values. If it is idempotent, you can retry freely and never need to work out how far the previous run got.
Why a plain INSERT is not idempotent
A plain INSERT always adds a row. Without a unique constraint, the second run adds copies of every record. With a unique constraint, the second run fails with a constraint violation, which stops the load and may leave it half applied.
The following script shows both outcomes side by side. The first table has no constraint and a plain insert. The second has a unique external_id and uses an upsert.
import sqlite3
rows = [("C-1001", "Ada Lovelace"), ("C-1002", "Grace Hopper")]
def count(conn):
return conn.execute("SELECT COUNT(*) FROM customers").fetchone()[0]
def snapshot(conn):
return conn.execute(
"SELECT id, external_id, name FROM customers ORDER BY id"
).fetchall()
# Naive load: plain INSERT, no unique constraint.
naive = sqlite3.connect(":memory:")
naive.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"external_id TEXT NOT NULL, "
"name TEXT NOT NULL)"
)
for _ in range(2):
naive.executemany(
"INSERT INTO customers (external_id, name) VALUES (?, ?)", rows
)
print("naive rows after two runs:", count(naive)) # 4
# Idempotent load: unique key plus upsert.
safe = sqlite3.connect(":memory:")
safe.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"external_id TEXT NOT NULL UNIQUE, "
"name TEXT NOT NULL)"
)
upsert = (
"INSERT INTO customers (external_id, name) VALUES (?, ?) "
"ON CONFLICT(external_id) DO UPDATE SET name = excluded.name"
)
safe.executemany(upsert, rows)
after_first = snapshot(safe)
safe.executemany(upsert, rows)
after_second = snapshot(safe)
print("safe rows after two runs:", count(safe)) # 2
print("same state after rerun:", after_first == after_second) # TrueThe check compares the full contents of the table, including the internal id values, not just the row count. A matching count can hide a load that rewrote rows with new ids. Here the second run finds each existing row through the unique key and updates it in place, so the ids stay the same.
What makes an upsert idempotent
Three properties together make the statement safe to repeat:
- A unique constraint on the match key. The database decides whether a row already exists. Your application does not check first.
- Values that come only from the incoming row.
SET name = EXCLUDED.nameproduces the same result however many times it runs, because the result depends on the input and not on the current state. - No side effects that accumulate. Anything that depends on how many times the statement ran breaks idempotency.
Patterns that break idempotency
Some upserts look safe and are not. Watch for these.
| Pattern | Why it breaks | Safer version |
|---|---|---|
| `SET visits = customers.visits + EXCLUDED.visits` | Each rerun adds the amount again | `SET visits = EXCLUDED.visits`, if the source sends totals |
| `SET updated_at = now()` | The value changes on every run, so the final state differs | Store the source's timestamp, or accept that this column is audit data |
| `SET load_count = customers.load_count + 1` | Counts runs, not records | Remove it, or keep run history in a separate log table |
| Plain `INSERT` into a child or log table in the same job | Adds a new row on every run | Give that table its own unique key and upsert into it too |
| Matching on `name` or another non-unique column | Different records collapse or duplicate | Match on `(source_system, external_id)` |
Accumulating values deserve a second look. Sometimes you really do want to add to a number, such as applying a delta from an event stream. In that case idempotency has to come from somewhere else, such as recording the event id in a table with a unique constraint and skipping events you have already applied.
Avoiding pointless writes
By default, DO UPDATE rewrites the row even when nothing changed. In PostgreSQL this still creates a new row version, adds work for vacuum, and fires update triggers. On a large rerun where almost nothing changed, that is a lot of wasted work.
Add a WHERE clause that compares the old and new values:
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name,
email = EXCLUDED.email
WHERE (customers.name, customers.email)
IS DISTINCT FROM (EXCLUDED.name, EXCLUDED.email)
RETURNING id;IS DISTINCT FROM treats two NULL values as equal. A plain <> would return NULL when either side is NULL, and the update would be skipped even when a value had changed from NULL to something else.
This statement has one side effect to know about. When the WHERE clause is false, no row is updated, and PostgreSQL does not return that row from RETURNING. A rerun of an unchanged record therefore returns zero rows. If your code needs the internal id of every record, either drop the WHERE clause or look the id up with a separate SELECT on the external ID.
DO NOTHING versus DO UPDATE
ON CONFLICT ... DO NOTHING is also idempotent, and it is the right choice when the source never changes a record after creating it. It is wrong when records can be corrected, because a later change in the source is silently ignored. Choose DO UPDATE unless you know the source data is immutable.
Sequence gaps on reruns
In PostgreSQL, a bigserial or identity column takes its next value before the database checks for a conflict. When a row conflicts and is updated, the value that was reserved is thrown away. After several reruns, the id values of new rows will have gaps.
The existing rows keep their ids, so the load is still idempotent in the sense that matters. Gaps only matter if something treats ids as gapless, and nothing should. Do not try to fix gaps by resetting the sequence.
Making a failed run safe to retry
Idempotency covers retries after a crash, but only if a half-finished run leaves nothing worse than a partial result. Two habits help:
- Wrap each batch in a single transaction, so a failure rolls back that batch completely.
- Do not delete and reload as a way to be "clean". A job that runs
DELETE FROM customersand then inserts leaves the table empty or short if it crashes in between, and it breaks any foreign keys that point at the deleted rows.
With both in place, a retry starts from either the state before the batch or the state after it. Neither state breaks the rerun.
Summary of the checks
A load is safe to run twice when:
- the match key has a unique constraint,
- every updated column is set from
EXCLUDEDand not computed from the old value, - no job step appends rows without its own unique key,
- each batch runs inside a transaction, and
- a rerun in a test database leaves an identical snapshot.
Exercise
This upsert runs nightly. After three nights of the same input file, the orders_seen column holds 3 for every customer. Explain why, and show a change that makes the load idempotent.
INSERT INTO customers (sourcesystem, externalid, name, ordersseen)
VALUES ('crm', 'C-1001', 'Ada Lovelace', 1)
ON CONFLICT (sourcesystem, externalid)
DO UPDATE SET name = EXCLUDED.name,
ordersseen = customers.ordersseen + EXCLUDED.ordersseen;
Show answer
The update adds the incoming value to the stored value, so its result depends on how many times it has run. Each rerun of the same file adds 1 again. To make it idempotent, replace the assignment with orders_seen = EXCLUDED.orders_seen, which works if the source sends the current total. If the source only sends per-event deltas, record each event id in a table with a unique constraint and apply only events not seen before.
Exercise
You add WHERE (customers.name, customers.email) IS DISTINCT FROM (EXCLUDED.name, EXCLUDED.email) to an upsert that ends in RETURNING id. On a rerun with unchanged data, the statement returns no rows. Is the load still idempotent, and what must you change if your code needs the id for every record?
Show answer
The load is still idempotent, because the table ends in the same state. The statement returns no rows because PostgreSQL only returns rows that were inserted or updated, and the WHERE clause skipped the update. If you need every id, remove the WHERE clause and accept the extra writes, or run a separate SELECT id FROM customers WHERE source_system = ... AND external_id = ... for the records you need.