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

Transaction Isolation &
Distributed ACID.

Isolation levels control which concurrent read/write anomalies a database permits, trading throughput and lock/abort rates for correctness—while distributed ACID extends those guarantees across shards via 2PC, TrueTime, or HLCs.
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, postgreSQL's REPEATABLE READ is Snapshot Isolation (still vulnerable to Write Skew), not true Serializability; across shards, distributed ACID requires either 2PC + SSI/TrueTime commit-wait or deterministic ordering—and retry loops for 40001 serialization failures.

TL;DR30-second simplified summary
▾

Core Mechanics: Transaction isolation defines the illusion a database gives each concurrent transaction: at the strongest level (SERIALIZABLE), concurrent transactions produce the exact same final state as if they had executed one-by-one in some serial order.

Visual & Structural Flow: Depicts MVCC Version Chain & Write-Ahead Log (WAL) (Transaction T2 -> MVCC Visibility -> WAL (fsync) -> Tuple Versions); Isolation Escalation: Read Committed -> SI -> SSI (READ COMMITTED -> REPEATABLE READ / SI -> SERIALIZABLE (SSI)).

Trade-Offs & Production: READ COMMITTED avoids 40001 serialization aborts and maximizes throughput for independent single-row updates. 1.

Failure Modes & Application: PostgreSQL's REPEATABLE READ is Snapshot Isolation (still vulnerable to Write Skew), not true Serializability; across shards, distributed ACID requires either 2PC + SSI/TrueTime commit-wait or deterministic ordering—and retry loops for 40001 serialization failures.

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 is Transaction Isolation & Distributed ACID.

Why this matters: The mechanism: understand how Transaction Isolation & Distributed ACID works from first principles.

The idea Transaction isolation defines the illusion a database gives each concurrent transaction: at the strongest level (SERIALIZABLE), concurrent transactions produce the exact same final state as if they had executed one-by-one in some serial order. Weakening isolation boosts concurrency by letting transactions read slightly stale or uncommitted data, but reintroduces anomalies (Lost Updates, Phantoms, Write Skew). Extending ACID across distributed shards adds two hard constraints: atomicity across independent nodes (Two-Phase Commit over Raft) and global timestamp ordering without a single bottleneck clock (TrueTime or Hybrid Logical Clocks).

Core Pillars:

  • ANSI SQL-92 defines 4 levels (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE) around Dirty Reads, Non-Repeatable Reads, and Phantoms, but misses Lost Updates and Write Skew (Berenson et al. 1995).
  • PostgreSQL REPEATABLE READ implements Snapshot Isolation (MVCC): readers never block writers, but two transactions reading the same snapshot and writing to disjoint rows still cause Write Skew.
  • PostgreSQL SERIALIZABLE uses SSI (Serializable Snapshot Isolation) via SIREAD predicate locks—detecting dangerous rw-antidependency cycles without blocking readers, aborting one transaction with SQLSTATE 40001.
  • Distributed ACID combines Two-Phase Commit (2PC) (or Raft-replicated coordinators) with Global Ordering: Spanner uses atomic/GPS clocks (TrueTime commit-wait >= 2ε, ~7 ms), while CockroachDB uses Hybrid Logical Clocks (HLC) + read restarts.
  • In MySQL InnoDB, REPEATABLE READ uses Next-Key Locks (record + gap locks) on locking reads (FOR UPDATE) to prevent phantoms, which can cause unexpected gap-lock deadlocks.
MVCC Snapshot Isolation

MVCC Version Chain & Write-Ahead Log (WAL)

Transaction T2Snapshot xmin/xmaxMVCC VisibilityReaders never block writersWAL (fsync)Durable redo logTuple Versionsv1(committed) -> v2(T2)

MVCC stores multiple row versions tagged with transaction IDs so readers see a consistent snapshot while writers append new versions.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why we need Transaction Isolation & Distributed ACID (and what fails without it).

Why this matters: The problem: see what breaks without Transaction Isolation & Distributed ACID under real concurrency or scale.

Default READ COMMITTED isolation lets two concurrent transfers check balance >= $100 simultaneously and both withdraw, leaving a negative balance. Even upgrading to REPEATABLE READ (Snapshot Isolation) in PostgreSQL still allows Write Skew—for example, two on-call doctors both checking that 2 doctors are on shift and both signing off at the same time, leaving 0 on call. In distributed databases (Spanner, CockroachDB, TiDB), preserving ACID across shards adds cross-node clock uncertainty and network round-trips that directly impact p99 tail latency.

Common Pitfalls:

  • Assuming REPEATABLE READ in PostgreSQL prevents Write Skew—it only prevents Dirty Reads, Non-Repeatable Reads, Phantoms, and Lost Updates.
  • Catching 40001 serialization errors and retrying non-idempotent side effects (like sending an email or charging Stripe) inside the same transaction block.
  • Using SELECT * FROM accounts FOR UPDATE in READ COMMITTED without realizing PostgreSQL re-evaluates the WHERE clause after waiting on a lock, which can still miss newly inserted rows.
Engineering Decision Framework
Problem
How to implement Transaction Isolation & Distributed ACID 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, postgreSQL's REPEATABLE READ is Snapshot Isolation (still vulnerable to Write Skew), not true Serializability; across shards, distributed ACID requires either 2PC + SSI/TrueTime commit-wait or deterministic ordering—and retry loops for 40001 serialization failures.
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 Transaction Isolation & Distributed ACID experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

Failure Mode

Mitigation: Wrap transactions in an idempotent retry loop (max 3–5 attempts with jittered exponential backoff) specifically catching SQLSTATE 40001 (serialization_failure) and 40P01 (deadlock_detected).

Failure Mode

Mitigation: Use Raft/Paxos-replicated transaction coordinators (Spanner, CockroachDB, TiDB) so a new leader immediately resolves IN_DOUBT transactions.

Failure Mode

Mitigation: Run local chrony with redundant NTP/PTP sources, monitor clock_offset metrics, and configure nodes to self-terminate if skew exceeds max_offset.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where Transaction Isolation & Distributed ACID is used (and where to avoid it).

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

Think of Where Transaction Isolation & Distributed ACID is used (and where to avoid it) as the intuition layer for Transaction Isolation & Distributed ACID: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Transaction Isolation & Distributed ACID delivers the highest leverage at well-defined architectural boundaries. Use it for financial ledgers, double-entry accounting, and inventory/seat reservations where lost updates, phantom reads, or write skew violate business invariants.

ChoiceWhat it buysWhat it costs
Production Fit #1Financial ledgers, double-entry accounting, and inventory/seat reservations where lost updates, phantom reads, or write skew violate business invariants.High-contention counters (like post view counts or rate-limiters) where `SERIALIZABLE` triggers 30%+ `40001` aborts—use atomic `UPDATE ... SET count = count + 1`, Redis `INCR`, or sharded counters.
Production Fit #2Multi-shard writes in CockroachDB, Google Spanner, or YugabyteDB where cross-partition atomicity and external consistency (linearizability) are required.Multi-service workflows spanning external HTTP APIs (Stripe, Twilio) where holding distributed locks across network calls causes cascading timeouts; use the Saga + Transactional Outbox pattern instead.
Production Fit #3Read-heavy analytics or billing snapshots (`REPEATABLE READ`) that need a consistent point-in-time view across multiple tables without blocking concurrent writers.Append-only telemetry or event logs where `READ COMMITTED` suffices and zero-coordination throughput is the priority.
On-Call Doctor Write Skew Under Snapshot IsolationRequires strict operational guardrails and observability.
Cross-Shard Ledger Transfer in CockroachDB vs. SpannerRequires strict operational guardrails and observability.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How Transaction Isolation & Distributed ACID works under the hood & reference implementation.

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

Concrete walkthrough Trace a distributed SERIALIZABLE transfer of $500 from Account A (Shard 1) to Account B (Shard 2) in a Spanner/CockroachDB-style engine:

  1. Begin & Timestamp: Coordinator assigns transaction T1 a read/write timestamp ts = HLC.now() (or TT.now().latest) and creates a Raft-replicated PENDING transaction record.
  2. Parallel Write Intents: T1 writes provisional write intents (Account A: -500, Account B: +500) to Shard 1 and Shard 2 via Raft consensus.
  3. 2PC Prepare & Conflict Check: Each shard checks for conflicting READ timestamps > ts or concurrent write intents. If another transaction T2 already read Account A at ts + 1, Shard 1 rejects T1 with 40001.
  4. Commit & Commit-Wait: Once both shards vote PREPARED, the coordinator flips the transaction record to COMMITTED via Raft (and in Spanner, waits out 2ε ~7 ms so now_real > ts).
  5. Async Intent Resolution: T1 returns OK to the client immediately and asynchronously clears the write intent flags on Shards 1 and 2.

The idea Transaction isolation defines the illusion a database gives each concurrent transaction: at the strongest level (SERIALIZABLE), concurrent transactions produce the exact same final state as if they had executed one-by-one in some serial order. Weakening isolation boosts concurrency by letting transactions read slightly stale or uncommitted data, but reintroduces anomalies (Lost Updates, Phantoms, Write Skew). Extending ACID across distributed shards adds two hard constraints: atomicity across independent nodes (Two-Phase Commit over Raft) and global timestamp ordering without a single bottleneck clock (TrueTime or Hybrid Logical Clocks).

Lifecycle & Failure Recovery

How Transaction Isolation & Distributed ACID works under the hood & reference implementation

index scanfsync WALdeadlock / skewTx Active(Snapshot)Row Lock HeldWAL FlushedSerializationRetry

Reference implementation (Python — Durable WAL Append & Flush)

# Write-Ahead Log (WAL) append + fsync batching helper (Python)
import os, json
class WalWriter:
    def __init__(self, path: str):
        self.fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
    def append_and_flush(self, record: dict) -> None:
        line = (json.dumps(record, separators=(",", ":")) + "\n").encode("utf-8")
        os.write(self.fd, line)
        os.fsync(self.fd)

Operational Guidelines

  • Core mental model: PostgreSQL's REPEATABLE READ is Snapshot Isolation (still vulnerable to Write Skew), not true Serializability; across shards, distributed ACID requires either 2PC + SSI/TrueTime commit-wait or deterministic ordering—and retry loops for 40001 serialization failures.
  • Avoid trap: Assuming REPEATABLE READ in PostgreSQL prevents Write Skew—it only prevents Dirty Reads, Non-Repeatable Reads, Phantoms, and Lost Updates.
  • Avoid trap: Catching 40001 serialization errors and retrying non-idempotent side effects (like sending an email or charging Stripe) inside the same transaction block.
  • When to reach for it: Financial ledgers, double-entry accounting, and inventory/seat reservations where lost updates, phantom reads, or write skew violate business invariants.
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives & trade-offs for Transaction Isolation & Distributed ACID.

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

Think of Alternatives & trade-offs for Transaction Isolation & Distributed ACID as the intuition layer for Transaction Isolation & Distributed ACID: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Evaluating Transaction Isolation & Distributed ACID against alternatives requires balancing latency, operational overhead, failure blast radius, and cost. READ COMMITTED avoids 40001 serialization aborts and maximizes throughput for independent single-row updates.

Design Trade-Off

Alternatives & trade-offs for Transaction Isolation & Distributed ACID

Before · Seq Scan + Unbounded Bloat
  • Implicit cast breaks B-Tree
  • Deadlock or XID wraparound risk
  • Long tx blocks VACUUM
After · Indexed Plan + Bounded MVCC
  • Index-only scan in <2 ms
  • Deterministic lock ordering
  • Autovacuum keeps bloat flat
ChoiceWhat it buysWhat it costs
READ COMMITTED vs. SERIALIZABLE (SSI)`READ COMMITTED` avoids `40001` serialization aborts and maximizes throughput for independent single-row updates.Requires manual `SELECT ... FOR UPDATE` or optimistic version columns (`WHERE version = ?`) on every multi-row invariant, or subtle race conditions slip in.
Pessimistic Locking (2PL) vs. Optimistic MVCC / SSI2PL (`FOR UPDATE` / InnoDB Next-Key Locks) guarantees the lock holder commits without retrying under high contention.Writers block readers/writers, risking lock convoys and deadlocks across shards; SSI never blocks readers but aborts conflicting writers at commit time.
TrueTime Commit-Wait (Spanner) vs. HLC Uncertainty Restarts (CockroachDB)Spanner's `2ε` (~7 ms) commit wait gives strict external consistency—if T1 finishes before T2 starts in real time, T2 is guaranteed to see T1.Adds mandatory ~7–14 ms to every write commit and requires specialized atomic/GPS clocks; HLC runs on commodity NTP VMs at the cost of occasional read restarts.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production architecture & hardening for Transaction Isolation & Distributed ACID.

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

Failure modes

  1. Convoy Effect on Hot Keys: Under 2PL (SELECT ... FOR UPDATE), 200 concurrent threads updating the same merchant balance form a serial queue; if each takes 15 ms, the 200th waits 3 seconds and triggers client timeouts.
  2. SSI False-Positive Aborts: PostgreSQL's SIREAD locks track page/tuple granularity; heavy concurrent inserts on the same B-tree leaf page can trigger 40001 aborts even between logically disjoint transactions.
  3. Cross-Region RTT Amplification: Synchronous 2PC + Raft across 3 continents adds 80–150 ms per commit, collapsing single-key throughput to ~10 TPS unless batched or localized via geo-partitioning.

Practical checklist

  • [ ] Audit every READ COMMITTED read-modify-write path for Lost Updates (FOR UPDATE or atomic UPDATE ... WHERE).
  • [ ] Use SERIALIZABLE (or explicit parent-row locking) whenever an invariant spans multiple rows (e.g., quotas, shifts, ledgers).
  • [ ] Implement an idempotent retry wrapper for SQLSTATE 40001 / 40P01 with jittered backoff.
  • [ ] Keep transactions short: never make external HTTP calls (Stripe, SMTP) inside an open DB transaction.
  • [ ] Enforce statement_timeout and idle_in_transaction_session_timeout to protect MVCC vacuuming.
Anomaly Prevention

Isolation Escalation: Read Committed -> SI -> SSI

freeze tx-start snapshottrack SIREAD locks -> 40001READ COMMITTEDFresh snapshot per stmtREPEATABLE READ /SIWrite skew still possiblSERIALIZABLE (SSI)rw-antidependency abort

Snapshot Isolation prevents dirty and non-repeatable reads, but only Serializable (SSI) or explicit `SELECT FOR UPDATE` prevents write skew.

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

Problems solved by Transaction Isolation & Distributed ACID & Related Concepts.

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

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

Apply Transaction Isolation & Distributed ACID to real-world engineering problems and explore adjacent architectural concepts below.

Request & State Flow

Problems solved by Transaction Isolation & Distributed ACID & Related Concepts

Client TxPlanner / Lock MgrWAL / MemTableHeap / SSTable1. Acquire snapshot / index plan2. Append redo record + fsync WAL3. Flush dirty pages / compactSSTables4. Commit & release row locks
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Two doctors simultaneously check an on-call table under Snapshot Isolation: both see 2 doctors on call, and both update their own distinct rows to go off-call, leaving 0 doctors. What is this anomaly?

Recommended Learning Flow