Sub topic 16
Serializable Snapshot Isolation
This chapter assumes you have read the earlier chapters on snapshots, isolation levels and write conflicts. You should know that Repeatable Read gives a transaction one snapshot for its whole life, and that xmin and xmax decide which row versions that snapshot can see. You also need two psql sessions against the same database.
What Repeatable Read still allows
In PostgreSQL, Repeatable Read is snapshot isolation. It stops dirty reads, non-repeatable reads and phantom reads. It does not guarantee that the result matches some one-at-a-time ordering of the transactions. The classic failure is write skew: two transactions read overlapping data, then each write a different row based on what they read.
CREATE TABLE oncall (doctor text PRIMARY KEY, on_duty boolean NOT NULL);
INSERT INTO oncall VALUES ('alice', true), ('bob', true);The rule is that at least one doctor must stay on duty. Run these steps in order across two sessions:
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM oncall WHERE on_duty; -- 2, so alice may leave
UPDATE oncall SET on_duty = false WHERE doctor = 'alice';
-- Session B
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM oncall WHERE on_duty; -- 2, so bob may leave
UPDATE oncall SET on_duty = false WHERE doctor = 'bob';
COMMIT;
-- Session A
COMMIT; -- succeedsBoth commits succeed, and nobody is on duty. The two updates touch different rows, so the first-updater-wins check from the previous chapter never fires. Each transaction read data that the other one changed, but a snapshot never notices that.
Reset the data with UPDATE oncall SET on_duty = true;, then repeat the experiment with BEGIN ISOLATION LEVEL SERIALIZABLE in both sessions. This time one transaction fails with SQLSTATE 40001:
ERROR: could not serialize access due to read/write dependencies among transactionsThe failure usually appears at COMMIT, but it can appear at any statement.
How SSI works
Serializable in PostgreSQL is Serializable Snapshot Isolation (SSI). It runs on top of the same snapshots as Repeatable Read. It adds bookkeeping that tracks what each transaction read, and it aborts a transaction when the pattern of reads and writes could not have come from any serial order.
SSI does not make transactions wait. Ordinary reads and writes proceed as under Repeatable Read, and PostgreSQL only decides whether to abort a transaction when a conflict pattern appears.
Read/write dependencies
Say transaction T1 reads data, and a concurrent transaction T2 writes a new version of that data that T1's snapshot cannot see. Then T1 must come before T2 in any equivalent serial order, because T1 did not see T2's work. This is a read/write dependency, or rw-antidependency, and it is written T1 → T2.
One such edge is harmless. The write skew above has two edges that point in opposite directions. A reads what B writes, and B reads what A writes. That is a cycle, and no serial order can explain it.
PostgreSQL does not build the whole dependency graph. It looks for a smaller pattern that every cycle in snapshot isolation must contain, called a dangerous structure. This is two rw-antidependency edges in a row, T1 → T2 → T3, where T3 commits first. When PostgreSQL finds one, it aborts one of the transactions.
SIRead locks
To find these edges, PostgreSQL has to remember what each serializable transaction read. It does this with predicate locks, shown in pg_locks with the mode SIReadLock. These locks never block anything. They only record that a transaction read something, so that a later write can be matched against them.
SELECT locktype, relation::regclass AS rel, page, tuple, pid
FROM pg_locks
WHERE mode = 'SIReadLock';Three details of these locks matter in practice:
- They cover reads that found nothing, not only the rows that were returned. An index scan locks the index pages it examined, which protects against phantoms.
- A transaction's SIRead locks can outlive its commit. PostgreSQL keeps them until every transaction that overlapped it has finished, because a later conflict can still involve them.
- A sequential scan locks the whole relation, so any concurrent write to that table creates an rw edge.
False positives and lock granularity
SSI is conservative. It aborts on a pattern that could be a cycle, even when the actual execution would have been fine. So some 40001 errors are false positives. You cannot avoid them completely, but you can reduce them.
PostgreSQL starts with tuple-level locks. When a transaction holds too many, it promotes them to page locks, and then to a relation lock. Coarser locks are cheaper to track but conflict with more writes. These settings control the thresholds:
| Setting | Effect |
|---|---|
| `max_pred_locks_per_transaction` | Sizes the shared pool of predicate locks. Raise it if you see out-of-shared-memory errors with many serializable transactions. |
| `max_pred_locks_per_relation` | How many page or tuple locks on one relation before promotion to a relation lock. |
| `max_pred_locks_per_page` | How many tuple locks on one page before promotion to a page lock. |
The best way to cut false positives is to let queries use indexes. A query that reads one row through a primary key conflicts only with writes to that row's index and heap pages. A query that scans the table conflicts with every writer.
What the application must do
Under SSI, the application must be ready to retry. The rules are:
- Run every transaction that takes part in the invariant at the Serializable level. SSI only tracks serializable transactions, so mixing levels gives no guarantee.
- Treat SQLSTATE
40001as a signal to rerun the whole transaction fromBEGIN, not just the failed statement. The retry gets a new snapshot, so it sees the other transaction's committed result. - Keep the transaction body free of side effects such as sending email, because it may run more than once.
- Cap the number of retries and add a short randomized delay.
This Python example uses psycopg 3:
import random
import time
import psycopg
from psycopg import errors
def go_off_duty(conninfo: str, doctor: str, max_attempts: int = 5) -> None:
for attempt in range(1, max_attempts + 1):
try:
with psycopg.connect(conninfo) as conn:
conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
with conn.transaction():
row = conn.execute(
"SELECT count(*) FROM oncall WHERE on_duty"
).fetchone()
if row[0] < 2:
raise ValueError("at least one doctor must stay on duty")
conn.execute(
"UPDATE oncall SET on_duty = false WHERE doctor = %s",
(doctor,),
)
return
except errors.SerializationFailure:
if attempt == max_attempts:
raise
time.sleep(random.uniform(0.01, 0.05) * attempt)The commit happens when the conn.transaction() block exits, which is inside the try. A failure at commit time is therefore caught and retried like any other.
Read-only transactions
A read-only transaction can only be the T1 side of an rw edge, so SSI can often prove it safe. PostgreSQL adds two features for this:
BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE;
-- long report queries here
COMMIT;With DEFERRABLE, the transaction blocks at its first query until it can get a snapshot that no concurrent writer can make dangerous. After that it takes no SIRead locks and can never fail with 40001. This suits long reports and backups, at the cost of a possible wait at the start.
Costs and limits
- Tracking has overhead in CPU and shared memory, and it grows with the number of concurrent serializable transactions.
- Explicit row locks such as
SELECT ... FOR UPDATEstill work as usual and can remove a conflict at its source, by making the second transaction wait. - Serializable transactions cannot be started on a hot standby.
- Because SSI aborts instead of waiting, a retry-heavy workload shows up as wasted work, not as lock waits. Watch your application's retry counts.
Exercise
Two serializable transactions each run SELECT count(*) FROM oncall WHERE on_duty and then update a different row. Why does PostgreSQL abort one of them, even though no row was updated by both? What should the application do after the error?
Show answer
Each transaction read rows that the other one changed, and its snapshot could not see that change. That gives two read/write dependencies pointing in opposite directions, which is a cycle with no equivalent serial order. SSI detects it through SIRead locks and aborts one transaction with SQLSTATE 40001. The application should roll back and rerun the entire transaction from BEGIN, with a retry limit and a short randomized delay. The retry takes a fresh snapshot and sees the other transaction's result.
Exercise
A report runs for ten minutes at the Serializable level and sometimes fails with 40001 because of concurrent writers. Which transaction mode removes those failures, and what is the trade-off?
Show answer
Use BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE. PostgreSQL waits until it has a snapshot that cannot be part of a dangerous structure, then runs without SIRead locks and cannot be aborted for serialization reasons. The trade-off is that the transaction may block at its first query while it waits for that safe snapshot.