Sub topic 6
Running the same load twice safely
This chapter assumes you know basic SQL (INSERT, UPDATE, SELECT, primary keys) and have seen a unique constraint. It builds on the customers table and the ON CONFLICT upsert from the previous chapters.
What idempotent means
An operation is idempotent if running it once or many times leaves the data in the same state. Loads fail halfway, schedulers retry, and people click "run" twice. If your load is idempotent, none of these cause damage. You rerun it and move on.
A plain INSERT is not idempotent. The second run either fails on a unique constraint or, without one, creates duplicate rows. An upsert keyed on a unique external ID is idempotent because the second run finds the existing rows and updates them with the same values.
The working model
The match key decides everything. The database looks up the incoming (source_system, external_id) pair in the unique index. If it finds a row, it takes the DO UPDATE branch. If not, it inserts.
Seeing it in code
This script runs the same batch twice against an in-memory SQLite database. SQLite supports the same ON CONFLICT ... DO UPDATE form used in PostgreSQL.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"external_id TEXT NOT NULL UNIQUE, "
"name TEXT NOT NULL)"
)
rows = [("C-1001", "Ada Lovelace"), ("C-1002", "Grace Hopper")]
sql = (
"INSERT INTO customers (external_id, name) VALUES (?, ?) "
"ON CONFLICT(external_id) DO UPDATE SET name = excluded.name"
)
conn.executemany(sql, rows)
conn.executemany(sql, rows) # second run changes nothing
print(conn.execute("SELECT COUNT(*) FROM customers").fetchone()[0]) # 2The count is 2 after both runs. The internal id values also stay the same, because the second run updates rows and does not delete and recreate them. That matters when other tables reference customers.id.
What idempotent does not mean
Idempotence is about the final state, so the update must be deterministic. These patterns break it:
- Setting a column to
now()on every update. The row changes on each rerun. Fine for an audit column, but not if you compare snapshots. - Incrementing a counter, such as
visits = visits + 1. Each rerun adds again. - Appending to a text or array column instead of replacing it.
- Reading the loaded values from something that changes between runs, such as a source that is still being edited.
Assign values from the incoming row (EXCLUDED.name), and the result depends only on the input.
Rerunning after a partial failure
Suppose a load of 10,000 records crashes after 6,000. With a plain insert you must work out which rows landed and load only the rest. With an idempotent upsert you rerun the whole load. The first 6,000 are updated with the same values, and the remaining 4,000 are inserted. For this to be safe, wrap each batch in a transaction so a failed batch leaves no partial writes, and rerun from the start or from the last committed batch.
Checking idempotence
A simple test has three steps:
- Run the load and record the row count.
- Run it again with the same input.
- Confirm the count is unchanged and that a checksum or sample of the non-audit columns matches.
Exercise
A teammate's load uses INSERT ... ON CONFLICT (source_system, external_id) DO UPDATE SET login_count = customers.login_count + 1. After a retry, some customers show a higher login_count than the source does. Is this load idempotent, and how would you fix it?
Show answer
It is not idempotent. The row count stays correct because the unique constraint prevents duplicates, but the update depends on the stored value, so each rerun adds 1 again. Fix it by assigning the value from the incoming row: SET login_count = EXCLUDED.login_count. Then the result depends only on the input, and reruns give the same state.