Transactions and isolation levels
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:
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
- 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:
-
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.
-
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.
-
Optimistic locking: add a
versioncolumn; 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.
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.
What goes wrong:
Fix 1:
Fix 2:What goes wrong: a lost update. Both transactions read seats_left = 2, both pass the
check, both insert a booking and both write seats_left = 0. Four seats are sold
though only two existed. READ COMMITTED doesn't stop two transactions from reading the
same value before either writes.
Fix 1 - atomic conditional update (simplest):
UPDATE events SET seats_left = seats_left - 2
WHERE id = 7 AND seats_left >= 2;
If it updated 1 row, insert the booking in the same transaction; if 0 rows, sold out.
The database applies the two updates one after the other, so only one succeeds.
Fix 2 - pessimistic locking:
SELECT seats_left FROM events WHERE id = 7 FOR UPDATE;
The second transaction waits until the first commits, then sees seats_left = 0.
(Also valid: optimistic locking with a version column and retry, or SERIALIZABLE
isolation with retry on serialization failure.)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.