Skip to main content
← CONCEPTS / DISTRIBUTED SYSTEMS & STORAGE
An end-to-end domain learning journey

Database Isolation Levels
& Transaction Anomalies.

Database isolation levels control what concurrent transaction anomalies—dirty reads, non-repeatable reads, phantom reads, and write skew—are permitted in exchange for lower locking or coordination overhead.
Start the journey7 sections· Last modified Oct 5, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When durability and read throughput pull in opposite directions, read Committed does not prevent lost updates or read skew; Snapshot Isolation prevents read anomalies via MVCC but still allows write skew unless you use explicit `SELECT FOR UPDATE` or true Serializable isolation.

TL;DR30-second simplified summary
▾

Core Mechanics: Isolation (the I in ACID) defines which concurrent transaction side effects are visible.

Visual & Structural Flow: Depicts How MVCC Separates Concurrent Readers from Uncommitted Writers (Tx1 Reader (snap=100) -> MVCC Tuple Chain -> WAL + pg_xact -> SIREAD Predicate Lock); Concurrent Room Booking: Snapshot Isolation Double-Books vs. SSI Aborts 40001 (Tx1 (Alice) -> Postgres MVCC -> Tx2 (Bob)); Serializable Transaction Execution & 40001 Retry State Machine (EXEC IN SNAPSHOT -> COMMITTED -> 40001 ABORT).

Trade-Offs & Production: Two engines claiming the same ANSI level behave differently under the hood. Combine SERIALIZABLE (or parent-row FOR UPDATE under high >10% contention) with an application-boundary retry state machine, and monitor pg_stat_database.deadlocks and xact_rollback alongside oldest xmin age.

Failure Modes & Application: Explore concrete SQL isolation anomalies, InnoDB gap-lock deadlocks, PostgreSQL XID wraparound, and ACID fundamentals.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Distributed & Application Caching
Caching keeps a reusable copy of data so an application can avoid repeating a database query, calculation, or network call. It can make responses faster and reduce database load. The trade-off: the copy may be out of date.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What are Isolation Levels & MVCC Snapshots.

Why this matters: The mechanism: understand how Isolation Levels & MVCC Snapshots works from first principles.

Isolation (the I in ACID) defines which concurrent transaction side effects are visible. While ANSI SQL-92 defined four levels around Dirty Reads, Non-Repeatable Reads, and Phantoms, modern MVCC engines (PostgreSQL, InnoDB, CockroachDB) also confront Read Skew, Lost Updates, and Write Skew.

Under MVCC, readers read a consistent snapshot (xmin/xmax or HLC timestamp) without blocking writers, and writers don't block readers. However, Snapshot Isolation (REPEATABLE READ in Postgres) still allows Write Skew unless upgraded to Serializable Snapshot Isolation (SSI) or Two-Phase Locking (2PL).

MVCC Snapshot Visibility

How MVCC Separates Concurrent Readers from Uncommitted Writers

Tx1 Reader (snap=100)Reads xmin<=100 committedMVCC Tuple Chainxmin=95 / xmax=102WAL + pg_xactAtomic commit statusSIREAD Predicate LockDetects…

MVCC lets readers and writers run concurrently without blocking; SSI adds lightweight SIREAD tracking to catch write-skew cycles.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why Default Isolation Permits Write Skew & Lost Updates.

Why this matters: The problem: see what breaks without Why Default Isolation Permits Write Skew & Lost Updates under real concurrency or scale.

Think of Why Default Isolation Permits Write Skew & Lost Updates as the intuition layer for Database Isolation Levels & Transaction Anomalies: The problem: see what breaks without Why Default Isolation Permits Write Skew & Lost Updates under real concurrency or scale.

PostgreSQL defaults to READ COMMITTED (which permits lost updates on read-modify-write and read skew across statements), and REPEATABLE READ implements Snapshot Isolation (which still permits Write Skew when two transactions read an overlapping premise and update disjoint rows).

Write Skew vs SSI

Concurrent Room Booking: Snapshot Isolation Double-Books vs. SSI Aborts 40001

Tx1 (Alice)Postgres MVCCTx2 (Bob)1. SELECT COUNT(*) room=101 -> 02. SELECT COUNT(*) room=101 -> 03. INSERT (id=501, room=101) ->COMMIT4. INSERT (id=502, room=101) ->SI: Double-Book!5. SSI: rw-cycle detected -> ABORT40001

Because 501 != 502, Snapshot Isolation sees no write-write conflict and commits both; SSI tracks SIREAD locks and aborts Tx2 with SQLSTATE 40001.

Engineering Decision Framework
Problem
How to implement Database Isolation Levels & Transaction Anomalies without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When durability and read throughput pull in opposite directions, read Committed does not prevent lost updates or read skew; Snapshot Isolation prevents read anomalies via MVCC but still allows write skew unless you use explicit SELECT FOR UPDATE or true Serializable isolation.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Database Isolation Levels & Transaction Anomalies experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

On-Call Doctor Write Skew under Snapshot Isolation

Two doctors both queried COUNT(*) WHERE on_call = true (saw 2) and updated their own disjoint rows to false, leaving 0 doctors on call. Switching to SERIALIZABLE (SSI) aborted the second commit with 40001.

Flash-Sale Lost Update under Read Committed

Two threads read stock = 1 in app memory and both wrote 0. Replacing read-modify-write with UPDATE inventory SET stock = stock - 1 WHERE sku = 'X' AND stock > 0 eliminated the race at READ COMMITTED.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where Each Isolation Level Fits.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where Each Isolation Level Fits as the intuition layer for Database Isolation Levels & Transaction Anomalies: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Match isolation level to the invariant scope—you don't always need global SERIALIZABLE if an atomic SQL expression or UNIQUE / EXCLUDE constraint enforces the rule.

ChoiceWhat it buysWhat it costs
Read Committed (PG Default)Lowest overhead; safe for independent single-row writes and atomic `SET bal = bal - 50 WHERE bal >= 50`.Allows read skew and lost updates on app-level read-modify-write.
Repeatable Read / Snapshot IsolationConsistent multi-table reporting and backups without blocking writers.Allows Write Skew on disjoint rows; long transactions block `VACUUM` / undo purge.
Serializable (PG SSI / CockroachDB / Spanner)Eliminates all anomalies including Write Skew automatically.Requires client-side retry loops for `SQLSTATE 40001` aborts under contention.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How to manage Retries, Deadlocks & MVCC Bloat.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

1.

Retry 40001 & 40P01: Always wrap REPEATABLE READ/SERIALIZABLE transactions in a bounded, jittered retry loop. 2. Canonical Lock Ordering: When using `SELECT ...

Lifecycle & Failure Recovery

How to manage Retries, Deadlocks & MVCC Bloat

index scanfsync WALdeadlock / skewTx Active(Snapshot)Row Lock HeldWAL FlushedSerializationRetry
# Idempotent PostgreSQL SERIALIZABLE retry wrapper for SQLSTATE 40001 / 40P01 (Python)
import time, random

def run_serializable(conn, fn, max_attempts: int = 5):
    for attempt in range(max_attempts):
        try:
            with conn.cursor() as cur:
                cur.execute("BEGIN ISOLATION LEVEL SERIALIZABLE")
                result = fn(cur)
                conn.commit()
                return result
        except Exception as err:
            conn.rollback()
            sqlstate = getattr(err, 'sqlstate', None)
            if sqlstate not in ('40001', '40P01') or attempt == max_attempts - 1:
                raise
            time.sleep(random.uniform(0.01, 0.05 * (2 ** attempt)))
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: Engine Behavior & Invariant Enforcement.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: Engine Behavior & Invariant Enforcement as the intuition layer for Database Isolation Levels & Transaction Anomalies: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Two engines claiming the same ANSI level behave differently under the hood.

ChoiceWhat it buysWhat it costs
PostgreSQL (Pure MVCC + SSI)`REPEATABLE READ` prevents phantoms via Snapshot Isolation; `SERIALIZABLE` uses SSI without blocking readers.False-positive `40001` aborts can occur when `SIREAD` locks coarsen to page level.
MySQL InnoDB (MVCC + Next-Key Locks)Locking reads (`FOR UPDATE`) use record + gap locks to stop phantoms.Gap locks frequently cause `Error 1213` deadlocks on concurrent `INSERT ... ON DUPLICATE KEY UPDATE`.
DB Constraints (`UNIQUE` / `EXCLUDE USING gist`)Enforces non-overlapping bookings or uniqueness at engine level even under `READ COMMITTED`.Limited to constraints expressible on a single table/index.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production Architecture: SSI Transaction State & Retry Lifecycle.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production Architecture: SSI Transaction State & Retry Lifecycle as the intuition layer for Database Isolation Levels & Transaction Anomalies: Production architecture: see how the components compose end to end under real load.

Combine SERIALIZABLE (or parent-row FOR UPDATE under high >10% contention) with an application-boundary retry state machine, and monitor pg_stat_database.deadlocks and xact_rollback alongside oldest xmin age.

SSI Retry Loop

Serializable Transaction Execution & 40001 Retry State Machine

No conflict cyclerw-antidependency cycleBackoff < max_attemptsEXEC IN SNAPSHOTTrack SIREAD locksCOMMITTEDNo rw-cycle found40001 ABORTRollback + jitter retry

SSI aborts with SQLSTATE 40001 are normal concurrency control signals—not bugs—and must be retried idempotently.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved & Related Concepts.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved & Related Concepts as the intuition layer for Database Isolation Levels & Transaction Anomalies: Applied problems: connect these internals to concrete system design and debugging scenarios.

Explore concrete SQL isolation anomalies, InnoDB gap-lock deadlocks, PostgreSQL XID wraparound, and ACID fundamentals.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Under PostgreSQL `REPEATABLE READ` (Snapshot Isolation), two concurrent transactions both count 2 on-call doctors and each updates a different doctor row to `on_call = false`, leaving 0 doctors on call. Why did Postgres allow both commits?

Recommended Learning Flow