Transactions, ACID and Concurrency Control

Understand ACID, isolation levels and the anomalies they prevent, serializability, locking protocols, MVCC and crash recovery.

Intermediate · about 7 hours · difficulty 4/5

Learn first: SQL for Interviews, Concurrency and Synchronization

A transaction is a group of operations that must succeed or fail together, like moving money between accounts. This topic connects OS synchronization to databases and is asked by almost every product company.

ACID

  • Atomicity: all or nothing, implemented with undo logs.
  • Consistency: constraints hold before and after.
  • Isolation: concurrent transactions behave as if run one at a time (to a configurable degree).
  • Durability: committed data survives crashes, via the write-ahead log (WAL).

Anomalies and isolation levels

  • Dirty read: reading uncommitted data.
  • Non-repeatable read: the same row returns different values within one transaction.
  • Phantom read: a repeated range query returns new rows.
  • Lost update: two read-modify-write cycles overwrite each other.
  • Levels: Read Uncommitted, Read Committed (PostgreSQL default), Repeatable Read (MySQL InnoDB default), Serializable. Be able to fill the table of which anomalies each level allows.

Concurrency control

  • Schedules and conflict serializability: build a precedence graph; a cycle means not serializable (another graph cycle problem).
  • Two-phase locking (2PL): a growing phase then a shrinking phase guarantees serializability; strict 2PL holds write locks until commit to avoid cascading aborts. Shared vs exclusive locks.
  • MVCC: readers see a snapshot and do not block writers. Used by PostgreSQL and InnoDB.
  • Optimistic vs pessimistic locking: version columns vs SELECT ... FOR UPDATE.
  • Deadlocks happen in databases too; the DB detects them and aborts a victim.

Recovery

Log-based recovery with undo and redo, checkpoints, and the idea behind ARIES (optional).

Good enough to move on: you can explain each ACID property with a bank transfer, map isolation levels to anomalies, and test a schedule for conflict serializability.

Key concepts

  • ACID properties
  • Dirty, non-repeatable and phantom reads
  • Isolation levels
  • Conflict serializability
  • Two-phase locking
  • MVCC
  • Optimistic vs pessimistic locking
  • Write-ahead logging and recovery
  • ARIES

Mini project

In PostgreSQL, open two psql sessions and reproduce a lost update, a non-repeatable read and a phantom read under different isolation levels, then fix a concurrent seat-booking script using SELECT FOR UPDATE and separately with an optimistic version column.

Check yourself

Which anomalies does Repeatable Read prevent that Read Committed does not, and what does Serializable add on top?

Free resources