Sub topic 10
Concurrent updates, row locks and serialization failures
This chapter assumes you have read the earlier chapters on row versions, xmin/xmax, snapshots, and isolation levels as snapshot timing. It also assumes you can open two psql sessions against the same database. Readers never block writers under MVCC, but two writers that touch the same row still have to be ordered. This chapter covers how PostgreSQL does that and what error your application sees when the ordering fails.
Why writers still conflict
A snapshot lets a query read old versions of a row freely. An UPDATE or DELETE is different, because it must create a new version from the newest version of the row. If another transaction has already changed that row, you cannot build on the old version without silently discarding the other change. That would be a lost update.
PostgreSQL checks the xmax of the version it is about to change. Three cases are possible:
xmaxis 0, or it belongs to a transaction that aborted. The row is free, and the update proceeds.xmaxbelongs to a transaction that is still in progress. The update waits for that transaction to finish.xmaxbelongs to a transaction that committed. What happens next depends on the isolation level.
Waiting on another writer
When a transaction must wait, it does not wait on the row itself. It waits on the transaction ID of the transaction that holds the row. You can see this in pg_locks, where the waiter requests a transactionid lock with granted = false. When the holder commits or rolls back, it releases its own transaction ID lock and the waiter wakes up.
Try it with two sessions:
-- Setup (once)
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100);
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- Session B (blocks, no output yet)
UPDATE accounts SET balance = balance + 5 WHERE id = 1;
-- Session C: see who waits for whom
SELECT pid, locktype, transactionid, granted
FROM pg_locks
WHERE locktype = 'transactionid';
-- Session A
COMMIT;
-- Session B now finishesSession C shows one granted lock (Session A's own transaction ID) and one ungranted request (Session B). pg_blocking_pids(pid) gives the same answer more directly.
What happens after the wait: Read Committed
When the other transaction commits, a Read Committed UPDATE does not fail. It re-reads the newest version of the row and checks whether the row still satisfies your WHERE clause. If it does, your update applies to that newer version. If it no longer matches, the row is skipped.
This is why SET balance = balance + 5 is safe in Read Committed. The expression is evaluated against the latest committed value, so Session B in the example above ends with 95, not 105.
The re-check applies only to the row being updated. The rest of your statement keeps its original snapshot. A statement that mixes a subquery with an update can therefore see slightly inconsistent data.
The read-then-write trap
The re-check does not save you when the application reads a value, computes in its own code, and writes the result back:
-- Session A (Read Committed)
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- 100; the app computes 100 - 10
-- Session B
UPDATE accounts SET balance = balance + 50 WHERE id = 1; -- commits, balance 150
-- Session A
UPDATE accounts SET balance = 90 WHERE id = 1; -- overwrites B's +50
COMMIT;Nothing failed, and B's deposit is gone. There are three common fixes:
- Do the arithmetic in SQL, as in
SET balance = balance - 10. - Lock the row when you read it, with
SELECT ... FOR UPDATE. - Use Repeatable Read or Serializable and retry on failure.
What happens after the wait: Repeatable Read
A Repeatable Read transaction must keep seeing one consistent snapshot. Updating a version that committed after that snapshot would break the guarantee. So PostgreSQL raises an error instead:
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1;
-- Session B
UPDATE accounts SET balance = balance + 10 WHERE id = 1;
-- Session A
UPDATE accounts SET balance = balance - 5 WHERE id = 1;
-- ERROR: could not serialize access due to concurrent update
ROLLBACK;The error has SQLSTATE 40001 (serialization_failure). The transaction is now aborted, and the only way forward is ROLLBACK and a retry from the start. The same error can occur on DELETE, SELECT ... FOR UPDATE, and the other locking reads when the target row was changed after your snapshot.
Row locks live in the tuple
Locking a row with SELECT ... FOR UPDATE does not use a shared-memory lock table. PostgreSQL writes your transaction ID into the row's xmax and sets lock bits in the tuple header. Two consequences follow:
- There is no limit on how many rows you can lock, and no lock-table memory to exhaust.
- Locking a row dirties the heap page, so a large
SELECT ... FOR UPDATEgenerates disk writes and WAL.
You can see it for yourself:
BEGIN;
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
SELECT xmin, xmax, * FROM accounts WHERE id = 1; -- xmax is now your XID
ROLLBACK;When several transactions hold a lock on the same row at once, for example shared locks, one XID no longer fits in xmax. PostgreSQL stores a multixact ID there instead, which points to the set of lockers.
The four row lock modes
| Mode | Typical source | Conflicts with |
|---|---|---|
| `FOR KEY SHARE` | Foreign key checks | `FOR UPDATE` |
| `FOR SHARE` | Explicit read lock | `FOR NO KEY UPDATE`, `FOR UPDATE` |
| `FOR NO KEY UPDATE` | Ordinary `UPDATE` that does not change a key | `FOR SHARE`, `FOR NO KEY UPDATE`, `FOR UPDATE` |
| `FOR UPDATE` | `DELETE`, `UPDATE` of a key column, explicit lock | All four modes |
The split exists so that inserting a child row, which takes FOR KEY SHARE on the parent, does not block a plain update of a non-key column on that parent.
Controlling how long you wait
By default a writer waits forever. Three tools change that:
-- Fail immediately if the row is locked
SELECT * FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;
-- Skip locked rows (useful for job queues)
SELECT id FROM accounts ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
-- Give up after 2 seconds, for this session
SET lock_timeout = '2s';NOWAIT and lock_timeout raise an error, SQLSTATE 55P03 (lock_not_available). SKIP LOCKED returns a possibly inconsistent view of the table by design. Use it for work queues, not for reports.
Deadlocks
If transaction A holds row 1 and wants row 2, while B holds row 2 and wants row 1, neither can proceed. PostgreSQL does not detect this immediately. After a waiter has waited deadlock_timeout (1 second by default), it runs the cycle check. If it finds a cycle, it aborts one participant with SQLSTATE 40P01 (deadlock_detected).
The surest prevention is to touch rows in a consistent order, for example ORDER BY id in your locking query. A deadlock error, like a serialization failure, is safe to retry.
Serializable adds more failures
At the Serializable level, PostgreSQL uses Serializable Snapshot Isolation (SSI). It tracks read/write dependencies between transactions, even ones that never touch the same row. If it finds a dependency pattern that could not be reproduced by any serial order, it aborts one transaction. The error is again 40001, with a message such as could not serialize access due to read/write dependencies among transactions. A later chapter explains how SSI chooses the victim. For now, the practical point is that the application handles it the same way as the Repeatable Read failure.
Writing the retry loop
Treat 40001 and 40P01 as normal outcomes under concurrency, not as bugs. The whole transaction must be retried, including any reads that fed into it. This example uses psycopg 3:
import time
import psycopg
from psycopg import errors
def run_with_retry(conn, work, attempts=5):
for attempt in range(attempts):
try:
with conn.transaction():
return work(conn)
except (errors.SerializationFailure, errors.DeadlockDetected):
if attempt == attempts - 1:
raise
time.sleep(0.05 * 2 ** attempt)
def withdraw(conn):
bal = conn.execute(
"SELECT balance FROM accounts WHERE id = 1"
).fetchone()[0]
conn.execute(
"UPDATE accounts SET balance = %s WHERE id = 1", (bal - 5,)
)
conn = psycopg.connect("dbname=postgres")
conn.isolation_level = psycopg.IsolationLevel.REPEATABLE_READ
run_with_retry(conn, withdraw)The read-then-write in withdraw is safe here only because of the retry. If another transaction changes the row between the read and the write, the UPDATE fails, and the retry re-reads the new balance.
Summary of behavior
| Situation | Read Committed | Repeatable Read | Serializable |
|---|---|---|---|
| Row locked by an in-progress writer | Waits | Waits | Waits |
| Writer committed after wait | Re-checks `WHERE`, updates newest version | Error 40001 | Error 40001 |
| Dependency cycle without a shared row | No error | No error | Possible error 40001 |
| Lock cycle between waiters | Error 40P01 | Error 40P01 | Error 40P01 |
Exercise
Two sessions run at Read Committed. Session A runs BEGIN; UPDATE accounts SET balance = balance - 10 WHERE id = 1; and does not commit. Session B runs UPDATE accounts SET balance = balance + 5 WHERE id = 1; and then A commits. Starting from a balance of 100, what does B do while A is open, and what is the final balance?
Show answer
B waits on A's transaction ID. After A commits, B re-reads the newest version (90), re-checks the WHERE clause (it still matches), and applies +5 to it. The final balance is 95, with no error.
Exercise
The same scenario runs again, but Session B started with BEGIN ISOLATION LEVEL REPEATABLE READ and ran a SELECT before A's update committed. What happens to B's UPDATE, and what must the application do?
Show answer
B waits for A, and once A commits, B fails with ERROR: could not serialize access due to concurrent update (SQLSTATE 40001). B's transaction is aborted. The application must roll back and rerun the whole transaction, which takes a new snapshot that includes A's change.
Exercise
Why does SELECT ... FOR UPDATE on a million rows cause disk writes even though it returns data and changes no column values?
Show answer
Row locks are stored in the tuple header (xmax and lock bits), not in a lock table in memory. Locking a row therefore modifies its heap page, which makes the page dirty and generates WAL.