System design concepts · Data That Doesn't Break

Database Transactions and Isolation Levels Explained

Two users, one last seat, the same millisecond. Concurrency bugs are the ones that pass every test and then cost real money in production.

What you'll be able to explain
  • Explain ACID in practical terms
  • Recognise lost updates, dirty reads, non-repeatable reads, phantoms and write skew
  • Pick an isolation level knowingly
  • Choose between pessimistic locking, optimistic concurrency and atomic operations
  • Prevent double booking with database constraints

ACID without the jargon

  • Atomicity: all of the transaction happens, or none of it does.
  • Consistency: your invariants (constraints, balances ≥ 0) hold before and after.
  • Isolation: concurrent transactions don't see each other's half-finished work (to a degree set by the isolation level).
  • Durability: once committed, it survives crashes (write-ahead log, replication).

The anomalies

Anomaly What happens Example
Dirty read Read another transaction's uncommitted data See a balance that is later rolled back
Lost update Two read-modify-writes; one overwrites the other Two likes both read 10, both write 11
Non-repeatable read Same row read twice gives different values Price changes mid-checkout
Phantom Same query returns new rows on rerun "Seats available" count changes
Write skew Two transactions read overlapping data, write different rows, break an invariant Two doctors both go off call, leaving none
Txn ADatabaseTxn B1SELECT stock → 12SELECT stock → 13UPDATE stock = 0, create order4UPDATE stock = 0, create order5one item, two orders: oversold!
A lost update: both transactions read the same stock and both "succeed".

Isolation levels

Level Prevents Still allows Notes
Read uncommitted Almost nothing Dirty reads Rarely used
Read committed Dirty reads Lost updates, non-repeatable reads, phantoms Default in PostgreSQL
Repeatable read / snapshot + non-repeatable reads Write skew (in snapshot isolation) Default in MySQL InnoDB
Serializable Everything — Correct but slower; retries on conflict
Common trap

Assuming your database is serializable by default. Most default to read committed or snapshot isolation. A read-then-write in application code is a race unless you add locking or use an atomic operation.