Database Isolation Levels: The Definitive Architectural Guide to Concurrency Anomalies, MVCC & SSI
This article is available in English. Browse translated guides in the language menu.
In distributed systems and relational database engineering, transaction isolation is where computer science theory collides violently with physical hardware realities. Every backend engineer has memorized the textbook definition of ACID, yet isolation remains the single most misunderstood letter in the acronym.
When systems scale to thousands of concurrent transactions per second, standard assumptions shatter. Balances drop below zero despite explicit CHECK constraints. Background job runners process the exact same payload twice. Inventory counts drift into negative values during flash sales. Autovacuum processes grind to a halt, triggering transaction ID wraparound emergencies because an analytics pipeline left a single read-only transaction open across lunch.
To eliminate data corruption and prevent catastrophic latency spikes, software architects cannot rely on high-level abstractions. You need to understand:
- Why the ANSI SQL-92 standard is fundamentally flawed and fails to describe modern storage engines.
- The complete taxonomy of concurrency anomalies—from classical Dirty Reads to nuanced phenomena like Read Skew, Write Skew, and Lost Updates.
- The internal mechanics of Multi-Version Concurrency Control (MVCC): tuple visibility headers (
xmin/xmax), Undo logs, and snapshot construction. - How Serializable Snapshot Isolation (SSI) eliminates lock-based serialization bottlenecks through lock-free dependency graph tracking.
- The divergence in implementation between PostgreSQL, MySQL InnoDB, and globally distributed databases like Google Cloud Spanner and CockroachDB.
- Production-grade transaction retry architectures, explicit locking strategies (
FOR UPDATE,SKIP LOCKED), and observability protocols.
This guide provides an end-to-end architectural breakdown of database isolation levels from low-level storage engines to production implementation.
1. The High-Stakes Concurrency Dilemma: Correctness vs Throughput
A database transaction is an abstraction designed to simplify application development. It groups multiple read and write operations into an atomic, consistent unit. In a single-threaded universe, transactions execute serially one after another with zero concurrency anomalies.
In production, multi-core servers and distributed nodes must process thousands of transactions concurrently to achieve acceptable throughput and low latency.
+-----------------------------------------------------------------------------+
| The Database Isolation Trade-Off Spectrum |
+-----------------------------------------------------------------------------+
STRICT SERIALIZABILITY READ UNCOMMITTED
(External Consistency) (Maximum Chaos)
<--------------------------------------------------------------------------->
Total Order Across Clock Time Complete Statement Interleaving
Highest Correctness Maximum Throughput
Lowest Contention Tolerance Zero Data Integrity
Significant Latency/Abort Overhead Dirty Reads, Lost Updates rampant
PRACTICAL PRODUCTION SWEET SPOTS
|
+-----------------------+-----------------------+
| |
v v
READ COMMITTED REPEATABLE READ /
(Default in Postgres, SNAPSHOT ISOLATION
Oracle, SQL Server) (Default in MySQL InnoDB)
The fundamental tension of isolation is: how much state interleaving will your application tolerate in exchange for raw query throughput?
Setting the isolation level too low exposes your data to silent corruption that no application-level test suite will catch during local single-user testing. Setting it too high without understanding engine mechanics causes lock-manager exhaustion, serialization abort storms, connection pool starvation, and cascading system outages.
2. Deconstructing ANSI SQL-92 and The 1995 Critique
In 1992, the American National Standards Institute (ANSI) published the ANSI X3.135-1992 standard (SQL-92), which defined four isolation levels based on three operational phenomena:
| Isolation Level | Dirty Read ($P_1$) | Non-Repeatable Read ($P_2$) | Phantom Read ($P_3$) |
|---|---|---|---|
| Read Uncommitted | Allowed | Allowed | Allowed |
| Read Committed | Prevented | Allowed | Allowed |
| Repeatable Read | Prevented | Prevented | Allowed |
| Serializable | Prevented | Prevented | Prevented |
Why the ANSI Standard Is Severely Flawed
In 1995, a landmark research paper titled “A Critique of ANSI SQL Isolation Levels” (Berenson, Bernstein, Gray, Melton, O’Neil, and O’Neil) exposed critical defects in the ANSI standard that still confuse software engineers today:
- Lock-Based Bias: ANSI SQL-92 implicitly assumed all relational engines used pessimistic Two-Phase Locking (2PL). It failed to anticipate Multi-Version Concurrency Control (MVCC), which was already emerging in engines like Oracle and Postgres.
- Ambiguous Phenomenon Definitions: ANSI defined phenomena using narrow English phrases rather than strict mathematical schedules. This led to implementations satisfying the letter of the standard while still permitting catastrophic data anomalies.
- Missing Critical Anomalies: The ANSI standard completely omitted:
- Dirty Write ($P_0$): A concurrent write that overwrites uncommitted data.
- Lost Update ($P_4$): A concurrent read-modify-write cycle that silently overwrites another committed update.
- Read Skew ($A5A$): Reading inconsistent, mutually dependent data across multiple queries.
- Write Skew ($A5B$): Two concurrent transactions satisfying independent preconditions that together violate a global invariant.
- Snapshot Isolation (SI) Was Uncategorized: Engines implementing Snapshot Isolation prevent Phantom Reads ($P_3$) while permitting Write Skew ($A5B$). Under ANSI’s three-phenomenon rubric, Snapshot Isolation is strictly stronger than Repeatable Read yet weaker than Serializable—an impossible classification in ANSI SQL-92.
3. The Complete Taxonomy of Concurrency Anomalies
To design resilient architectures, you must recognize the exact data corruption patterns that occur when transactions interleave.
+-----------------------------------------------------------------------------+
| Taxonomy of Concurrency Anomalies |
+-----------------------------------------------------------------------------+
| |
| [Dirty Write (P0)] --> Transaction overwrites uncommitted data |
| [Dirty Read (P1/A1)] --> Transaction reads uncommitted changes |
| [Non-Repeatable Read (P2)] --> Re-reading row returns modified values |
| [Phantom Read (P3)] --> Re-querying range returns new/missing rows |
| [Lost Update (P4)] --> Concurrent read-modify-write clobbers data |
| [Read Skew (A5A)] --> Multi-row read sees inconsistent states |
| [Write Skew (A5B)] --> Concurrent writes break multi-row constraint|
| |
+-----------------------------------------------------------------------------+
Phenomenon $P_0$: Dirty Write
A transaction overwrites a data item that has been modified by another active transaction that has not yet committed or rolled back.
-- Initial State: account_id = 10, balance = 100
Transaction 1 Transaction 2
------------- -------------
BEGIN;
UPDATE accounts
SET balance = 500
WHERE id = 10;
BEGIN;
UPDATE accounts
SET balance = 900
WHERE id = 10;
ROLLBACK;
COMMIT;
The Impact: If Transaction 1 rolls back, what should the balance be? If the engine rolls back to the pre-Transaction 1 state (100), Transaction 2’s committed write (900) is erased. If it leaves it at 900, Transaction 1’s rollback failed. No production relational engine permits Dirty Writes. Every modern database enforces exclusive write locks until transaction completion to guarantee recoverable storage.
Phenomenon $P_1$ / $A_1$: Dirty Read
Transaction 1 modifies a row. Transaction 2 reads that row before Transaction 1 commits. Transaction 1 subsequently aborts and rolls back.
Timeline:
T1: BEGIN;
T1: UPDATE users SET email = '[email protected]' WHERE id = 42;
T2: BEGIN;
T2: SELECT email FROM users WHERE id = 42; -- Reads '[email protected]'
T2: SendPasswordResetLink(to: '[email protected]');
T1: ROLLBACK; -- Reverts email back to '[email protected]'
T2: COMMIT;
The Impact: Transaction 2 acted upon phantom data that logically never existed in persistent storage.
Phenomenon $P_2$ / $A_2$: Non-Repeatable Read (Fuzzy Read)
Transaction 1 reads a row. Transaction 2 updates or deletes that row and commits. Transaction 1 re-reads the row and observes the mutated state or discovers the row has vanished.
-- Client 1 (Financial Audit Report)
BEGIN;
SELECT balance FROM accounts WHERE id = 101; -- Reads $5,000
-- Client 2 (ATM Withdrawal)
BEGIN;
UPDATE accounts SET balance = balance - 2000 WHERE id = 101;
COMMIT;
-- Client 1 (Re-evaluating summary invariant)
SELECT balance FROM accounts WHERE id = 101; -- Reads $3,000!
COMMIT;
The Impact: Within the same atomic transaction, an entity mutated without Client 1 performing any update. This breaks report generation, validation loops, and multi-step computational pipelines.
Phenomenon $P_3$ / $A_3$: Phantom Read
Transaction 1 executes a query that reads a set of data items satisfying a search condition (WHERE predicate). Transaction 2 creates new items or mutates existing items that satisfy Transaction 1’s search predicate and commits. Transaction 1 repeats the query and receives a different set of rows.
-- Client 1: Count active worker nodes in region 'us-east-1'
BEGIN;
SELECT count(*) FROM worker_nodes
WHERE region = 'us-east-1' AND status = 'ACTIVE';
-- Output: 4 nodes
-- Client 2: Autoscaler provisions node
BEGIN;
INSERT INTO worker_nodes (id, region, status)
VALUES (99, 'us-east-1', 'ACTIVE');
COMMIT;
-- Client 1: Allocates jobs assuming exactly 4 nodes exist
SELECT id FROM worker_nodes
WHERE region = 'us-east-1' AND status = 'ACTIVE';
-- Output: 5 rows (Node 99 appeared from nowhere!)
COMMIT;
The Distinction Between $P_2$ and $P_3$:
- Non-Repeatable Read ($P_2$) involves modifying an existing row that was already read.
- Phantom Read ($P_3$) involves modifying the cardinality of the search predicate via
INSERT,DELETE, or updating a row into/out of the predicate filter.
Phenomenon $P_4$: Lost Update
Two transactions read the same initial state, compute a new value based on that state, and write back their updates concurrently. The second transaction overwrites the first transaction’s update without incorporating it.
Initial Value: balance = $1,000
Transaction 1 (Debit $100) Transaction 2 (Credit $200)
-------------------------- ---------------------------
BEGIN; BEGIN;
SELECT balance FROM accounts;
-- Reads $1,000
SELECT balance FROM accounts;
-- Reads $1,000
UPDATE accounts
SET balance = 1000 - 100;
-- balance is now $900
COMMIT;
UPDATE accounts
SET balance = 1000 + 200;
-- balance is now $1,200!
COMMIT;
The Impact: Transaction 1’s debit of $100 is completely erased. The balance is $1,200 instead of the correct $1,100. This occurs whenever developers execute application-level SELECT followed by UPDATE without explicit atomic increments (SET balance = balance + delta) or row locking.
Phenomenon $A5A$: Read Skew
Transaction 1 reads row $X$. Transaction 2 modifies row $X$ and row $Y$ to maintain a global constraint (e.g., $X + Y = 1000$) and commits. Transaction 1 reads row $Y$ and observes a state that violates the constraint.
-- Constraint: Checking (X) + Savings (Y) = Total Balance ($1,000)
-- Initial: X = 500, Y = 500
Transaction 1 (Balance Audit) Transaction 2 (Transfer $400 from X to Y)
----------------------------- -----------------------------------------
BEGIN;
SELECT balance FROM accounts
WHERE type = 'CHECKING';
-- Reads: $500
BEGIN;
UPDATE accounts SET balance = 100 WHERE type = 'CHECKING';
UPDATE accounts SET balance = 900 WHERE type = 'SAVINGS';
COMMIT;
SELECT balance FROM accounts
WHERE type = 'SAVINGS';
-- Reads: $900!
COMMIT;
The Impact: Transaction 1 observed total funds of $1,400 ($500 Checking + $900 Savings). Inconsistent snapshots during financial reconciliation, tax calculations, or batch ETL jobs cause severe auditing failures.
Phenomenon $A5B$: Write Skew
Two concurrent transactions read overlapping data sets that satisfy a business constraint, verify the constraint holds, make disjoint updates that independently preserve the constraint, but when combined, violate the global invariant.
The Canonical Hospital Doctor Problem
Invariant: At least one doctor must be on-call at all times.
Initial State: Both Alice and Bob are on-call (count(*) = 2).
Transaction 1 (Alice requests off) Transaction 2 (Bob requests off)
---------------------------------- --------------------------------
BEGIN; BEGIN;
SELECT count(*) FROM doctors SELECT count(*) FROM doctors
WHERE on_call = true; WHERE on_call = true;
-- Returns 2 (Safe to take off!) -- Returns 2 (Safe to take off!)
UPDATE doctors UPDATE doctors
SET on_call = false SET on_call = false
WHERE name = 'Alice'; WHERE name = 'Bob';
COMMIT; COMMIT;
The Outcome: Both transactions commit successfully under standard Snapshot Isolation! Why? Because Alice modified her row, and Bob modified his row. Neither transaction updated a row that the other was updating—there was no row-level write conflict.
Yet the resulting database state has zero doctors on-call, completely violating the core business invariant.
+-----------------------------------------------------------------------------+
| The Write Skew Anatomy in Snapshot Isolation |
+-----------------------------------------------------------------------------+
Snapshot State: [Alice: on_call=true] [Bob: on_call=true]
|
+----------------+----------------+
| |
v v
Transaction 1 Transaction 2
Reads: Alice, Bob (Count = 2) Reads: Alice, Bob (Count = 2)
Writes: Alice = false Writes: Bob = false
| |
v v
Rows Written: {Alice} Rows Written: {Bob}
Conflict Check: {Alice} ∩ {Bob} = ∅ --> NO CONFLICT DETECTED!
| |
+----------------+----------------+
|
v
Resulting State: 0 Doctors On Call
INVARIANT VIOLATED!
4. The Four Standard Isolation Levels Under the Microscope
Relational database engines handle concurrency by combining two core architectures: Pessimistic Locking (holding read and write locks) and Multi-Version Concurrency Control (MVCC) (creating timestamped immutable versions of tuples).
+--------------------+---------------------------------------------------------+
| Isolation Level | Snapshot Lifecycle & Engine Behavior |
+--------------------+---------------------------------------------------------+
| Read Uncommitted | Reads dirty in-memory buffers; no snapshot guarantee |
| Read Committed | Fresh snapshot instantiated per SQL statement |
| Repeatable Read | Single static snapshot frozen at transaction start |
| Serializable | Snapshot Isolation + Read/Write Dependency Tracking |
+--------------------+---------------------------------------------------------+
1. Read Uncommitted: The Wild West
- ANSI Contract: Prevents Dirty Writes ($P_0$); permits Dirty Reads ($P_1$), Non-Repeatable Reads ($P_2$), and Phantoms ($P_3$).
- Engine Reality:
- PostgreSQL: Does not implement dirty reads. Executing
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTEDsilently promotes the connection to Read Committed. PostgreSQL’s tuple visibility engine always checks the commit status log (pg_xact); uncommitted rows cannot be read. - MySQL InnoDB: Implements true Read Uncommitted by performing un-versioned reads against memory buffers without validating transaction IDs.
- Production Verdict: Almost never acceptable in financial, operational, or SaaS applications. Occasionally used in non-critical reporting on secondary replicas where dirty telemetry can be tolerated.
- PostgreSQL: Does not implement dirty reads. Executing
2. Read Committed: The Pragmatic Default
- ANSI Contract: Prevents $P_0$ and $P_1$; permits $P_2$, $P_3$, Lost Updates ($P_4$), Read Skew ($A5A$), and Write Skew ($A5B$).
- How It Works: The database engine creates a new MVCC snapshot at the start of every single SQL statement.
- Statement Interleaving:
If statement 1 executes at
T1, it sees all data committed up toT1. If a concurrent transaction commits changes atT2, and statement 2 executes atT3, statement 2 sees the new data. - Vulnerabilities:
- Unsafe for multi-statement balance transfers.
- Vulnerable to phantom rows appearing during multi-step batch updates.
- Why It’s the Industry Default: It delivers the highest concurrency with minimal locking. In PostgreSQL, read queries never block write queries, and write queries never block read queries.
3. Repeatable Read: Transaction-Level Snapshot Isolation
- ANSI Contract: Prevents $P_0$, $P_1$, and $P_2$; ANSI claims it permits Phantoms ($P_3$).
- Engine Reality:
- PostgreSQL: Implements Repeatable Read via Snapshot Isolation (SI). A single snapshot is taken when the first query in the transaction begins. This snapshot is preserved until
COMMIT. Because the snapshot is frozen, PostgreSQL Repeatable Read prevents Phantom Reads ($P_3$) entirely! - First-Committer-Wins (PostgreSQL Conflict Rule): If Transaction 1 attempts to
UPDATEorDELETEa row that was updated and committed by Transaction 2 after Transaction 1’s snapshot was taken, Transaction 1 immediately aborts with:ERROR: could not serialize access due to concurrent update SQLSTATE: 40001 - MySQL InnoDB: Also takes a single snapshot at transaction start for standard reads. However, for locking reads (
SELECT ... FOR UPDATE), InnoDB uses Next-Key Locks (record locks + gap locks) on the index to physically prevent other transactions from inserting into the scanned range.
- PostgreSQL: Implements Repeatable Read via Snapshot Isolation (SI). A single snapshot is taken when the first query in the transaction begins. This snapshot is preserved until
- The Residual Threat: Repeatable Read / Snapshot Isolation does NOT prevent Write Skew ($A5B$).
4. Serializable: True Sequential Equivalence
- ANSI Contract: Prevents all concurrency phenomena. Guarantees that any concurrent execution of transactions produces the exact same state as if they were run one at a time sequentially.
- The Historic Approach: Strict Two-Phase Locking (SS2PL):
- Transactions obtain shared locks ($S$) on every row or range they read, and exclusive locks ($X$) on every row they modify.
- Locks are held until the very end of the transaction.
- The Performance Problem: Complete concurrency collapse. Reads block writes; writes block reads; deadlock rates skyrocket under high traffic.
- The Modern Approach: Serializable Snapshot Isolation (SSI):
- Pioneer research by Cahill, Röhm, and Fekete (2008) introduced SSI, which was implemented in PostgreSQL 9.1.
- Transactions run concurrently under optimistic Snapshot Isolation without holding blocking read locks.
- The engine tracks read-write dependencies dynamically in memory using non-blocking
SIREADlocks. - If the engine detects a dangerous dependency cycle in the serialization graph, it aborts one transaction (the “pivot”) with SQLSTATE
40001.
+-----------------------------------------------------------------------------+
| Serializable Snapshot Isolation (SSI) Dependency Tracking |
+-----------------------------------------------------------------------------+
Transaction 1 Transaction 2
------------- -------------
Reads Range A (Doctors) Reads Range A (Doctors)
[Sets SIREAD lock on A] [Sets SIREAD lock on A]
| |
| v
| Writes to Row B (Alice)
| Conflict: T1 -rw-> T2
v |
Writes to Row C (Bob) |
Conflict: T2 -rw-> T1 |
| |
+-------------------+---------------------+
|
v
Dependency Graph: T1 <==rw==> T2
CYCLE DETECTED (Dangerous Structure)
|
v
PostgreSQL SSI Engine Intervenes:
ERROR: could not serialize access (40001)
One transaction aborted -> Invariant Preserved!
5. Under the Hood: Concurrency Control in Modern Storage Engines
To truly master isolation, you must understand the physical data structures inside the database kernel.
PostgreSQL: Heap Tuples, Commit Status, and SIREAD Locks
PostgreSQL implements MVCC by appending new versions of rows directly to the table’s 8KB heap pages.
+-----------------------------------------------------------------------------+
| PostgreSQL Heap Tuple Header |
+-----------------------------------------------------------------------------+
| t_xmin (32-bit XID) | Transaction ID that created/inserted this row |
| t_xmax (32-bit XID) | Transaction ID that deleted/updated this row (0) |
| t_cid (32-bit CID) | Command identifier within the transaction |
| t_ctid (ItemPointer) | Disk pointer (page, offset) to newer tuple version |
| t_infomask | Bit flags (XMIN_COMMITTED, XMAX_INVALID, etc.) |
+-----------------------------------------------------------------------------+
| Row Data Payload |
+-----------------------------------------------------------------------------+
-
Snapshot Representation: A PostgreSQL snapshot is represented as
xmin:xmax:xip_list:xmin: Earliest transaction ID that was still active when the snapshot was taken. All transactions withXID < xminare committed and visible.xmax: First unassigned transaction ID. All transactions withXID >= xmaxbegan after the snapshot and are invisible.xip_list: The list of active transaction IDs betweenxminandxmaxat snapshot creation time.
-
Read Committed vs Repeatable Read:
- In Read Committed, PostgreSQL calls
GetTransactionSnapshot()for every statement. - In Repeatable Read, PostgreSQL calls
GetTransactionSnapshot()once during the first query and caches the pointer in the transaction state struct.
- In Read Committed, PostgreSQL calls
-
The Hidden Cost: Table Bloat & Autovacuum: When an
UPDATEoccurs, PostgreSQL does not modify the row in-place; it writes a brand new row version witht_xmin = current_xidand updates the old row’st_xmax = current_xid.If an application holds open a long-running transaction under
REPEATABLE READ, the database cannot vacuum any dead tuples modified after that transaction’s snapshotxmin. This leads to table bloat, disk exhaustion, and degraded cache efficiency.
MySQL InnoDB: Clustered Indexes, Undo Logs, and Next-Key Locks
Unlike PostgreSQL, MySQL InnoDB updates rows in-place inside the clustered index (B+ Tree) and writes previous versions to an Undo Log segment.
+-----------------------------------------------------------------------------+
| MySQL InnoDB Undo Log Architecture |
+-----------------------------------------------------------------------------+
Clustered Index Page
+---------------------------------------------------------------------------+
| Primary Key: 101 | DATA: "Active" | DB_TRX_ID: 504 | DB_ROLL_PTR: 0x8F40 |
+---------------------------------------------------------------------------+
|
v Points to Undo Log
+---------------------------------------------------------------------------+
| Undo Record (Trx 490): DATA: "Pending" | DB_ROLL_PTR: 0x8A10 |
+---------------------------------------------------------------------------+
|
v
+---------------------------------------------------------------------------+
| Undo Record (Trx 412): DATA: "Draft" | DB_ROLL_PTR: NULL |
+---------------------------------------------------------------------------+
- Reconstructing History: When an InnoDB query needs an older version of a row, it traverses the rollback pointer (
DB_ROLL_PTR) chain in the Undo Log until it finds a record created by a committed transaction prior to its Read View. - Next-Key Locking:
In InnoDB’s
REPEATABLE READ, locking queries (SELECT ... FOR UPDATE,UPDATE,DELETE) don’t just lock matching index records; they also acquire gap locks on the index gaps between keys.- If keys 10 and 20 exist, scanning
WHERE id BETWEEN 10 AND 20 FOR UPDATEplaces a gap lock on the interval(10, 20). - Any concurrent transaction attempting
INSERT INTO accounts (id) VALUES (15)will be blocked at the lock manager until the first transaction commits. This prevents Phantom Reads physically.
- If keys 10 and 20 exist, scanning
Distributed Databases: Google Cloud Spanner & CockroachDB
In distributed databases spanning multiple data centers, there is no single physical CPU or memory bus to coordinate snapshots.
+-----------------------------------------------------------------------------+
| Distributed Isolation Architectures |
+-----------------------------------------------------------------------------+
Google Cloud Spanner CockroachDB
-------------------- -----------
- External Consistency - Strict Serializability
- TrueTime API (GPS + Atomic Clocks) - Hybrid Logical Clocks (HLC)
- Explicit Bounded Clock Uncertainty (ε) - Raft Consensus per Range
- Commit Wait: Wait out 2ε uncertainty - Read Re-starts & Write Pushes
- Strict Serializability (External Consistency): If Transaction $T_2$ begins after Transaction $T_1$ commits anywhere in the world, $T_2$ must see the effects of $T_1$.
- Google Cloud Spanner TrueTime:
Spanner utilizes atomic clocks and GPS receivers deployed in every datacenter to assign monotonically increasing timestamps with a guaranteed maximum uncertainty bound ($\epsilon \approx 1\text{ms} - 7\text{ms}$).
- To guarantee external consistency, Spanner enforces Commit Wait: when committing at timestamp $t$, the coordinator delays releasing locks until $t + \epsilon$ has passed in real physical time.
- CockroachDB Hybrid Logical Clocks (HLC): CockroachDB combines physical wall-clock time with logical Lamport counters to provide serializable execution across generic cloud infrastructure without proprietary GPS hardware.
6. The Engine Realities Matrix
Different relational databases make vastly different design choices under the standard SQL isolation names.
| Isolation Level | PostgreSQL | MySQL (InnoDB) | Oracle Database | CockroachDB |
|---|---|---|---|---|
| Read Uncommitted | Promoted to Read Committed | Pure Dirty Read (no MVCC read view) | Not supported | Promoted to Serializable |
| Read Committed | MVCC statement snapshot | MVCC statement snapshot | MVCC statement snapshot | Read Committed (Historical read) |
| Repeatable Read | Snapshot Isolation (Aborts on write conflict) | Snapshot Isolation for reads; Next-Key Locks for writes | Not supported (Oracle calls SI “Serializable”) | Promoted to Serializable |
| Serializable | SSI (SIREAD locks + graph analysis) | 2PL (Converts all reads to LOCK IN SHARE MODE) | Snapshot Isolation (Vulnerable to Write Skew!) | Serializable (SSI + Raft consensus) |
The Oracle Gotcha: In Oracle Database, setting
SET TRANSACTION ISOLATION LEVEL SERIALIZABLEdoes not give you true serializability! It gives you standard Snapshot Isolation, which remains vulnerable to Write Skew ($A5B$).
7. Architectural Decision Framework: Choosing the Right Level
Choosing an isolation level requires balancing correctness against system operational limits.
+-----------------------------------------------------------------------------+
| Isolation Level Selection Decision Flow |
+-----------------------------------------------------------------------------+
Does workload involve concurrent
read-modify-write on related entities?
|
+----------------+----------------+
| NO | YES
v v
Read Committed Can conflicts be resolved by
(High Throughput API, explicit atomic SQL increments?
Content Catalog, CMS) |
+-------------+-------------+
| YES | NO
v v
Read Committed Do you have a strict
(atomic: UPDATE ... cross-row business rule
SET c = c + 1) (e.g., Doctor on-call)?
|
+-------------------+-------------------+
| YES | NO
v v
Serializable Repeatable Read /
(With Retry Runner) Snapshot Isolation
Workload Characteristics & Recommended Levels
- High-Throughput E-Commerce / SaaS APIs:
- Recommended:
READ COMMITTEDwith explicit atomic operations. - Pattern: Instead of reading a quantity and updating it in memory, write:
UPDATE inventory SET stock = stock - 1 WHERE product_id = 99 AND stock >= 1; - Why: Zero serialization aborts, minimal locking overhead, high throughput.
- Recommended:
- Financial Ledgers & Double-Entry Accounting:
- Recommended:
SERIALIZABLEorREAD COMMITTEDwith strictSELECT ... FOR UPDATElocking in deterministic order. - Why: Eliminates Read Skew and Write Skew across multi-currency account pairs.
- Recommended:
- Background Worker Queues & Job Schedulers:
- Recommended:
READ COMMITTEDwith explicit row-level locking:SELECT id, payload FROM job_queue WHERE status = 'PENDING' ORDER BY priority DESC LIMIT 10 FOR UPDATE SKIP LOCKED; - Why: Zero contention between concurrent worker threads; skipped rows allow parallel dequeue without thread starvation.
- Recommended:
8. Production Implementation: The Resilient Transaction Retry Runner
When using REPEATABLE READ or SERIALIZABLE, serialization failures (SQLSTATE 40001) and deadlocks (SQLSTATE 40P01) are normal operational occurrences, not bugs.
Any application operating at higher isolation levels must wrap transactions in an automated retry runner with exponential backoff and randomized full jitter.
Production-Grade TypeScript Retry Engine
import { Pool, PoolClient } from 'pg';
interface RetryOptions {
maxRetries?: number;
initialDelayMs?: number;
maxDelayMs?: number;
isolationLevel?: 'READ COMMITTED' | 'REPEATABLE READ' | 'SERIALIZABLE';
}
const SERIALIZATION_FAILURE = '40001';
const DEADLOCK_DETECTED = '40P01';
/**
* Executes a transactional unit of work with automated retry logic
* for transient concurrency errors (serialization failures and deadlocks).
*/
export async function runTransactionWithRetry<T>(
pool: Pool,
work: (client: PoolClient) => Promise<T>,
options: RetryOptions = {}
): Promise<T> {
const {
maxRetries = 5,
initialDelayMs = 50,
maxDelayMs = 1000,
isolationLevel = 'SERIALIZABLE',
} = options;
let attempt = 0;
while (true) {
const client = await pool.connect();
attempt++;
try {
await client.query(`BEGIN TRANSACTION ISOLATION LEVEL ${isolationLevel}`);
// Execute application business logic
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error: any) {
await client.query('ROLLBACK').catch(() => {});
const isTransientError =
error.code === SERIALIZATION_FAILURE || error.code === DEADLOCK_DETECTED;
if (!isTransientError || attempt >= maxRetries) {
throw new Error(
`Transaction failed (Attempt ${attempt}/${maxRetries}): ${error.message} [SQLSTATE: ${error.code}]`
);
}
// Exponential backoff with Full Jitter: Sleep = rand(0, min(maxDelay, base * 2^attempt))
const backoffLimit = Math.min(maxDelayMs, initialDelayMs * Math.pow(2, attempt));
const jitterDelay = Math.floor(Math.random() * backoffLimit);
console.warn(
`[Concurrency Conflict] SQLSTATE ${error.code} on attempt ${attempt}. Retrying in ${jitterDelay}ms...`
);
await new Promise((resolve) => setTimeout(resolve, jitterDelay));
} finally {
client.release();
}
}
}
Handling the Doctor On-Call Problem in Production
Here is how the doctor on-call problem is safely resolved in application code using the retry runner:
async function requestLeave(pool: Pool, doctorId: number): Promise<boolean> {
return runTransactionWithRetry(
pool,
async (client) => {
// 1. Check invariant under SERIALIZABLE isolation
const countRes = await client.query(
'SELECT count(*) FROM doctors WHERE on_call = true'
);
const activeCount = parseInt(countRes.rows[0].count, 10);
if (activeCount <= 1) {
throw new Error('Leave rejected: At least one doctor must remain on-call.');
}
// 2. Mutate state
await client.query(
'UPDATE doctors SET on_call = false WHERE id = $1',
[doctorId]
);
return true;
},
{ isolationLevel: 'SERIALIZABLE', maxRetries: 3 }
);
}
9. Production Diagnostics & Observability
You cannot optimize what you do not measure. In production environments running high concurrency, monitor lock contention and transaction durations using these diagnostic queries.
1. Tracking Serialization Failures in PostgreSQL
Monitor serialization conflicts in pg_stat_database to detect abort storms:
SELECT
datname,
xact_commit,
xact_rollback,
conflicts,
round((conflicts::numeric / nullif(xact_commit + xact_rollback, 0)) * 100, 4) AS conflict_pct
FROM pg_stat_database
WHERE datname = current_database();
2. Identifying Active Lock Contention & Blocked Sessions
Find queries blocked waiting for row or table locks:
SELECT
blocked_locks.pid AS blocked_pid,
blocked_activity.usename AS blocked_user,
blocking_locks.pid AS blocking_pid,
blocking_activity.usename AS blocking_user,
blocked_activity.query AS blocked_statement,
blocking_activity.query AS current_statement_in_blocking_process
FROM pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks
ON blocking_locks.locktype = blocked_locks.locktype
AND blocking_locks.database IS NOT DISTINCT FROM blocked_locks.database
AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation
AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page
AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple
AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid
AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid
AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid
AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid
AND blocking_locks.pid != blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.granted;
3. Killing Stale Idle-in-Transaction Connections
Connections left open in idle in transaction hold back the engine’s vacuum horizon and freeze locks:
-- Terminate transactions that have been idle inside a transaction block for over 5 minutes
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction'
AND state_change < now() - INTERVAL '5 minutes'
AND pid <> pg_backend_pid();
10. Architectural Summary & Engineering Checklist
Mastering database isolation levels requires shifting from theoretical textbook rules to empirical operational trade-offs:
- Default to
READ COMMITTED: Unless your system exhibits proven multi-row write skew anomalies, stay onREAD COMMITTED. Use atomic SQL expressions (SET count = count + 1) to eliminate lost updates. - Beware the ANSI SQL-92 Lie: Remember that ANSI SQL-92 is obsolete. Understand that PostgreSQL’s
REPEATABLE READis actually Snapshot Isolation (preventing Phantoms), and Oracle’sSERIALIZABLEis actually Snapshot Isolation (vulnerable to Write Skew). - Implement Retries on Higher Levels: If you switch to
REPEATABLE READorSERIALIZABLE, build an automated transaction retry runner with exponential backoff and jitter into your data access layer. - Use Explicit Locking Judiciously: For queue processing, always use
SELECT ... FOR UPDATE SKIP LOCKED. For inventory or ledger updates underREAD COMMITTED, use deterministicSELECT ... FOR UPDATEorderings to avoid deadlocks. - Guard Against Vacuum Starvation: Configure
idle_in_transaction_session_timeout(e.g., 30s) in PostgreSQL to prevent rogue transactions from blocking vacuuming and causing table bloat.
Related Database Architecture Guides & Interactive Lab
- Database Transactions & ACID Isolation Levels: The Complete Engineering Guide
- PostgreSQL Internals: Under the Hood of MVCC, WAL, and VACUUM
- The Architect’s Guide to PostgreSQL Connection Pooling
- SQL Query Optimization: Cost Planners, Join Internals, and Execution Mechanics
- Interactive SQL Practice Lab (Client-Side WASM)
Ready to Level Up Your SQL?
Don't just read about databases. Write queries, build schemas, and practice real-world interview questions interactively.