FullStack AI Hub
Studio
System Design · 03. Data & Storage
12 min
10 steps
Intermediate

Transactions & ACID

Prevent double-spends, dirty reads, lost updates, and write skew using MVCC snapshots and isolation levels.

System Design03. Data & StorageLesson 5 of 11
12 minIntermediate10 steps

Transactions & ACID

Prevent double-spends, dirty reads, lost updates, and write skew using MVCC snapshots and isolation levels.

FINAL BALANCE
-$60 (bug!)
INTEGRITY
Broken
TX LATENCY
18 ms
RACE WINDOWS
Wide open
READ 100 → WRITE 20READ 100 → WRITE 20Tab 1 (-$80)reads $100Tab 2 (-$80)reads $100Unprotected Ledger72%balance = -$60!
TX write / lock
snapshot read
clean commit
lock wait / retry
race / anomaly
In This LessonStep 1 of 10
What You Will Master
  • ✓Enforce atomic all-or-nothing multi-row updates with WAL rollback when crashes strike mid-transfer
  • ✓Explain how Multi-Version Concurrency Control (MVCC) lets readers never block writers and writers never block readers
  • ✓Eliminate lost-update race conditions using atomic increments, `SELECT FOR UPDATE`, or Optimistic Locking
  • ✓Recognize subtle Write Skew under Snapshot Isolation and stop it with Serializable (SSI) or row locks

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Read Committed (Postgres Default)Standard CRUD apps where preventing dirty reads and dirty writes is sufficientStill vulnerable to non-repeatable reads, lost updates, and write skew
Snapshot Isolation / Repeatable Read (MVCC)Consistent multi-query reports, backups, and read-heavy dashboards without blocking writersAllows Write Skew when two transactions read overlapping conditions and write disjoint rows
Optimistic Concurrency (`version = v`)Low-contention edits (profiles, carts) where holding DB row locks across user think time is badHigh contention causes frequent CAS retry storms on hot rows
Serializable (SSI / `FOR UPDATE`)Bank transfers, seat booking, on-call schedules, and inventory invariants where zero anomalies are allowedAdds lock waits or serialization aborts requiring client retry logic

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Transactions & ACID.

STEP 01 · PROBLEMJump to step →

Without transactions: the $100 double-spend race

Alice has **$100** in her wallet. She taps **Pay $80** twice in 5 milliseconds from two tabs. Without transaction isolation, both API workers read `balance = 100`, both see `100 >= 80`, and both subtract `$80`.

Worse, if the server crashes *after* debiting Alice and *before* crediting Bob, **$80 vanishes into thin air**.

watch:Read-Modify-Write in application memory without database locking or transactions is a guaranteed financial bug under concurrent traffic.

Double SpendRead-Modify-Write RacePartial Failure
STEP 02 · SOLUTIONJump to step →

Atomicity & Durability: all-or-nothing with WAL rollback

Wrap the debit and credit in **`BEGIN; UPDATE alice -80; UPDATE bob +80; COMMIT;`**. **Atomicity** guarantees that either *both* rows commit together or *neither* does.

If the database crashes right after debiting Alice before reaching `COMMIT`, startup recovery reads the **WAL**, sees no `COMMIT` marker, and cleanly rolls back Alice’s debit.

idea:Atomicity in ACID isn’t about concurrency—it’s about fault tolerance: turning multi-step crashes into clean all-or-nothing rollbacks.

AtomicityDurabilityAbort & Rollback
STEP 03 · TECHNIQUEJump to step →

Read Committed: stop dirty reads & dirty writes

The baseline isolation level in PostgreSQL and Oracle is **Read Committed**. It guarantees two things: you never read another transaction’s uncommitted changes (**no Dirty Reads**) and two writers never overwrite each other’s uncommitted row (**no Dirty Writes**).

However, if a reporting query reads Alice’s balance, then a transfer commits, and the report reads Bob’s balance 10 ms later, the report sees a **skewed sum** (non-repeatable read).

idea:Read Committed is fast and stops dirty reads, but each statement inside a transaction sees a fresh committed state—so multi-query reads can disagree.

Read CommittedDirty ReadsNon-Repeatable Reads
STEP 04 · SOLUTIONJump to step →

MVCC Snapshot Isolation: readers never block writers

How can an audit report read a frozen consistent point-in-time snapshot **without locking the entire bank**? Through **Multi-Version Concurrency Control (MVCC)**.

Every row stores hidden `xmin` (created-by TX) and `xmax` (deleted-by TX) version tags. When the audit opens at `txid = 105`, it sees only row versions committed `<= 105` while writers freely append `txid = 106` concurrently!

idea:MVCC’s golden rule: readers never block writers, and writers never block readers—every transaction reads from its own consistent version snapshot.

MVCC (xmin / xmax)Snapshot IsolationZero Reader Locks
STEP 05 · TECHNIQUEJump to step →

Preventing Lost Updates: Atomic SQL, Pessimistic & Optimistic Locks

When two workers update the *same* inventory counter (`stock = stock - 1`), choose one of three proven guards: **(1) Atomic SQL** (`UPDATE items SET stock = stock - 1 WHERE id = 9 AND stock > 0`), **(2) Pessimistic Row Lock** (`SELECT ... FOR UPDATE`), or **(3) Optimistic Locking (CAS)** (`WHERE version = 4`).

Use **Optimistic Locking** when contention is low (user profiles); switch to **`FOR UPDATE`** or atomic SQL on hot SKUs so transactions queue cleanly instead of thrashing on retries.

idea:Never load a counter into app RAM, add 1, and `UPDATE SET count = 42`—push atomic increments into SQL or guard with `WHERE version = old_version`.

Atomic SQL UpdateSELECT FOR UPDATEOptimistic Locking (CAS)
STEP 06 · PROBLEMJump to step →

The subtle bug MVCC misses: Write Skew

Snapshot Isolation sounds bulletproof—until **Write Skew** strikes! A hospital requires **at least 1 doctor on call** at all times. Both Alice and Bob are on call (`count = 2`).

At the exact same millisecond, Alice and Bob both click *"Go Off-Call."* Under Snapshot Isolation, both read `count = 2`, then Alice updates **Alice’s row** and Bob updates **Bob’s row**. Because they wrote *different* rows, both commits succeed—leaving **0 doctors on call**!

watch:Write Skew happens when two transactions read the same invariant (`count >= 2`) and mutate *different* rows—Snapshot Isolation only detects conflicts on the *same* row.

Write SkewPhantom ReadsSnapshot Isolation Limit
STEP 07 · SOLUTIONJump to step →

Stop Write Skew: Serializable Snapshot Isolation (SSI)

Switch the critical shift-change transaction to **`ISOLATION LEVEL SERIALIZABLE`**. Modern Postgres uses **Serializable Snapshot Isolation (SSI)**—it stays optimistic (no heavy table locks!) while tracking **SIREAD predicate locks**.

When Alice commits, SSI detects that Bob’s read predicate (`WHERE shift_id = 9 AND on_call = true`) became stale, **aborts Bob with SQLSTATE `40001`**, and Bob’s client retries—seeing `count = 1` and safely rejecting the drop.

idea:Serializable (SSI) guarantees transactions behave as if executed one by one—just remember your app MUST catch `40001` serialization errors and retry cleanly.

Serializable (SSI)SIREAD Predicate Tracking40001 Retry Loop
STEP 08 · TRADE-OFFJump to step →

Deadlocks: how inconsistent lock ordering freezes transfers

TX 1 transfers **Alice → Bob** (locks Alice, waits for Bob). Simultaneously, TX 2 transfers **Bob → Alice** (locks Bob, waits for Alice). Neither can ever proceed—a classic **Deadlock**.

Databases detect deadlocks after ~1 second and kill one victim, wasting latency. The permanent engineering fix is trivial: **always acquire row locks in deterministic sorted ID order** (`min(id)` first, then `max(id)`).

idea:Sorting lock keys (`ORDER BY account_id ASC` before `FOR UPDATE`) mathematically makes lock-wait cycles impossible—zero deadlocks forever.

Deadlock DetectionConsistent Lock OrderingLock Timeout
STEP 09 · TRADE-OFFJump to step →

Operational trap: never hold a DB transaction open over HTTP

One classic outage pattern: opening `BEGIN`, calling a slow 3-second external **Stripe HTTP API**, and then calling `COMMIT`.

A long-lived open transaction holds both **row locks** and an **MVCC snapshot horizon**—blocking `VACUUM` from reclaiming dead tuples and rapidly exhausting your 100-connection DB pool!

watch:Rule of iron: never make external network calls (Stripe, email, webhooks) inside an open SQL transaction. Commit fast, then use an Outbox or async worker.

Connection Pool ExhaustionMVCC Bloat / VACUUMTransactional Outbox
STEP 10 · RECAPJump to step →

Recap: choosing the right isolation level per workflow

Isolation levels trade **concurrency performance** against **subtle race anomalies**. Know which bug each level eliminates so you neither under-protect money nor over-lock harmless reads.

Use **Read Committed** for routine CRUD, **MVCC Snapshot** for reports, **Atomic SQL / Optimistic CAS** for counters, **Serializable (SSI)** for cross-row invariants, and keep every transaction **short and sorted**.

idea:Interview cheat code: explain MVCC ("readers don’t block writers"), distinguish Lost Updates from Write Skew, and mention `40001` retries + short transactions.

ACIDMVCCLost Update vs Write SkewSerializable SSI

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.