Transactions and isolation levels

Topic 5 of 10 in Week 3: Databases12 min readIntermediateFree course

Overview

When money moves from one account to another, both the debit and the credit must happen, or neither. When two people buy the last ticket at once, only one should get it. Transactions and isolation levels are how databases keep data correct under failures and concurrency. They come up in any design involving payments, inventory or bookings.

ACID

A transaction is a group of reads and writes treated as one unit:

SQL
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;

Relational databases promise ACID:

  • Atomicity: all of it happens or none of it does. A crash halfway rolls everything back.
  • Consistency: the transaction moves data from one valid state to another, respecting constraints (no negative balances if a constraint says so).
  • Isolation: concurrent transactions don’t see each other’s half-finished work, to a degree set by the isolation level.
  • Durability: once committed, the change survives crashes (thanks to the write-ahead log).

What goes wrong under concurrency

When transactions overlap, several anomalies are possible:

  • Dirty read: reading another transaction’s uncommitted change, which may be rolled back.
  • Non-repeatable read: reading the same row twice in one transaction and getting different values because someone committed in between.
  • Phantom: running the same query twice and getting a different set of rows because rows were inserted or deleted.
  • Lost update: two transactions read a value, both modify it and the second write silently overwrites the first.
  • Write skew: two transactions read overlapping data, each makes a decision based on it and writes different rows, together breaking a rule. Classic example: two on-call doctors each check “is someone else on call?”, see yes, and both go off call.

Isolation levels

Isolation levels and what they prevent. Read uncommitted allows dirty reads, non-repeatable reads, phantoms and write skew. Read committed prevents dirty reads only. Repeatable read or snapshot isolation also prevents non-repeatable reads; whether it prevents phantoms depends on the database; write skew is still possible. Serializable prevents all of them. Below, a lost update: T1 reads stock 5, T2 reads stock 5, T1 writes 4, T2 writes 4, so two items are sold but stock should be 3. Fixes: an atomic update such as UPDATE SET stock = stock minus 1 WHERE stock > 0; locking the row with SELECT FOR UPDATE; or an optimistic check such as UPDATE WHERE version = 7, retrying if no rows changed.

  • Read committed: the default in PostgreSQL, Oracle and SQL Server. You never see uncommitted data, but values can change between your reads.
  • Repeatable read / snapshot isolation: your transaction sees a consistent snapshot as of its start. The default in MySQL InnoDB. Most implementations use MVCC (multi-version concurrency control): writers create new row versions, so readers don’t block writers.
  • Serializable: the result is as if transactions ran one at a time. Implementations use locking or detect conflicts and abort one transaction, which the application must retry.

Stronger levels mean more blocking or more aborted transactions. Many systems run at read committed and fix the specific risky operations explicitly.

Practical fixes for races

Most real bugs are read-modify-write races. Three standard tools:

  1. Atomic updates: let the database do the arithmetic in one statement.

    SQL
    UPDATE products SET stock = stock - 1 WHERE id = 42 AND stock > 0;

    Check the number of affected rows: 0 means sold out.

  2. Pessimistic locking: lock the row while you decide.

    SQL
    SELECT stock FROM products WHERE id = 42 FOR UPDATE;

    Other transactions wait. Simple and safe, but long-held locks hurt throughput and can deadlock.

  3. Optimistic locking: add a version column; update only if it hasn’t changed.

    SQL
    UPDATE products SET stock = 4, version = 8 WHERE id = 42 AND version = 7;

    If no row was updated, someone else won: reload and retry. Great when conflicts are rare.

Unique constraints are another underrated tool: a unique index on (event_id, seat_number) makes double-booking a seat impossible, whatever the application code does.

Transactions at scale

Single-database transactions are fast and reliable. Things get harder when data is split:

  • Across shards: a transaction touching two shards needs a distributed protocol such as two-phase commit, which is slower and can block if the coordinator fails. Some databases (Spanner, CockroachDB, YugabyteDB) do this for you, at a latency cost.
  • Across services: each service owns its database, so there’s no shared transaction. Systems use sagas (a sequence of local transactions with compensating actions) and the outbox pattern, covered in week 5.

A good design keeps data that must change together in the same database, or on the same shard, whenever possible.

In an interview

Whenever a design involves counting down something limited (stock, seats, balance) or moving money, say how you prevent races: “Seats are decremented with a conditional atomic update, and a unique constraint on (event, seat) guarantees no double booking.” It’s one of the clearest signals of depth.

Recap

Transactions make groups of operations atomic, consistent, isolated and durable. Concurrency causes anomalies from dirty reads to write skew, and isolation levels trade protection for throughput. In practice, use atomic updates, row locks, optimistic version checks and unique constraints to protect critical operations, and keep data that must change together in one database where possible.

Exercise

Don't oversell the last seat

A booking service runs this code for each request: (1) SELECT seats_left FROM events WHERE id = 7; (2) if seats_left >= requested, INSERT a booking and UPDATE events SET seats_left = seats_left_read_in_step_1 - requested. Two users each try to book the last 2 seats at the same moment under READ COMMITTED isolation. Explain what can go wrong, then give two different correct fixes.

Text
What goes wrong:

Fix 1:

Fix 2:

Summary

  • A transaction groups operations so they all succeed or all fail: atomicity, consistency, isolation and durability (ACID).
  • Concurrent transactions can cause dirty reads, non-repeatable reads, phantoms, lost updates and write skew.
  • Isolation levels trade safety for concurrency: read committed is a common default; serializable prevents all anomalies.
  • Fix read-modify-write races with atomic updates, row locks (SELECT … FOR UPDATE) or optimistic version checks.
  • Transactions across services or shards are hard; later lessons cover sagas and the outbox pattern.