skip to content

A PostgreSQL concert-ticket reservation service moved to SERIALIZABLE and now logs SQLSTATE 40001 read/write dependency errors; how do you diagnose and reduce them?

level: seniorimportance: should knowfreq 36%

answer

  1. locks that never block anyone
  2. SIReadLock rows in pg_locks
  3. tuple, page, relation granularity
  4. sequential scans lock the whole table
  5. max_pred_locks_per_transaction

basics

~20 s

Treat some 40001s as normal, retried work, then cut the excess: find relation-level SIReadLock entries in pg_locks, index the filtered columns so scans lock pages not tables, raise the max_pred_locks limits, mark reports READ ONLY and keep transactions short.

solid answer

~40 s

PostgreSQL's `SERIALIZABLE` is **SSI**: REPEATABLE READ plus non-blocking **predicate locks** (`SIReadLock` in `pg_locks`) recording what each transaction read. When read/write conflicts chain through one transaction, a participant is cancelled with `could not serialize access due to read/write dependencies among transactions` (`40001`); the `DETAIL` gives a reason code. Some cancellations are false positives, and coarse locks cause more. Diagnose by grouping `SIReadLock` rows by relation and `locktype`: `relation`-level locks mean a sequential scan or lock promotion. Reduce by indexing the columns the transactions filter on; raising `max_pred_locks_per_transaction` (default 64, restart), `max_pred_locks_per_relation` (-2) and `max_pred_locks_per_page` (2); declaring reports `READ ONLY`; keeping transactions short and never idle in transaction; capping connections with a pool; and dropping redundant `SELECT ... FOR UPDATE`. The retry path stays mandatory.

code

sql · 7 lines
sql
CREATE INDEX CONCURRENTLY seats_event_status_idx ON seats (event_id, status);

ALTER ROLE ticketing_app SET default_transaction_isolation = 'serializable';

ALTER SYSTEM SET max_pred_locks_per_transaction = 256;  -- takes effect after a restart
ALTER SYSTEM SET max_pred_locks_per_page = 4;           -- reloadable
SELECT pg_reload_conf();

go deeper

for a junior

Recall that SERIALIZABLE in PostgreSQL can cancel transactions with SQLSTATE 40001 and that the application has to retry them.

for a middle

Explain that SSI tracks reads with non-blocking SIReadLock predicate locks and cancels a transaction when read/write conflicts chain through a pivot.

for a senior

Diagnose from pg_locks and the error DETAIL — relation-level SIReadLocks from sequential scans or promotion — then fix with indexes, the max_pred_locks limits, READ ONLY and short transactions.

for a principal

Set a tolerable failure budget for the service and judge whether SSI with retries beats explicit locking for the invariants it really has.

## How SSI decides to cancel PostgreSQL's **SERIALIZABLE** level is **Serializable Snapshot Isolation (SSI)**. It behaves exactly like REPEATABLE READ — one snapshot per transaction, first updater wins on the same row — and adds **monitoring**. Each serializable transaction takes **predicate locks** on what it reads: tuples, pages, or whole relations. These are not ordinary locks: they never block anyone and cannot take part in a deadlock. They only let the server notice a **read/write conflict**, where one transaction writes data that a concurrent transaction read without seeing the write. A single conflict is harmless. The danger is a transaction with a conflict coming in *and* one going out — a **pivot** between two others. When that structure appears and the commit order could close it into a cycle, PostgreSQL cancels one of the transactions with SQLSTATE `40001`. Not every such structure is part of a real cycle, so some cancellations are **false positives**: the transactions would have produced a serial result after all. Coarser locks widen the net and produce more of them. The monitoring adds no blocking beyond REPEATABLE READ, except that a `READ ONLY DEFERRABLE` transaction may wait at its start for a safe snapshot. ## Reading the error The message is `could not serialize access due to read/write dependencies among transactions`, with the hint `The transaction might succeed if retried.` The `DETAIL` line carries a reason code naming the check that fired, for example: - `Reason code: Canceled on identification as a pivot, during commit attempt.` - `Reason code: Canceled on identification as a pivot, during write.` - `Reason code: Canceled on conflict out to pivot ..., during read.` Logged together with the statement, these show which code paths act as pivots most often — usually a transaction that both reads a range of rows and writes into it. ## Finding coarse predicate locks While the load runs, sample the predicate locks: ```sql SELECT relation::regclass AS rel, locktype, count(*) FROM pg_locks WHERE mode = 'SIReadLock' GROUP BY 1, 2 ORDER BY 3 DESC; ``` Many `tuple` or `page` rows on `seats` are fine. A `relation` row on `seats` means some transaction holds a predicate lock on the whole table, so *any* concurrent write to `seats` conflicts with it. There are two causes: 1. A **sequential scan** always takes a relation-level predicate lock. `SELECT count(*) FROM seats WHERE event_id = 42 AND status = 'held'` without a usable index locks the seats of every event. 2. **Promotion**: more than `max_pred_locks_per_page` locked tuples on one page become a page lock, and more than `max_pred_locks_per_relation` locked pages or tuples in one relation become a relation lock. A shared lock table running short also forces promotion, and an exhausted one raises `out of shared memory` with a hint to raise `max_pred_locks_per_transaction`. ## Levers that lower the failure rate | Lever | Why it helps | Cost | |---|---|---| | Index the filter columns, e.g. `(event_id, status)` | index scans lock pages and tuples, not the table | index write overhead | | Raise `max_pred_locks_per_transaction` (default 64, needs a restart) | larger shared lock table, less forced promotion | shared memory | | Raise `max_pred_locks_per_relation` (default -2: the per-transaction value divided by 2) and `max_pred_locks_per_page` (default 2), both reloadable | finer locks survive longer before promotion | more lock entries | | Declare reports `READ ONLY` | read-only transactions can often skip or release predicate locks early | none | | Short transactions, nobody idle in transaction | predicate locks outlive commit until overlapping read/write transactions finish | discipline; `idle_in_transaction_session_timeout` can enforce it | | Fewer active connections, through a pool | fewer overlapping transactions to conflict | queueing | | Remove now-redundant `SELECT ... FOR UPDATE` | SSI already protects the rule; the lock only adds blocking | code change | The manual also suggests nudging the planner toward index scans by lowering `random_page_cost` or raising `cpu_tuple_cost`, weighed against any change in query time. ## What must stay true - **Retries are part of the design.** A tuned system still cancels some transactions, so every serializable transaction needs a wrapper that reruns it on `40001`. - **Every writer must be serializable.** A writer at READ COMMITTED or REPEATABLE READ is outside the conflict tracking, and the guarantee leaks. A role-level `default_transaction_isolation = 'serializable'` helps keep stragglers out. - **A unique violation can be a disguised serialization failure.** Two serializable transactions that both see a key is free and insert it can get `23505` rather than `40001`, unless every inserter checks for the key first. - **Hot standbys are outside the guarantee**: SERIALIZABLE is not available there, and reads on a replica can see states no serial order would produce.

  • Why does a PostgreSQL SERIALIZABLE transaction sometimes fail at COMMIT rather than at the statement that read or wrote the conflicting data?
    SSI cancels only once a dangerous structure is complete and the commit order makes a cycle possible; PostgreSQL waits until a transaction at the far end of the chain has committed first. So the check can fire during a read, a write or the commit attempt, and the `DETAIL` reason code says which. Application code must treat a failed `COMMIT` exactly like any other `40001` and rerun the transaction.
  • Do SIReadLock entries disappear from pg_locks when a serializable transaction commits?
    Not necessarily. A committed serializable transaction's predicate locks are kept until every overlapping read/write transaction has finished, because a later write could still complete a dangerous structure with it. That is why one long or idle-in-transaction serializable session inflates the lock table, and the failure rate, for everyone.

  • SIReadLock rows in pg_locks mean serializable sessions are blocking each other.
  • Once SSI is tuned, the application can drop its 40001 retry logic.
  • Raising deadlock_timeout reduces serialization failures under SSI.
  • A sequential scan's single relation-level predicate lock is harmless under SSI.
  • A few writers left at READ COMMITTED do not weaken a SERIALIZABLE system.