ML
PostgreSQL

Postgres SSI and Predicate Locks: Why Serializable Transactions Abort on Phantom Reads

Serializable Snapshot Isolation (SSI) detects write skews without physical page locking by tracking SIREAD predicate locks in shared memory. How predicate lock exhaustion falls back to relation locks and triggers 40001 serialization failures.

November 24, 202612 min readPostgresDatabaseConcurrencyArchitecture

In PostgreSQL, achieving true mathematical serializability historically required coarse table locks or invasive SELECT ... FOR UPDATE clauses that serialized throughput down to a crawl. Starting in PostgreSQL 9.1, the engine introduced Serializable Snapshot Isolation (SSI), based on the research of Cahill, Rohm, and Fekete. SSI allows transactions to execute with the full performance of normal MVCC snapshot isolation, intervening only when it mathematically detects a cycle in the dependency graph.

However, running transactions under ISOLATION LEVEL SERIALIZABLE often surprises teams with unexpected spikes in serialization failures (SQLSTATE 40001). Transactions that read seemingly disjoint rows suddenly abort. Understanding how Postgres implements SSI via in-memory SIREAD predicate locks reveals why these false-positive aborts occur and how to architect systems to avoid them.

1. How SSI Works: Tracking rw-Antidependencies

Unlike two-phase locking (2PL) systems that physically block concurrent readers and writers, Postgres SSI never blocks. Instead, it tracks data flow dependencies between concurrent transactions. The dangerous pattern that can create write skew is known as an rw-antidependency (a rw-conflict):

  • Transaction T1 reads a version of tuple V.
  • Transaction T2 subsequently writes a newer version of tuple V (or inserts a new tuple matching T1's read condition).
  • From T1's perspective, T2 appears to have committed after T1. An edge T1 -> T2 is formed in the serialization graph.

A serialization anomaly can only occur if there is a cycle of such dependencies containing two consecutive rw-antidependency edges. When the Postgres lock manager detects such a cycle (or a dangerous structure that could become one), it terminates the cycle by aborting one of the participating transactions with a could not serialize access due to read/write dependencies among transactions error.

2. The Role of SIREAD Predicate Locks

To detect rw-conflicts on rows that do not yet exist (phantom reads), Postgres acquires virtual locks called SIREAD locks. It is essential to recognize what these locks are and what they are not:

  • They do not block: An SIREAD lock held by T1 never prevents T2 from modifying or inserting rows.
  • They are memory-only flags: SIREAD locks reside in a fixed-size shared memory hash table. They simply record: "Transaction T1 inspected this tuple, page, or index range."
  • Index and sequential scan coverage: If T1 executes SELECT * FROM accounts WHERE balance > 1000, Postgres places SIREAD locks on the matching tuples in the table and on the corresponding index leaf pages. If a sequential scan is performed, SIREAD locks are placed on every page scanned in the relation!

3. Predicate Lock Promotion and False-Positive Aborts

Because the shared memory pool for predicate locks is finite (governed by max_pred_locks_per_transaction, max_pred_locks_per_relation, and max_pred_locks_per_page), Postgres aggressively promotes fine-grained locks to coarse locks when memory pressure rises:

[ Individual Tuple SIREAD Locks ]
               |
   (Exceeds max_pred_locks_per_page)
               v
    [ Page-Level SIREAD Lock ]
               |
  (Exceeds max_pred_locks_per_relation)
               v
  [ Whole Relation SIREAD Lock ]

Once a predicate lock is promoted to a page-level or relation-level lock, the engine can no longer distinguish between specific tuples. Any concurrent write to any row on that page or relation is treated as a conflict with the reader! This coarse granularity produces massive false-positive conflict cycles, causing completely unrelated transactions to fail with serialization aborts.

4. Production Patterns for Taming SSI Aborts

To operate high-volume workloads under serializable isolation successfully, apply these core architectural practices:

A. Implement Automated Exponential Backoff and Retry

Under SSI, transaction rollbacks due to 40001 errors are not operational crashes; they are an expected concurrency control mechanism. Any application executing serializable transactions must wrap execution in an idempotent retry handler:

async function executeSerializableTransaction(pool, workFn, maxRetries = 5) {
  let attempt = 0;
  while (true) {
    const client = await pool.connect();
    try {
      await client.query("BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE");
      const result = await workFn(client);
      await client.query("COMMIT");
      return result;
    } catch (err) {
      await client.query("ROLLBACK").catch(() => {});
      if (err.code === "40001" && attempt < maxRetries) {
        attempt++;
        const jitter = Math.random() * 50;
        const delay = Math.min(1000, Math.pow(2, attempt) * 20 + jitter);
        await new Promise((res) => setTimeout(res, delay));
        continue;
      }
      throw err;
    } finally {
      client.release();
    }
  }
}

B. Declare Read-Only Transactions as DEFERRABLE

Reporting queries and read-only audits should always be declared as SET TRANSACTION READ ONLY DEFERRABLE. A deferrable read-only transaction will wait until all concurrent read-write transactions that started before it have completed. Once it starts, it is mathematically guaranteed never to suffer serialization failures and never to cause other transactions to abort, completely freeing the predicate lock table from tracking its reads.

C. Maintain Supporting Indexes on All Filtered Columns

When a query lacks an index, Postgres falls back to a sequential scan, acquiring SIREAD locks on every single page of the table and rapidly forcing lock promotion to the whole relation. Providing tight B-tree indexes ensures SIREAD locks stay confined to exact index keys and leaf pages.

Summary

Postgres Serializable Snapshot Isolation offers rigorous consistency without the bottleneck of physical reader locks. By monitoring predicate lock usage, ensuring comprehensive index coverage to prevent relation promotions, and wrapping database calls in idempotent retry handlers, teams can leverage full ACID serializability at production scale.

SharePostLinkedIn

Reader Discussion

1 replies// weighed in

TopNewestAuthor
Add to the thread
Disagree, agree harder, or share your own experience…
Email instead →markdown okbe kind
  1. Rachel Gold· Staff SREAgrees

    the on-call framing throughout this piece is what makes it land. too many infra articles assume you never get paged. those are written by people who never got paged.

    Nov 27, 2026·3 days later

Worked on something similar? Email ducminhldm@gmail.com — I read every one. The good ones become future posts.

Comments seeded · live discussion via email