Sub topic 13
Concurrent Writers and Why the Constraint Matters
This chapter assumes you can write the INSERT ... ON CONFLICT statement from earlier chapters. It also assumes the customers table has a unique constraint on (source_system, external_id). Here you will see what goes wrong when two writers load the same record at the same time, and why the constraint is what makes the upsert safe.
The check-then-insert race
Before upserts, many loaders used two steps. They looked for the record, then inserted it or updated it depending on what they found.
SELECT id FROM customers
WHERE source_system = 'crm' AND external_id = 'C-1001';
-- if no row came back:
INSERT INTO customers (source_system, external_id, name)
VALUES ('crm', 'C-1001', 'Ada Lovelace');This works when one process runs at a time. With two processes, both can run the SELECT before either runs the INSERT. Both see no row, and both decide to insert.
What happens at the last step depends on the schema.
| Schema | Result of the race |
|---|---|
| No unique constraint | Both inserts succeed and you have two rows for one customer. |
| Unique constraint, check-then-insert code | The second insert fails with an error, and the loader must catch it and retry. |
| Unique constraint, `ON CONFLICT` upsert | The second statement becomes an update. No error and no duplicate. |
Application code cannot close this gap, because the time between the check and the write is outside your control. Only the database can compare and write as a single step.
How the constraint closes the gap
A unique constraint is backed by a unique index. When PostgreSQL inserts a row, it checks that index as part of the same operation. If a concurrent transaction has inserted the same key but not yet committed, the second writer waits. If the first transaction commits, the second hits the conflict. If it rolls back, the second proceeds with its insert.
ON CONFLICT DO UPDATE uses this behavior. When it detects a conflict, it locks the existing row and runs the update on it. Two concurrent upserts of C-1001 therefore end up with one row, and the later writer's values are applied after the earlier writer's.
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
RETURNING id;The conflict target must match a unique index. If it does not, PostgreSQL refuses the statement with an error like there is no unique or exclusion constraint matching the ON CONFLICT specification. Without the constraint you cannot even write the safe version.
Remaining problems
The constraint stops duplicate rows, but concurrency can still cause other trouble.
- Last writer wins. If two loads carry different values for
C-1001, whichever commits last is kept, even when its data is older. Use the stale guard from the previous chapter, which comparessource_updated_at, so older data cannot overwrite newer data. - Deadlocks in batches. Batch A locks
C-1001thenC-1002. Batch B locksC-1002thenC-1001. Each waits for the other, and PostgreSQL aborts one with a deadlock error. Sort each batch by key before sending it so every writer locks rows in the same order, and retry the aborted batch. - Duplicates in one batch. A single statement cannot update the same row twice. PostgreSQL raises
ON CONFLICT DO UPDATE command cannot affect row a second time. Deduplicate within the batch first, as covered earlier.
Practical checklist
- Create the unique constraint before the first load, not after you notice duplicates. Adding it later fails until you clean the existing duplicates.
- Use one atomic
INSERT ... ON CONFLICTstatement per record, or per batch. - Normalize external IDs before writing.
c-1001andC-1001are different keys to the index. - Sort batches by key and retry on deadlock errors.
Exercise
Two loaders upsert the same customer at the same moment, and the table has no unique constraint on (sourcesystem, externalid). What goes wrong, and what is the fix?
Show answer
PostgreSQL rejects the statement because ON CONFLICT needs a matching unique index. If a check-then-insert approach is used instead, both writers can insert and you get two rows for one customer. The fix is to add a unique constraint on (sourcesystem, externalid) after removing existing duplicates, then use INSERT ... ON CONFLICT DO UPDATE so the database resolves the race.