Transactions, ACID and Isolation

Group changes atomically and understand what each isolation level does and does not protect you from.

Intermediate · about 8 hours · difficulty 4/5

Learn first: Writing SQL Queries

A transaction groups several statements so they succeed or fail together. Transferring money is the textbook case: debit one account and credit another, or do neither.

ACID

  • Atomicity: all or nothing. On error you ROLLBACK.
  • Consistency: constraints hold before and after.
  • Isolation: concurrent transactions do not see each other's half-finished work (to a configurable degree).
  • Durability: once committed, data survives a crash (thanks to the write-ahead log).

Isolation levels and anomalies

Concurrency causes anomalies: dirty reads (seeing uncommitted data), non-repeatable reads (a row changes between two reads), phantoms (new rows appear in a range) and lost updates / write skew.

  • Read Committed (PostgreSQL default): no dirty reads, but other anomalies possible.
  • Repeatable Read: a stable snapshot for the whole transaction.
  • Serializable: behaves as if transactions ran one after another; the database may abort one, so you must retry.

Practical tools

  • SELECT ... FOR UPDATE locks rows you intend to change.
  • Atomic updates like UPDATE stock SET qty = qty - 1 WHERE id = $1 AND qty > 0 avoid read-modify-write races.
  • Optimistic locking with a version column detects conflicting edits.

Pitfalls

  • Holding a transaction open while calling an external API. Locks are held the whole time.
  • Assuming the default level prevents double-booking. It usually does not.

You are ready to move on when you can reproduce a lost update with two concurrent sessions and then fix it two different ways.

Key concepts

  • BEGIN, COMMIT, ROLLBACK
  • ACID properties
  • Isolation levels
  • Read anomalies and write skew
  • Row locks and SELECT FOR UPDATE
  • Optimistic locking
  • MVCC internals
  • Retrying serialization failures

Mini project

Build a seat-booking endpoint, write a script that fires 50 concurrent booking requests for the last seat, prove overbooking happens, then fix it with row locks or an atomic conditional update.

Check yourself

Two requests read stock = 1 and both decrement it. Which isolation level or query pattern prevents this in PostgreSQL?

Free resources