Sub topic 13
Concurrent Writers and Why the Constraint Matters
This chapter assumes you have read the earlier chapters of this tutorial. You should know what an external ID is, have a UNIQUE (source_system, external_id) constraint on your table, and have written an INSERT ... ON CONFLICT DO UPDATE statement. Examples use PostgreSQL, plus one Python script that runs on SQLite so you can reproduce the failure on any machine.
Why concurrency changes the problem
A sync job rarely runs alone. A nightly batch may overlap with a webhook handler, two workers may pull from the same queue, or a retry may start before the original attempt has finished. Any two of these can try to write the same external ID at nearly the same moment.
Most upsert bugs that appear only in production come from this overlap. The code looks correct when you test it with one writer.
The check-then-insert race
The most common hand-written upsert has two steps:
SELECTthe row by its external ID.- If nothing came back,
INSERT. Otherwise,UPDATE.
Each statement is correct on its own. The problem is the gap between them. Two writers can both run step 1 before either has run step 2. Both see no row, and both decide to insert.
<br>
Wrapping the two steps in a transaction does not fix this under the default isolation level. In PostgreSQL's default READ COMMITTED mode, writer B's SELECT does not see writer A's uncommitted insert, and it takes no lock that would make B wait.
Reproducing the race
The script below makes the interleaving deterministic. It opens two connections, runs both SELECT statements first, then runs both inserts. It does this twice, once without the unique constraint and once with it.
import os
import sqlite3
import tempfile
path = os.path.join(tempfile.mkdtemp(), "race.db")
FIND = (
"SELECT id FROM customers "
"WHERE source_system = 'crm' AND external_id = 'C-1001'"
)
INSERT = (
"INSERT INTO customers (source_system, external_id, name) "
"VALUES ('crm', 'C-1001', ?)"
)
def setup(with_unique):
if os.path.exists(path):
os.remove(path)
extra = ", UNIQUE (source_system, external_id)" if with_unique else ""
conn = sqlite3.connect(path)
conn.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"source_system TEXT NOT NULL, "
"external_id TEXT NOT NULL, "
"name TEXT NOT NULL" + extra + ")"
)
conn.commit()
conn.close()
def run(with_unique):
setup(with_unique)
a = sqlite3.connect(path)
b = sqlite3.connect(path)
# Both writers check first, and both see an empty table.
assert a.execute(FIND).fetchone() is None
assert b.execute(FIND).fetchone() is None
a.execute(INSERT, ("Ada Lovelace",))
a.commit()
try:
b.execute(INSERT, ("Ada Lovelace",))
b.commit()
except sqlite3.IntegrityError as exc:
b.rollback()
print(" writer B rejected:", exc)
count = a.execute("SELECT COUNT(*) FROM customers").fetchone()[0]
print(" rows stored:", count)
a.close()
b.close()
print("Without a unique constraint:")
run(with_unique=False)
print("With a unique constraint:")
run(with_unique=True)Without the constraint, the table ends up with two rows for one customer. With it, writer B receives an error and the table keeps one row. The constraint is what turns a silent data corruption into a loud, recoverable error.
What the constraint gives you
A unique constraint is enforced by a unique index, and the database checks that index at the moment of the write. This check is atomic. Two transactions cannot both insert the same key and both succeed.
When two transactions try to insert the same key, PostgreSQL makes the second one wait until the first commits or rolls back. Then:
- If the first transaction committed, the second one sees the conflict and fails with SQLSTATE
23505(unique_violation). - If the first transaction rolled back, the second one proceeds with its insert.
Application code cannot get this guarantee from a SELECT. Only the database can, because only the database sees every writer.
<br>
How ON CONFLICT resolves the race
INSERT ... ON CONFLICT DO UPDATE runs the check and the write as one atomic statement. It does not fail when two writers collide. Here is what happens when writers A and B upsert the same key at the same time:
- A inserts the row. It is not yet committed.
- B tries to insert the same key. It finds A's uncommitted row and waits.
- A commits. B stops waiting and takes the
DO UPDATEpath against the row A created. - B's update runs against the latest committed version of the row, not against a stale snapshot.
PostgreSQL documents this behavior: under ON CONFLICT DO UPDATE, each row proposed for insertion either inserts or updates, and this outcome is guaranteed even with concurrent activity. Your code needs no retry loop for the plain conflict case.
-- Session 1 -- Session 2
BEGIN;
INSERT INTO customers
(source_system, external_id, name)
VALUES ('crm', 'C-2001', 'First')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name;
BEGIN;
INSERT INTO customers
(source_system, external_id, name)
VALUES ('crm', 'C-2001', 'Second')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name;
-- blocks here, waiting for session 1
COMMIT;
-- unblocks, updates the row to 'Second'
COMMIT;The final row has the name Second. When two writers send different values for the same key, the last one to commit wins. If that is not acceptable, you need the stale guard described below.
Updates that depend on the current value
Because the update runs against the latest committed row, expressions that read the existing value are also safe:
INSERT INTO customers (source_system, external_id, name, sync_count)
VALUES ('crm', 'C-1001', 'Ada Lovelace', 1)
ON CONFLICT (source_system, external_id)
DO UPDATE SET sync_count = customers.sync_count + 1;This assumes you added a sync_count integer NOT NULL DEFAULT 0 column. Two concurrent runs produce a count of 2, not 1. A read in your application followed by a write of the computed value would lose one of the increments.
Concurrency and the stale guard
The WHERE clause on DO UPDATE from the earlier chapter is evaluated after the row lock is acquired. This matters when two writers carry different versions of the same record:
INSERT INTO customers (source_system, external_id, name, source_updated_at)
VALUES ('crm', 'C-1001', 'Ada King', '2026-11-30T12:00:00Z')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name,
source_updated_at = EXCLUDED.source_updated_at
WHERE customers.source_updated_at IS NULL
OR customers.source_updated_at < EXCLUDED.source_updated_at;If the worker holding the older record commits last, its update is skipped, because the stored timestamp is already newer. The outcome no longer depends on which worker finished first. Without the guard, arrival order decides which version survives.
Failure modes that remain
The constraint and ON CONFLICT close the duplicate-row race. Other concurrency problems still occur in upsert pipelines.
Deadlocks in batches
Suppose worker 1 upserts keys C-1, then C-2. Worker 2 upserts C-2, then C-1. Each holds a row lock the other needs, and PostgreSQL aborts one of them with SQLSTATE 40P01 (deadlock_detected).
The standard fix is to sort every batch by the unique key before sending it. All writers then lock rows in the same order, and a cycle cannot form.
INSERT INTO customers (source_system, external_id, name)
SELECT source_system, external_id, name
FROM (VALUES
('crm', 'C-1002', 'Grace Hopper'),
('crm', 'C-1001', 'Ada Lovelace')
) AS incoming(source_system, external_id, name)
ORDER BY source_system, external_id
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name;Duplicates within one statement
Sorting does not help if the same key appears twice inside one INSERT. PostgreSQL then raises 21000 with the message "ON CONFLICT DO UPDATE command cannot affect row a second time". Deduplicate the batch before sending it, as covered in the chapter on duplicate external IDs.
Stricter isolation levels
Under REPEATABLE READ or SERIALIZABLE, a concurrent change can cause a serialization failure (40001). Treat 40001 and 40P01 as retryable. Rerun the whole transaction, and rely on the upsert being idempotent to make the retry safe.
Gaps in generated IDs
A bigserial default is evaluated before the conflict is detected, so each conflicting upsert consumes a sequence value. Your internal id column will have gaps. This is harmless unless something treats those IDs as gap-free.
Normalization
A unique constraint compares exact values. C-1001 and c-1001 are different keys, so two writers that format the ID differently never conflict, and you get two rows. Normalize the external ID before it reaches the database, in every writer.
Summary of error codes
| SQLSTATE | Name | Cause | Response |
|---|---|---|---|
| 23505 | unique_violation | Plain `INSERT` hit an existing key | Switch to `ON CONFLICT`, or treat as already created |
| 21000 | cardinality_violation | Same key twice in one upsert statement | Deduplicate the batch |
| 40P01 | deadlock_detected | Writers lock rows in different orders | Sort by key; retry |
| 40001 | serialization_failure | Concurrent change under a strict isolation level | Retry the transaction |
<br>
Exercise
Two workers run a check-then-insert sync for external ID C-3001 at the same moment. The table has no unique constraint. What is the most likely result, and what is the smallest change that makes the outcome safe?
Show answer
Both workers run their SELECT before either inserts, both find no row, and both insert. The table ends up with two rows for C-3001. The smallest safe change is to add UNIQUE (sourcesystem, externalid) and replace the SELECT-then-INSERT logic with INSERT ... ON CONFLICT (sourcesystem, externalid) DO UPDATE. The constraint makes duplicates impossible, and ON CONFLICT makes the second writer update the existing row instead of failing.
Exercise
Two workers each upsert the batch of keys C-1 and C-2, but in opposite orders. Occasionally one of them fails with SQLSTATE 40P01. Why does this happen, and how do you prevent it?
Show answer
Each worker locks one row and then waits for the row the other worker has locked, which creates a deadlock. PostgreSQL aborts one transaction. Prevent it by sorting every batch by the unique key before the upsert so all workers acquire locks in the same order. Also retry the transaction if a deadlock still occurs, which is safe because the upsert is idempotent.