Sub topic 10
Why upserts are safe under concurrency
This chapter explains why INSERT ... ON CONFLICT stays correct when many sessions write the same key at once, and why the common "check, then insert" pattern does not. It assumes you can write INSERT ... ON CONFLICT DO UPDATE, you know what EXCLUDED is, and you know the basics of transactions and isolation levels in PostgreSQL. The examples use the product_stock table from earlier chapters.
CREATE TABLE product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);The race in SELECT-then-INSERT
Many applications emulate an upsert in two steps. They look for the row, then insert it if it is missing or update it if it exists.
-- Session A and session B both run this logic for sku 'C-300'.
BEGIN;
SELECT quantity FROM product_stock WHERE sku = 'C-300';
-- Both sessions see zero rows, so both decide to insert.
INSERT INTO product_stock (sku, quantity) VALUES ('C-300', 1);
COMMIT;The SELECT and the INSERT are separate statements, and nothing connects them. Under READ COMMITTED, each statement takes a fresh snapshot. A snapshot is the set of committed rows a statement can see. Session A can commit between B's SELECT and B's INSERT. B's SELECT then saw "no row", but by the time B inserts, the row exists. B fails with a unique violation (SQLSTATE 23505).
The check can never be trusted, because it describes the past. Wrapping the two statements in one transaction does not help, since transaction boundaries do not stop another session from inserting.
A read-modify-write update has a related problem: a lost update.
-- Application code reads quantity = 10, adds 3 in memory, then writes 13.
SELECT quantity FROM product_stock WHERE sku = 'A-100';
UPDATE product_stock SET quantity = 13 WHERE sku = 'A-100';If two sessions each add 3 to the same starting value 10, both write 13 and one increment is lost. The correct total is 16.
What ON CONFLICT guarantees
The PostgreSQL documentation states the guarantee directly. ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome. If there is no independent error, one of those two outcomes happens, even under high concurrency. Your code never has to handle "the row appeared between my check and my write".
The guarantee has three parts:
- The check for an existing row and the write happen inside one statement. There is no gap for another session to use.
- If the key already exists, the existing row is locked before it is updated, so concurrent upserts on that key take turns.
- The update reads the latest committed version of the locked row, not an old snapshot.
The next section describes how the server does this.
How the server does it: speculative insertion
For each proposed row, PostgreSQL runs a loop. You do not write this loop, but knowing it explains the behavior you see.
- Look for a conflict. Check the arbiter index for an existing entry with the same key. The arbiter index is the unique index chosen by your conflict target.
- If a live conflicting row exists, lock that row and run the
DO UPDATE(or skip it forDO NOTHING). The update sees the newest committed version of the row. - If no conflict exists, insert the row speculatively. The server writes the new heap tuple and a provisional index entry, and the index insertion checks for a competing entry again.
- If a concurrent session inserted the same key in the meantime, the speculative row is abandoned and the loop starts again from step 1. This time step 1 finds the conflict.
If the conflicting row was inserted by a transaction that has not committed, the upsert waits for that transaction to finish. If it commits, the key is a conflict and the upsert takes the update path. If it aborts, the key is free and the upsert inserts.
Seeing it with two sessions
You can reproduce the wait in two psql windows. Run these steps in order.
-- Session A
BEGIN;
INSERT INTO product_stock (sku, quantity)
VALUES ('C-300', 1)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity;
-- Do not commit yet.-- Session B (blocks until A finishes)
INSERT INTO product_stock (sku, quantity)
VALUES ('C-300', 1)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity;-- Session A
COMMIT;
-- Session B now completes. Check the result:
SELECT sku, quantity FROM product_stock WHERE sku = 'C-300';
-- quantity = 2: both increments counted, with no error and no lost update.The expression product_stock.quantity + EXCLUDED.quantity is safe because it runs against the locked, latest version of the row. The application-side version (read 10, write 13) is not safe, because the arithmetic uses a value read earlier.
Isolation levels
The guarantee holds at every isolation level, but the failure mode differs.
| Isolation level | Conflicting row committed after your statement began | Result |
|---|---|---|
| `READ COMMITTED` (default) | The statement takes the latest committed row, locks it, and proceeds. | Upsert succeeds. |
| `REPEATABLE READ` | The row is not visible to the transaction's snapshot. | Error `40001` (serialization failure). |
| `SERIALIZABLE` | Same as above, plus serialization checks on reads and writes. | Error `40001` possible. |
Under READ COMMITTED, DO UPDATE can modify a row that a plain SELECT in the same transaction could not see before the statement began. This is deliberate. The statement always works on the newest committed state.
Under REPEATABLE READ and SERIALIZABLE, a transaction must behave as if it saw one snapshot. Updating a row that appeared after the snapshot would break that promise, so PostgreSQL raises a serialization failure instead. The same applies to a DO NOTHING that skips such a row. Code running at these levels must retry the whole transaction on SQLSTATE 40001.
-- Retry the entire transaction if it fails with SQLSTATE 40001.
BEGIN ISOLATION LEVEL REPEATABLE READ;
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 1)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity;
COMMIT;Locking details that affect your design
DO UPDATE locks the row, DO NOTHING does not
When DO UPDATE finds a conflict, it locks the row even if a WHERE clause then rejects the update. The lock lasts until your transaction ends. A long transaction that upserts a hot key keeps other writers of that key waiting.
DO NOTHING skips a conflicting row without locking it. Because it takes no lock, it makes no promise about the state of that row afterwards. Another session may update or delete the row immediately after you skip it. If you need the row to stay stable, use DO UPDATE with a harmless change, or lock the row explicitly with SELECT ... FOR UPDATE after the upsert.
Only the arbiter index is handled
ON CONFLICT (sku) handles conflicts on the index that matches sku. A violation of a different unique index on the same table still raises an error.
ALTER TABLE product_stock ADD COLUMN barcode text UNIQUE;
INSERT INTO product_stock (sku, quantity, barcode)
VALUES ('D-400', 1, '123')
ON CONFLICT (sku) DO NOTHING;
-- If another row already has barcode '123', this raises a unique violation
-- on the barcode index, even though the conflict target is sku.ON CONFLICT DO NOTHING without a conflict target treats every unique index as an arbiter. DO UPDATE always requires a target.
Deadlocks across multi-row upserts
A multi-row upsert locks rows one at a time, in the order the rows are processed. Two statements that touch the same keys in opposite orders can deadlock.
-- Session A
INSERT INTO product_stock (sku, quantity)
VALUES ('X-1', 1), ('X-2', 1)
ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity;
-- Session B, concurrently, with the keys in the opposite order
INSERT INTO product_stock (sku, quantity)
VALUES ('X-2', 1), ('X-1', 1)
ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity;If A holds X-1 and B holds X-2, each waits for the other. PostgreSQL detects this after deadlock_timeout (1 second by default) and aborts one session with SQLSTATE 40P01. To prevent it, feed the rows in a consistent order, such as sorted by key.
INSERT INTO product_stock (sku, quantity)
SELECT sku, quantity
FROM (VALUES ('X-2', 1), ('X-1', 1)) AS v(sku, quantity)
ORDER BY sku
ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity;Remember from the batch chapter that the same key must not appear twice in one statement.
A conditional update under concurrency
A WHERE clause on DO UPDATE is evaluated after the row is locked, against the latest version. This makes it suitable for optimistic rules such as "only accept newer data".
ALTER TABLE product_stock ADD COLUMN source_version integer NOT NULL DEFAULT 0;
INSERT INTO product_stock (sku, quantity, source_version)
VALUES ('A-100', 9, 7)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
source_version = EXCLUDED.source_version
WHERE product_stock.source_version < EXCLUDED.source_version
RETURNING sku, quantity, source_version;If two writers race with versions 7 and 8, the outcome does not depend on arrival order. Version 8 always wins. If 8 lands first, version 7 finds a higher stored version, skips the update, and returns no row. Because the check runs on the locked row, the rule cannot be bypassed by a race.
Costs that remain
Safety does not make the statement free.
- Contention. Many sessions upserting one hot key serialize on that row's lock. Throughput on that key is limited by how fast transactions commit.
- Abandoned speculative rows. An insertion that loses a race leaves a dead tuple (a row version nobody can see) that vacuum must clean up.
- Sequence gaps. A column fed by an identity or
serialdefault consumes a sequence value even when the upsert takes the update path, so ids have gaps. - Error handling is still needed. Deadlocks, serialization failures, and violations of non-arbiter indexes can still occur, and the caller must handle them.
Comparison with MERGE
MERGE (PostgreSQL 15 and later) joins source rows to the target and decides per row between insert and update. It does not use speculative insertion on a unique index. If a concurrent session inserts a matching row between MERGE evaluating "not matched" and performing its insert, MERGE can raise a unique violation. For a single-key upsert on a unique constraint under concurrent writers, INSERT ... ON CONFLICT is the safer choice. Use MERGE when you need DELETE actions, several WHEN conditions, or matching on a condition that is not backed by a unique index.
Exercise
Two sessions run SELECT quantity FROM product_stock WHERE sku = 'E-500' and both find no row. Both then run a plain INSERT for 'E-500'. What happens, and which single statement removes the problem?
Show answer
The first INSERT to commit succeeds. The second fails with a unique violation (SQLSTATE 23505), because its SELECT result was stale by the time it inserted. Replacing the two steps with INSERT ... ON CONFLICT (sku) DO UPDATE (or DO NOTHING if skipping is acceptable) makes the existence check and the write one atomic statement, so the second session takes the conflict path instead of failing.
Exercise
A transaction at REPEATABLE READ runs INSERT ... ON CONFLICT (sku) DO UPDATE for a sku that another session inserted and committed after this transaction's snapshot was taken. What does PostgreSQL do, and what should the application do?
Show answer
PostgreSQL raises a serialization failure (SQLSTATE 40001, "could not serialize access due to concurrent update"), because the conflicting row is not visible to the transaction's snapshot and updating it would break snapshot consistency. The application should roll back and retry the whole transaction, which takes a new snapshot that can see the committed row.
Exercise
Why can two concurrent batch upserts on the same keys deadlock, and how do you prevent it?
Show answer
Each statement locks conflicting rows in the order it processes them. If one statement holds X-1 and wants X-2 while the other holds X-2 and wants X-1, they wait on each other, and PostgreSQL aborts one with SQLSTATE 40P01. Prevent it by feeding the rows in the same order in every statement, for example with ORDER BY sku in the SELECT that supplies the rows, and by keeping transactions short.