Most developers treat database transactions like magic parentheses. You write BEGIN, run a bunch of queries, write COMMIT, and assume your data is protected from the chaos of concurrent traffic.

Then you deploy to production.

Two users book the last concert seat at the exact same millisecond. Both get confirmation emails. Two doctors on an on-call roster request the same evening off. Both requests succeed, leaving the hospital emergency room with zero staff. Two account holders withdraw funds from a shared balance simultaneously, and the final balance ends up negative.

Nobody got a database error. Every query returned status code 200. The logs show clean COMMIT statements with zero rollbacks.

Here is what went wrong: PostgreSQL default settings do not protect you from concurrent race conditions. Wrapping operations in BEGIN ... COMMIT guarantees atomicity and durability, but isolation is entirely configurable. Even worse, the setting most developers turn to when they want safety, REPEATABLE READ, still allows data corruption bugs through a mechanism known as Write Skew.

To prevent silent data corruption in production, you have to understand what PostgreSQL is actually doing with snapshots, MVCC tuple headers, and predicate locks under the hood.

The ANSI SQL 1992 Illusion

Most computer science courses teach transaction isolation using the ANSI SQL-92 standard. That standard defines four levels based on whether they prevent three specific anomalies:

Isolation Level Dirty Read Non-Repeatable Read Phantom Read
Read Uncommitted Allowed Allowed Allowed
Read Committed Prevented Allowed Allowed
Repeatable Read Prevented Prevented Allowed
Serializable Prevented Prevented Prevented

If you base your mental model on this table, your production architecture will have blind spots.

In 1995, database researchers Hal Berenson, Phil Bernstein, Jim Gray, and others published a paper titled A Critique of ANSI SQL Isolation Levels. They proved that the ANSI standard was fundamentally broken. It was written with lock-based database engines in mind and completely failed to capture how Multi-Version Concurrency Control (MVCC) engines actually work.

In PostgreSQL, the reality looks completely different:

  1. READ UNCOMMITTED does not exist. If you run SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;, Postgres accepts the command without error, but silently runs your transaction in READ COMMITTED. PostgreSQL never allows dirty reads under any circumstance because MVCC engines never read uncommitted tuple versions anyway.
  2. REPEATABLE READ prevents Phantom Reads in PostgreSQL. Under ANSI SQL, Repeatable Read is allowed to suffer from phantoms (new rows appearing in range queries). In Postgres, Repeatable Read operates as Snapshot Isolation. You will never see phantom rows appear mid-transaction.
  3. Preventing all three ANSI anomalies still does not give you Serializability. Snapshot Isolation prevents Dirty Reads, Non-Repeatable Reads, and Phantom Reads, but it still permits Write Skew and Read-Only Transaction Anomalies.

To see why, look at how PostgreSQL constructs and evaluates snapshots in physical memory.

Inside the Snapshot: How Postgres Sees Time

PostgreSQL implements concurrency using Multi-Version Concurrency Control (MVCC). When you update a row, Postgres does not overwrite the existing data on disk. It writes a brand new version of the row (a tuple) into the table page and marks the old version as dead once transactions no longer need it.

Every heap tuple header on disk contains metadata:

  • t_xmin: The transaction ID (txid) of the transaction that inserted this tuple.
  • t_xmax: The transaction ID of the transaction that updated or deleted this tuple (or 0 if still active and untouched).
  • t_infomask: Bit flags storing commit status hints (whether xmin or xmax is committed, aborted, or in-flight).

When a query executes, Postgres does not look at the clock on the wall. It evaluates tuple visibility against an in-memory struct called SnapshotData (defined in src/include/utils/snapshot.h):

typedef struct SnapshotData { SnapshotType snapshot_type; TransactionId xmin; // Lowest txid still running when snapshot was taken TransactionId xmax; // First unassigned txid (future transactions) TransactionId *xip; // Array of active txids between xmin and xmax uint32 xcnt; // Number of active txids in xip array // ... } SnapshotData; 

When Postgres scans a page to decide whether a row is visible to your transaction, it runs a visibility algorithm:

  • If tuple.xmin < snapshot.xmin: The transaction that created the row finished before your snapshot began. Visible (unless deleted).
  • If tuple.xmin >= snapshot.xmax: The transaction that created the row started after your snapshot was taken. Completely invisible.
  • If snapshot.xmin <= tuple.xmin < snapshot.xmax: Postgres searches the xip array. If tuple.xmin is in xip, that transaction was still running when your snapshot was taken, so its changes are invisible. If it is not in xip, it committed before the snapshot, so its changes are visible.

The difference between READ COMMITTED and REPEATABLE READ comes down to a single detail: When does Postgres take that snapshot?

Read Committed: A Moving Target

In PostgreSQL default READ COMMITTED mode, a fresh SnapshotData struct is allocated at the start of every individual SQL statement.

If you have a transaction with three SELECT queries:

BEGIN; SELECT count(*) FROM orders; -- Snapshot 1 taken here -- Concurrent transaction commits 100 new orders here SELECT count(*) FROM orders; -- Snapshot 2 taken here (sees the 100 new orders!) COMMIT; 

Each query sees whatever transactions committed before that specific query began. If another transaction commits halfway through your transaction, your subsequent statements will observe a completely different state of the database.

Repeatable Read: Frozen in Time

In REPEATABLE READ mode, Postgres takes exactly one snapshot at the start of the first non-transaction-control statement (the first SELECT, INSERT, UPDATE, or DELETE) and reuses that identical snapshot for every query until COMMIT.

No matter what happens outside, your transaction looks at a frozen photograph of the database taken at time T0.

The First Production Trap: The Lost Update

Consider a classic balance increment:

-- Session 1 BEGIN; SELECT balance FROM accounts WHERE id = 42; -- returns 100 UPDATE accounts SET balance = 100 + 50 WHERE id = 42; COMMIT; 

If Session 1 and Session 2 both read balance 100 concurrently, Session 1 sets it to 150, and Session 2 sets it to 120. One deposit gets wiped out.

How does Postgres handle this under different isolation levels?

What Happens in Read Committed

In Read Committed, when Session 2 runs its UPDATE, Postgres attempts to acquire an exclusive row-level lock on the tuple for account 42. Because Session 1 already holds that lock, Session 2 pauses and blocks.

When Session 1 commits, Session 2 wakes up. But what does it update?
Postgres triggers an internal mechanism called EvalPlanQual (EPQ). Instead of writing blindly to the old tuple, Postgres re-evaluates the query's WHERE clause against the newly committed version of the row. If the row still matches the WHERE condition, Session 2 proceeds.

However, if your application fetched the balance in application memory (balance = 100) and issued an absolute update (SET balance = 120), you still overwrite Session 1's work! The database lock alone did not protect you because the calculation happened outside the database engine.

If you instead use atomic relative updates (SET balance = balance + 20), EPQ re-fetches the updated row, and the math works.

What Happens in Repeatable Read

In REPEATABLE READ, Postgres refuses to allow silent overwrites.

When Session 2 wakes up after Session 1 commits, Postgres runs an update conflict check:
\"Was the target row updated or deleted by a transaction that committed after this transaction's snapshot was taken?\"

Because Session 1 committed after Session 2's snapshot began, Session 2 aborts immediately with an error:

ERROR: could not serialize access due to concurrent update SQLSTATE: 40001 

Postgres forces your application to abort and retry.

Many developers see this error, breathe a sigh of relief, and conclude: \"Great! Repeatable Read prevents all concurrency bugs. I'll just use Repeatable Read everywhere.\"

That conclusion is dangerous.

The Write Skew Anomaly: Why Repeatable Read Breaks

Write Skew happens when two concurrent transactions read overlapping data, make decisions based on that data, and then write to different rows or tables.

Because each transaction updates a distinct row, their row-level write locks never conflict. Under REPEATABLE READ, both transactions commit without any error, but the combined result violates your global business constraint.

The Hospital On-Call Failure

Consider an on-call rota table:

CREATE TABLE doctors_on_call ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, is_on_call BOOLEAN NOT NULL ); INSERT INTO doctors_on_call (name, is_on_call) VALUES ('Alice', true), ('Bob', true); 

Hospital Rule: At least one doctor must remain on call at all times.

Now, both Alice and Bob want to go off duty. They submit their requests simultaneously:

-- Session 1 (Alice's request) BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM doctors_on_call WHERE is_on_call = true; -- Returns 2. Alice thinks: \"Bob is on call, so I can safely leave.\" UPDATE doctors_on_call SET is_on_call = false WHERE name = 'Alice'; 

At the exact same instant, Bob's application runs:

-- Session 2 (Bob's request) BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM doctors_on_call WHERE is_on_call = true; -- Returns 2. Bob thinks: \"Alice is on call, so I can safely leave.\" UPDATE doctors_on_call SET is_on_call = false WHERE name = 'Bob'; 

Now watch the commit sequence:

-- Session 1 COMMIT; -- Result: SUCCESS! Alice's row is updated. -- Session 2 COMMIT; -- Result: SUCCESS! Bob's row is updated. 

Inspect the table:

SELECT * FROM doctors_on_call; id | name | is_on_call ----+-------+------------ 1 | Alice | f 2 | Bob | f 

Zero doctors are on call. The hospital is uncovered.

Why did this pass?

  1. Alice's transaction only locked row 1 (name = 'Alice').
  2. Bob's transaction only locked row 2 (name = 'Bob').
  3. Neither transaction touched a row that the other modified.
  4. Because there was no write-write collision on the same tuple, Repeatable Read's concurrent update check never fired.

Both transactions executed valid logic against a valid snapshot, but the interleaving of operations produced an invalid state.

How PostgreSQL Solves It: Serializable Snapshot Isolation (SSI)

In older relational engines, guaranteeing true serializability required Two-Phase Locking (2PL). Readers locked out writers, and writers locked out readers. If Alice ran a SELECT, every other transaction was blocked from inserting or updating until Alice committed. Throughput plummeted, and deadlocks became constant.

In PostgreSQL 9.1, engineers Dan Ports and Kevin Grittner implemented Serializable Snapshot Isolation (SSI), based on theoretical work by Michael Cahill, Uwe Röhm, and Alan Fekete.

SSI provides true serializability with the performance profile of Snapshot Isolation.
The core innovation: Readers never block writers, and writers never block readers.

How does SSI pull this off?

SIREAD Locks: Non-Blocking Predicate Tracking

When you run a transaction in SERIALIZABLE mode, Postgres acquires special in-memory locks called SIREAD locks (Predicate Locks) on everything your transaction reads.

Do not let the word \"lock\" mislead you. An SIREAD lock:

  • Does not block any other transaction from reading.
  • Does not block any other transaction from writing.
  • Never sleeps or waits on a lock queue.
  • Can never cause a traditional lock deadlock.

Instead, an SIREAD lock is a sensory tripwire stored in shared memory (PREDICATELOCK). It registers an interest: \"Transaction T1 read this tuple (or this index page).\"

Detecting rw-Antidependencies

SSI monitors the database for conflicts called rw-antidependencies.

An rw-antidependency occurs when transaction T1 reads a version of a row, and a concurrent transaction T2 writes a newer version of that same row.
In the serialization order, this means T1 must be ordered before T2 (because T1 did not see T2's write). We write this as:
T1 --rw--> T2

Postgres detects these dependencies in two directions:

  1. Write after Read: T1 holds an SIREAD lock on a tuple. T2 comes along and updates that tuple. When T2 acquires its write lock, it notices T1's SIREAD lock and flags an rw edge from T1 to T2.
  2. Read after Write: T2 updates a tuple and commits. T1 comes along and reads the table. By checking t_xmin and t_xmax in the tuple header, T1 notices that a newer version was written by concurrent transaction T2. Postgres flags an rw edge from T1 to T2.

The Dangerous Structure: Identifying the Pivot

In graph theory, transactions are serializable if and only if their dependency graph contains no directed cycles.

Testing a massive live dependency graph for cycles on every single query is computationally impossible: finding cycles in a dynamic graph with thousands of nodes would crush the database CPU.

Cahill, Röhm, and Fekete proved a mathematical theorem:
Every serialization cycle in Snapshot Isolation contains a transaction that has both an incoming rw-antidependency edge AND an outgoing rw-antidependency edge.

Such a transaction is called a Pivot:
T_in --rw--> T_pivot --rw--> T_out

Instead of searching the whole database graph for complex cycles, PostgreSQL only looks for this local pattern: two consecutive rw edges forming a pivot.

The moment a transaction becomes a pivot, PostgreSQL knows that a serialization cycle is possible. To preserve data integrity, Postgres aborts one of the transactions before it can commit:

ERROR: could not serialize access due to read/write dependencies among transactions DETAIL: Reason code = Canceled on identification as a pivot, with conflict in = 1042, conflict out = 1043. SQLSTATE: 40001 

Now re-run the hospital on-call scenario under SERIALIZABLE:

  1. Alice's transaction reads the on-call table. Postgres drops an SIREAD lock on the table.
  2. Bob's transaction reads the on-call table. Postgres drops an SIREAD lock for Bob.
  3. Alice updates her row. Postgres detects that Bob read the table Alice just modified (Bob --rw--> Alice).
  4. Bob updates his row. Postgres detects that Alice read the table Bob just modified (Alice --rw--> Bob).
  5. A pivot structure is formed: Alice --rw--> Bob --rw--> Alice.
  6. When Bob attempts to COMMIT, PostgreSQL aborts Bob's transaction with error 40001.
  7. Alice's commit succeeds. Bob's transaction rolls back. Alice is off duty, Bob remains on duty, and the hospital has cover.

The Memory Trap: Lock Escalation and False Positives

Because PostgreSQL checks for dangerous structures rather than full graph cycles, it is conservative. Sometimes it aborts transactions that were technically safe (false positives).

This gets amplified by how Postgres manages SIREAD lock memory.

Shared memory for predicate locks is bounded by two configuration parameters:

  • max_pred_locks_per_transaction (default 64)
  • max_connections (default 100)

If a transaction reads thousands of individual rows, storing a separate SIREAD lock for every single tuple would exhaust shared memory.

To prevent memory crashes, Postgres implements Lock Promotion:

  1. If a transaction acquires too many tuple-level SIREAD locks on the same page, Postgres promotes them into a single Page-level SIREAD lock and frees the tuple locks.
  2. If a transaction acquires too many page-level SIREAD locks in a table, Postgres promotes them into a single Relation-level SIREAD lock.

Here is the operational catch:
If your query performs a Sequential Scan because you forgot to create an index on a foreign key or filter column, Postgres immediately acquires a Relation-level SIREAD lock on the entire table.

Once you have a relation-level lock, any concurrent write to any row in that table by another transaction creates an rw-antidependency! You will start getting random 40001 serialization_failure errors on unrelated user accounts.

To keep Serializable transactions healthy in production:

  • Ensure all filtered queries use indexes so SIREAD locks stay at the tuple or B-tree leaf page level.
  • Keep transactions short. The longer a transaction lives, the more rw-edges it accumulates, and the higher the probability it becomes a pivot.

The Production Blueprint: How to Handle Isolation in Code

Switching to SERIALIZABLE is not a free drop-in replacement. If your application code is not prepared to handle aborts, your users will see raw 500 errors.

In SERIALIZABLE mode, serialization aborts are normal control flow, not system bugs.

Any application running SERIALIZABLE must wrap its transactional database calls in an automatic retry loop with exponential backoff and jitter.

Here is a production-grade Python implementation using psycopg:

import time import random import psycopg from psycopg.errors import SerializationFailure def run_serializable_transaction(conn_pool, max_retries=5, base_delay=0.05): \"\"\" Executes a unit of work under SERIALIZABLE isolation. Automatically retries on SQLSTATE 40001 (SerializationFailure). \"\"\" attempt = 0 while True: try: with conn_pool.connection() as conn: with conn.transaction(): # Set isolation level for this specific transaction with conn.cursor() as cur: cur.execute(\"SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\") # Your business logic here: cur.execute(\"SELECT count(*) FROM doctors_on_call WHERE is_on_call = true;\") count = cur.fetchone()[0] if count <= 1: raise ValueError(\"Cannot go off duty: minimum 1 doctor required.\") cur.execute(\"UPDATE doctors_on_call SET is_on_call = false WHERE name = 'Alice';\") # If transaction block exits without exception, it committed successfully return except SerializationFailure as err: attempt += 1 if attempt >= max_retries: raise RuntimeError(f\"Transaction failed after {max_retries} serialization retries\") from err # Full jitter exponential backoff: sleep between 0 and base_delay * 2^attempt sleep_time = random.uniform(0, base_delay * (2 ** attempt)) time.sleep(sleep_time) 

When to Use Which Isolation Level

You do not need SERIALIZABLE for every table in your database. Here is how senior data engineers select isolation levels in production:

Isolation Level When to Use It Trade-Off
Read Committed 90% of standard web workloads: blogs, profile updates, dashboards, simple CRUD. Fast, no serialization aborts. Vulnerable to non-repeatable reads, phantom reads, and lost updates if logic is computed in application memory.
Read Committed + Explicit Locking (FOR UPDATE) Financial ledger entries, inventory stock decrement, single-row state machines. Use SELECT ... FOR UPDATE to lock specific rows explicitly. Avoids serialization retry loops, but can cause deadlocks if lock acquisition order is inconsistent.
Repeatable Read Long-running analytical reports, batch data exports, audit snapshots. Guarantees consistent snapshot across multiple queries without blocking writers. Cannot prevent Write Skew.
Serializable Complex cross-row integrity invariants (e.g. medical rosters, multi-account ledger constraints, auction bidding rules). Eliminates all race conditions mathematically. Requires application retry loops and tuned indexes to prevent false positive aborts.

Practical Takeaways

  1. BEGIN ... COMMIT does not prevent race conditions. Transactions guarantee that your changes happen all-or-nothing, not that concurrent transactions cannot read stale state.
  2. Postgres has no Read Uncommitted. Requesting it quietly runs Read Committed.
  3. Repeatable Read is Snapshot Isolation. It freezes your view of the database at query start and blocks lost updates on the same row, but it remains blind to Write Skew across multiple rows.
  4. PostgreSQL Serializable uses SSI, not 2PL. Readers never block writers, and writers never block readers. It uses lightweight, non-blocking SIREAD locks in shared memory to detect dangerous pivot structures.
  5. Missing indexes ruin Serializable performance. Sequential scans trigger relation-level SIREAD locks, causing false positive serialization aborts on completely unrelated records.
  6. If you use Serializable, you must write retry loops. Error code 40001 is not an unexpected crash; it is the database engine saving your data from corruption. Catch it, back off, and try again.