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.
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.
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:
- Phantom Reads (
READ COMMITTED): ConcurrentINSERTs committed by Tx B appear mid-transaction in Tx A. - Write Skew (
REPEATABLE READ): PostgreSQL's Snapshot Isolation eliminates phantoms for queries, but two concurrentINSERTs see the same pre-insertSUMand both commit, violating the 16-GPU or 3-on-call-engineer cap.
PostgreSQL REPEATABLE READ Allows Both Quota Inserts to Commit
PostgreSQL REPEATABLE READ prevents phantoms, but only SERIALIZABLE (SSI) or parent-row FOR UPDATE prevents write skew.
- 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.
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?
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 ...
Why SELECT ... FOR UPDATE on child rows fails in PostgreSQL
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 singleprojectsrow (WHERE id = $1 FOR UPDATE) before queryingSUM(gpus)and inserting. Contention is scoped per-project (5–20 RPS), leaving the other9,999projects lock-free. - PostgreSQL
SERIALIZABLE(SSI): Uses non-blockingSIREADpredicate locks to detectrw-antidependency cycles and abort one conflicting writer withSQLSTATE 40001, which the app retries with bounded exponential backoff + jitter.
MVCC Snapshot + SIREAD Predicate Locks / Parent Row Lock
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
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 UPDATEorSERIALIZABLEto prevent negative balances. - Booking & Inventory Systems: Avoids double-booking overlapping time slots via
EXCLUDE USING gistor SSI.
Practice: Make the trade-off yourself.
Why does `SELECT ... FROM allocations WHERE project_id = $1 FOR UPDATE` fail to prevent concurrent quota over-allocation in PostgreSQL?