Skip to main content
← PROBLEMS / ARCHITECTURE
An end-to-end domain learning journey

SQL Isolation Levels:
Preventing Phantom Reads.

Under READ COMMITTED, each SQL statement acquires a fresh snapshot, allowing concurrent INSERTs to appear mid-transaction as phantom rows; meanwhile, PostgreSQL REPEATABLE READ prevents phantoms via transaction-level snapshots but still permits write skew without SERIALIZABLE or explicit parent locking.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, match isolation to the invariant: use PostgreSQL SERIALIZABLE (with retry on SQLSTATE 40001) or explicit parent-row SELECT ... FOR UPDATE for multi-row business invariants, and understand how PostgreSQL SSI differs from InnoDB Next-Key Locking.

TL;DR30-second simplified summary
▾

Core Mechanics: A PostgreSQL 16 quota service enforces SUM(gpus) <= 16 per project (5–20 concurrent requests/sec per project, 10,000 active projects).

Visual & Structural Flow: Depicts PostgreSQL REPEATABLE READ Allows Both Quota Inserts to Commit (Tx A (+6 GPUs) -> Postgres MVCC -> Tx B (+6 GPUs)); MVCC Snapshot + SIREAD Predicate Locks / Parent Row Lock (Tx A & Tx B (5-20 RPS/proj) -> Postgres 16 MVCC / SSI -> projects (Parent Row) -> allocations (Child Rows)).

Trade-Offs & Production: Unlike MySQL InnoDB—which uses Next-Key (Gap) Locks to block phantom INSERTs into a range under REPEATABLE READ—PostgreSQL has no gap locks. Enforce multi-row invariants cleanly at < 40 ms p99 across 10,000 projects: Parent-Row SELECT ... FOR UPDATE: Lock the single projects row (WHERE id = $1 FOR UPDATE) before querying SUM(gpus) and inserting.

Failure Modes & Application: Understanding MVCC vs. locking isolation prevents subtle financial and quota bugs: Cloud Quota & Seat-Limit Enforcement: Prevents over-allocating GPUs, licenses, or shift slots.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why SELECT SUM(...) + INSERT breaks quota invariants under MVCC.

Why this matters: The mechanism: understand how Why SELECT SUM(...) + INSERT breaks quota invariants under MVCC works from first principles.

Think of Why SELECT SUM(...) + INSERT breaks quota invariants under MVCC as the intuition layer for SQL Isolation Levels: Preventing Phantom Reads: The mechanism: understand how Why SELECT SUM(...) + INSERT breaks quota invariants under MVCC works from first principles.

A PostgreSQL 16 quota service enforces SUM(gpus) <= 16 per project (5–20 concurrent requests/sec per project, 10,000 active projects). Under default READ COMMITTED, each statement takes a fresh MVCC snapshot—allowing two concurrent transactions to both read SUM(gpus) = 12, both insert 4 GPUs (Wait—or 8 GPUs!), and silently violate the 16-GPU cap.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Phantom rows under READ COMMITTED and write skew under REPEATABLE READ.

Why this matters: The problem: see what breaks without Phantom rows under READ COMMITTED and write skew under REPEATABLE READ under real concurrency or scale.

Multi-row invariants fail silently across two isolation levels in PostgreSQL:

  1. Phantom Reads (READ COMMITTED): Concurrent INSERTs committed by Tx B appear mid-transaction in Tx A.
  2. Write Skew (REPEATABLE READ): PostgreSQL's Snapshot Isolation eliminates phantoms for queries, but two concurrent INSERTs see the same pre-insert SUM and both commit, violating the 16-GPU or 3-on-call-engineer cap.
Snapshot Isolation Write Skew

PostgreSQL REPEATABLE READ Allows Both Quota Inserts to Commit

Tx A (+6 GPUs)Postgres MVCCTx B (+6 GPUs)1. BEGIN REPEATABLE READ (SUM=10)2. BEGIN REPEATABLE READ (SUM=10)3. 10+6 <= 16 -> INSERT + COMMIT4. 10+6 <= 16 -> INSERT + COMMIT!5. Fix: SERIALIZABLE (40001) / FORUPDATE

PostgreSQL REPEATABLE READ prevents phantoms, but only SERIALIZABLE (SSI) or parent-row FOR UPDATE prevents write skew.

Engineering Decision Framework
Problem
How to implement SQL Isolation Levels: Preventing Phantom Reads 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
To keep the architecture evolvable without sacrificing reliability, match isolation to the invariant: use PostgreSQL SERIALIZABLE (with retry on SQLSTATE 40001) or explicit parent-row SELECT ... FOR UPDATE for multi-row business invariants, and understand how PostgreSQL SSI differs from InnoDB Next-Key Locking.
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 SQL Isolation Levels: Preventing Phantom Reads experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Why SELECT ... FOR UPDATE on child rows fails in PostgreSQL.

Why this matters: The problem: see what breaks without Why SELECT ... FOR UPDATE on child rows fails in PostgreSQL under real concurrency or scale.

Unlike MySQL InnoDB—which uses Next-Key (Gap) Locks to block phantom INSERTs into a range under REPEATABLE READ—PostgreSQL has no gap locks.

Running `SELECT ...

Lifecycle & Failure Recovery

Why SELECT ... FOR UPDATE on child rows fails in PostgreSQL

index scanfsync WALdeadlock / skewTx Active(Snapshot)Row Lock HeldWAL FlushedSerializationRetry
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: PostgreSQL SERIALIZABLE (SSI) or Parent-Row FOR UPDATE.

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

Enforce multi-row invariants cleanly at < 40 ms p99 across 10,000 projects:

  • Parent-Row SELECT ... FOR UPDATE: Lock the single projects row (WHERE id = $1 FOR UPDATE) before querying SUM(gpus) and inserting. Contention is scoped per-project (5–20 RPS), leaving the other 9,999 projects lock-free.
  • PostgreSQL SERIALIZABLE (SSI): Uses non-blocking SIREAD predicate locks to detect rw-antidependency cycles and abort one conflicting writer with SQLSTATE 40001, which the app retries with bounded exponential backoff + jitter.
PostgreSQL SSI vs. Parent Lock

MVCC Snapshot + SIREAD Predicate Locks / Parent Row Lock

Tx A & Tx B (5-20 RPS/proj)Retry on SQLSTATE 40001Postgres 16 MVCC / SSISIREAD predicate / parent lockprojects (Parent Row)Per-project…allocations (Child…Invariant SUM(gpus) <=…

1.No Gap Locks in PG: FOR UPDATE on child rows does not block new INSERTs in Postgres (unlike InnoDB Next-Key locks).

2.Parent-Row Lock: Locking projects.id serializes only that project without blocking 10,000 others.

3.SSI (SQLSTATE 40001): Detects write-skew rw-cycles without blocking readers; app retries 40001 with jitter.

Locking the parent row or using SERIALIZABLE with 40001 retries enforces multi-row invariants under MVCC.

-- Option A: Parent-row lock serializes quota checks per project (works in READ COMMITTED)
BEGIN;
SELECT gpu_quota FROM projects WHERE id = $1 FOR UPDATE;
SELECT COALESCE(SUM(gpus), 0) FROM allocations WHERE project_id = $1;
-- Verify sum + new_gpus <= 16, then INSERT INTO allocations ...
COMMIT;

-- Option B: PostgreSQL SERIALIZABLE (SSI) with retry loop on SQLSTATE 40001
BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT COALESCE(SUM(gpus), 0) FROM allocations WHERE project_id = $1;
INSERT INTO allocations (project_id, gpus) VALUES ($1, $2);
COMMIT; -- Aborts one concurrent writer with 40001 if write skew detected
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where isolation-level guarantees protect business invariants.

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

Understanding MVCC vs. locking isolation prevents subtle financial and quota bugs:

  • Cloud Quota & Seat-Limit Enforcement: Prevents over-allocating GPUs, licenses, or shift slots.
  • Double-Entry Ledgers & Balances: Uses parent-account FOR UPDATE or SERIALIZABLE to prevent negative balances.
  • Booking & Inventory Systems: Avoids double-booking overlapping time slots via EXCLUDE USING gist or SSI.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does `SELECT ... FROM allocations WHERE project_id = $1 FOR UPDATE` fail to prevent concurrent quota over-allocation in PostgreSQL?

Recommended Learning Flow