Skip to main content

Debugging Write Skew Under Serializable Isolation

How SIREAD predicate locks, rw-antidependency graphs and pivot detection expose and resolve write skew bugs hiding under serializable snapshot isolation.

KBY Technologies13 min read
Debugging Write Skew Under Serializable Isolation

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

A ledger service reports balanced books in every unit test, then silently overdraws an account in production once concurrency exceeds a handful of transactions per second. The transactions never violate a foreign key, never throw a deadlock, and each individually reads consistent data.

The root cause is write skew, and it survives precisely because the team assumed REPEATABLE READ or naive snapshot isolation was equivalent to true serializability. It is not. Serializable snapshot isolation (SSI) closes that gap, though it still produces confusing false-positive aborts and has to be tuned to avoid collapsing throughput.

#The Precise Bottleneck: Snapshot Isolation Is Not Serializability

Under classic snapshot isolation, each transaction reads from a consistent snapshot taken at start time and writes are checked only for direct write-write conflicts. Two transactions that read overlapping data and each write to disjoint rows based on that read will both commit successfully, even though no serial execution of the two transactions would have produced that combined result.

This is the textbook write skew anomaly: two doctors on call, each checking that at least one other doctor is on duty before going off-call themselves, both querying concurrently, both seeing the other as “on duty”, and both going off-call. The invariant is violated despite neither transaction touching a row the other wrote.

Financial systems hit this constantly with balance checks. Consider two withdrawals from two linked accounts whose combined balance must stay non-negative, enforced in application logic rather than a database constraint; each transaction debits a different account:

1-- Transaction A
2BEGIN;
3SELECT SUM(balance) FROM accounts WHERE id IN (42, 43); -- returns 100
4-- application checks 100 - 60 >= 0, proceeds
5UPDATE accounts SET balance = balance - 60 WHERE id = 42;
6COMMIT;
7
8-- Transaction B, concurrent, same snapshot
9BEGIN;
10SELECT SUM(balance) FROM accounts WHERE id IN (42, 43); -- also returns 100
11-- application checks 100 - 70 >= 0, proceeds
12UPDATE accounts SET balance = balance - 70 WHERE id = 43;
13COMMIT;

The function checks the same combined balance as the SQL above, so it guards the two-account invariant rather than one row. InsufficientFunds propagates to the caller, which declines the withdrawal, and the finally block resets the session whichever way the function exits. The exponential backoff is not optional. Under contention, retrying immediately without a jittered delay reproduces the same rw-conflict pattern and produces a retry storm that looks identical to a livelock from the outside.

#
Configuration Tuning

1# postgresql.conf - sizing for high-concurrency SSI workloads
2max_pred_locks_per_transaction = 256   # takes effect only after a server restart
3max_pred_locks_per_relation = -2   # PostgreSQL's documented default; a negative value means max_pred_locks_per_transaction divided by the absolute value of this setting: 256 / 2 = 128 here
4max_pred_locks_per_page = 4   # the documented default is 2
5default_transaction_isolation = 'read committed'  # keep default cheap; opt in explicitly

These values are illustrative. Back up postgresql.conf and record the current settings first, and validate any sizing under a realistic load test.

Leaving default_transaction_isolation at read committed and opting into serializable per transaction avoids paying the SIREAD bookkeeping cost on every connection pool query, including migrations and health checks.

#Failure Modes and Edge Cases

The certifier’s SIREAD lock table is finite: shared memory holds room for max_pred_locks_per_transaction locks per server process or prepared transaction, roughly max_pred_locks_per_transaction × (max_connections + max_prepared_transactions) in total, and if it fills, transactions fail with an out of shared memory error.

promotes tuple locks to a page lock past max_pred_locks_per_page on one page, and to a relation lock past max_pred_locks_per_relation on one relation. This escalation dramatically increases false-positive aborts because a relation-level SIREAD lock conflicts with almost any concurrent write to that table, regardless of actual row overlap.

Under sustained high-concurrency load with insufficient lock table sizing, you will observe serialization failure rates climbing non-linearly even though the underlying data contention hasn’t changed — the symptom is a saw-tooth throughput graph as the system periodically restarts transactions.

serializable snapshot isolation

Long-running serializable transactions are the other major failure mode.

PostgreSQL keeps a committed transaction’s SIREAD locks until every transaction that overlapped it has completed, so a single analytical query left open under SERIALIZABLE for minutes delays the clean-up of predicate locks held by transactions that committed while it ran (a read-only transaction can release its own SIREAD locks early once PostgreSQL establishes that no conflict can still arise), filling the fixed-size shared lock table, which drives more lock promotion and more false-positive aborts.

Idle-in-transaction timeouts become mandatory operational hygiene, not an optional safeguard, once serializable snapshot isolation is in play.

A subtler edge case: read-only transactions still participate in the dependency graph and can still be the one aborted, unless started as SERIALIZABLE READ ONLY DEFERRABLE (DEFERRABLE has no effect unless the transaction is both SERIALIZABLE and READ ONLY). Such a transaction may wait while taking its snapshot until a safe one is available, and then runs with no risk of being cancelled by a serialization failure.

#Isolation Level Comparison

Isolation LevelWrite Skew ProtectionLocking MechanismTypical OverheadBest Fit
Read CommittedNoneRow-level, per-statement snapshotLowestHigh-throughput CRUD, no cross-row invariants
Repeatable Read (SI)None — vulnerableTransaction-level snapshot, write-write check onlyLowReporting, analytics, single-row invariants
Serializable (SSI)Full, via rw-antidependency detectionSIREAD predicate locks + certifier graphModerate, contention-dependentLedgers, inventory, uniqueness across queries
Application-level locking (SELECT FOR UPDATE)Partial, requires manual coveragePessimistic row locksHigh under contentionNarrow hot-row cases where retries are unacceptable

#Scaling and Security Trade-offs

Adopting serializable snapshot isolation is an explicit trade of raw throughput for correctness guarantees, and the trade-off surface widens as you scale horizontally. When designing the surrounding architectural patterns for a service layer sitting on top of a serializable database, weigh the following:

  • Connection pool sizing — SIREAD bookkeeping grows with concurrent serializable transactions; SIREAD locks belong to transactions, not sessions, so transaction length matters more than the PgBouncer pooling mode; whichever mode you use, keep serializable transactions short and never leave them idle in transaction.
  • Retry amplification as a DoS surface — an attacker who can trigger high-contention write paths (e.g. a public “claim voucher” endpoint) can deliberately induce serialization failures across unrelated transactions sharing the same hot predicate, effectively a low-cost denial-of-service against write availability.
  • Read replica divergence — SSI guarantees apply only within a single serializable cluster; if reads are served from asynchronous replicas for the invariant check while writes commit on the primary, the anomaly reappears because the replica’s snapshot is stale relative to the certifier’s view.
  • Cross-service transactions — serializable snapshot isolation solves single-database write skew; it does nothing for invariants spanning two microservices’ separate databases, which still require sagas or two-phase commit with their own distinct failure modes.
  • Observability cost — tracking pg_stat_database.xact_rollback against serialization failure counters specifically (rather than generic rollback counts) is necessary to distinguish application bugs from expected SSI aborts during capacity planning.

None of this argues against using serializable snapshot isolation for genuinely invariant-sensitive write paths — it argues for scoping it precisely. Apply it to the transactions that actually enforce cross-row invariants, leave everything else on cheaper isolation levels, and instrument serialization failures as a first-class metric rather than folding them into generic error rates. Treated that way, SSI becomes a targeted correctness tool rather than a blanket performance tax across the whole write path.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01official transaction isolation documentationpostgresql.org

About this page

Credited to

Dates

Published

Last updated

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details

Found this useful? Follow KBY for more like it.

Reader Interaction

Comments

Add a thoughtful note on Debugging Write Skew Under Serializable Isolation. Comments are checked for spam and held for moderation before appearing.

Loading comments...

More from KBY that goes with this article.

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.