Full answer
Setup for the example:
sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);sql
BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 2;Result on PostgreSQL 17:
text
balance
---------
300
(1 row)In a second session:
sql
UPDATE accounts SET balance = balance + 100 WHERE id = 2;Result:
text
UPDATE 1sql
UPDATE accounts SET balance = balance - 50 WHERE id = 2;Output:
text
ERROR: could not serialize access due to concurrent updatesql
ROLLBACK; BEGIN ISOLATION LEVEL REPEATABLE READ; UPDATE accounts SET balance = balance - 50 WHERE id = 2; COMMIT; SELECT balance FROM accounts WHERE id = 2;PostgreSQL returns:
text
balance
---------
350
(1 row)A's snapshot shows 300. B adds 100 and commits. A's update would be based on a stale view, so it fails with the serialization error rather than silently losing B's deposit. After rolling back, the retried transaction sees 400 and ends at 350, the correct result. Retry loops should cover the whole transaction, including its reads, and cap the number of attempts. Under READ COMMITTED the same update would instead wait for B and then apply to the new row version, which is fine for simple increments but not for decisions based on earlier reads.
sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);
BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 2;
-- session B
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
UPDATE accounts SET balance = balance - 50 WHERE id = 2;
ROLLBACK; BEGIN ISOLATION LEVEL REPEATABLE READ; UPDATE accounts SET balance = balance - 50 WHERE id = 2; COMMIT; SELECT balance FROM accounts WHERE id = 2;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Concurrent updates fail under REPEATABLE READ
- SQLSTATE 40001 means retry
- Retry the whole transaction
- Prevents lost updates
- READ COMMITTED re-applies to the new row instead
Common mistakes
- Retrying only the failing statement
- Treating 40001 as a fatal error
Follow-ups
- How does SERIALIZABLE differ?
- How would you write a retry decorator for 40001?
Tips
- Name the SQLSTATE