Transactions and isolation levels
Your code is correct when it runs alone. Isolation levels decide what happens when it runs twice at the same moment.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
A small shop sells concert T-shirts. The stock for size M is 10. A popular singer posts a link, and orders arrive many per second.
The order code looks fine. It reads the stock, checks that it is above zero, works out stock minus one, and saves the new number. Each order runs inside a database transaction. Every test passes.
After the sale, the warehouse counts the shirts. The database says 4 left, but the shelf is empty. The shop has sold 6 shirts it does not have. Now someone must email 6 customers and refund them.
The code was correct for one order at a time. It was not correct for two orders at the same moment. Wrapping it in a transaction did not help, because of the isolation level.
The idea in simple words
A transaction groups several reads and writes into one unit. The database makes four promises about it, called ACID. 1
- Atomicity: all or nothing. If anything fails halfway, the database undoes the whole group.
- Consistency: your rules, like "stock is never negative", still hold at the end. This one is mostly your job, not the database's.
- Isolation: transactions running at the same time should not get in each other's way.
- Durability: once the database says "committed", the data survives a crash.
The surprise is in the "I". Full isolation is slow, so databases offer weaker isolation levels. Most apps run at a weak level without knowing it.
The key idea. A transaction is not a lock. At the default level in Postgres and MySQL, two transactions can both read a value, both change it, and one change can vanish. 5
How it works
Step through the T-shirt bug. Two orders, A and B, buy one shirt each.
- Stock is 10. Order A starts a transaction and reads the stock row. It gets 10.
- At the same moment, Order B starts its own transaction and reads the same row. It also gets 10.
- Order A works out 10 − 1 = 9 in the app code. It writes 9 and commits.
- Order B also works out 9, writes it and commits. It overwrites A's write. Two items were sold, but stock says 9. One update is lost.
- Fixes: let the database do the math in one atomic UPDATE, or lock the row with SELECT … FOR UPDATE so B waits and then reads 9. In Postgres, Repeatable Read or Serializable would instead make B's write fail, and the app retries B.
This is a lost update: two transactions read, change and write the same value, and the second write wipes out the first. 1
The levels, from weak to strong
Read committed. You never see data that another transaction has not committed yet. That rules out the dirty read. But each statement sees the newest committed data. So two reads in one transaction can return different answers. This is the Postgres default. 2
Snapshot isolation (called Repeatable Read in Postgres). The transaction reads from one snapshot of the database, taken at its first statement. It does not see changes that others commit later. 2
How does the database keep old and new versions at once? With MVCC. It keeps several versions of a row. Readers see the version that fits their snapshot, and writers add a new version. Readers and writers do not block each other. 1
Serializable. The result must be the same as if the transactions had run one after another. Postgres builds this on top of snapshots. It watches for dangerous patterns and aborts one transaction when it finds one. 2
What the defaults really do
Names differ between databases, so check what your database does, not what the level is called.
- Postgres defaults to Read Committed. A lost update can happen here. 2 5
- In Postgres Repeatable Read, order B's write fails. It gets "could not serialize access due to concurrent update", and the app must retry the whole transaction. 2
- MySQL InnoDB defaults to REPEATABLE READ. Plain reads use a snapshot from the first read. 4 But Hermitage's tests found that this level does not prevent lost updates when you read with a plain SELECT. 5
- At Serializable, both databases prevent lost updates and write skew. 5
Three ways to fix a lost update
1. Atomic update. Let the database do the math in one statement:
UPDATE products SET stock = stock - 1
WHERE id = 42 AND stock > 0;If no row changed, the shirt is sold out. In Read Committed, Postgres makes the second update wait. Then it checks the WHERE clause again on the new row. 2 This is the simplest fix, and you should use it whenever the change fits in one statement.
2. Lock the row. Read with SELECT … FOR UPDATE. Other transactions that try to lock or change the row wait until you commit or roll back. 3 In Read Committed, the waiting transaction then gets the new value, 9, not 10. 2 Use this when the logic is too complex for one statement.
3. Stronger isolation. Use Repeatable Read or Serializable in Postgres, and retry when the database aborts a transaction. Every caller must handle the retry.
Write skew: the harder bug
Some bugs are not about one row. A hospital rule says at least one doctor must be on call. Two doctors are on call, and both feel ill at the same time. 1
Each doctor's transaction checks: "Are at least 2 on call? Yes." Then each removes only their own row. No row is written twice, so no lock and no snapshot check fires. Both commit. Now nobody is on call.
This is write skew. Repeatable Read does not stop it, in Postgres or in MySQL. Serializable does. 5 You can also lock the rows you read with FOR UPDATE, so the second doctor waits and then sees only one on call. 1
Trade-offs
| Level | Stops lost update? | Stops write skew? | Cost |
|---|---|---|---|
| Read committed (Postgres default) | No Use atomic updates or FOR UPDATE. | No | Cheapest. Few aborts. |
| Repeatable read, Postgres (snapshot) | Yes One transaction fails and must retry. | No | The app must retry on errors. |
| Repeatable read, MySQL (default) | No , Hermitage says. | No | Cheap. But it does not catch the conflict for you. |
| Serializable | Yes | Yes | More aborts and retries under contention. In MySQL, plain reads take shared locks when autocommit is off. 4 |
Simple rule: keep the default level. Make every read-change-write either one atomic statement or a FOR UPDATE read. Use Serializable for rules that span several rows, like the on-call check.
At work: how a senior uses this
- In code review, look for this shape: read a value, change it in app code, write it back. Ask: "What if two requests do this at once?"
- Know your database's default level, and write it in the service README. Don't assume "repeatable read" means the same thing in MySQL and Postgres.
- Prefer
SET x = x + 1over reading and writing the value in app code. - Turn business rules into constraints when you can:
UNIQUE,CHECK (stock >= 0). The database then enforces them for every caller. - If you use Repeatable Read or Serializable, wrap transactions in a retry helper. Postgres marks these failures with the error code (SQLSTATE)
40001. 2 - Keep transactions short. Never wait for a user or a slow network call while holding a row lock.
- Write a concurrency test. Run the same request 50 times in parallel and check the final count.
With AI
What to ask the agent
"Find every place in this service that reads a row, changes a value in code, and writes it back. For each, tell me if two requests at once can lose an update."
"Rewrite this stock decrement as one atomic UPDATE with a stock > 0 check. Return whether a row was updated."
"Write a test that runs 20 parallel orders against a real Postgres with stock 10. Assert that exactly 10 succeed and stock ends at 0."
What to check yourself
- The test uses a real database with real parallel connections. Mocks and an in-memory map cannot show a lost update.
- The fix runs inside the same transaction as the rest of the order. A lock taken in one transaction and used in another protects nothing.
- Any retry repeats the whole transaction, not just the last statement.
- The agent did not "fix" it with a lock in app memory. That breaks as soon as you run two servers.
- Locks are taken in the same order everywhere, so two transactions don't wait for each other forever.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 5 sources and related lessons
- Martin Kleppmann, Designing Data-Intensive Applications (O'Reilly)
1st edition (2017): chapter 7, Transactions (ACID, weak isolation levels, lost updates, write skew, serializability). - PostgreSQL documentation: Transaction Isolation (opens in a new tab)
The default level, what each level allows in Postgres, and the errors you must retry. - PostgreSQL documentation: Explicit Locking (Row-Level Locks) (opens in a new tab)
What SELECT … FOR UPDATE locks, and who has to wait. - MySQL 8.4 Reference Manual: Transaction Isolation Levels (InnoDB) (opens in a new tab)
The InnoDB default level, how its snapshots work, and how locking reads differ. - Martin Kleppmann, Hermitage: testing transaction isolation levels (GitHub) (opens in a new tab)
A table of which anomalies each database's levels really prevent, tested by hand.
Related: Locking and MVCC in practice · PostgreSQL in depth · Replication · Money and double-entry ledgers
Before this: Replication, which adds stale reads on top of these bugs. Next on this line: Concurrency control in practice. Across machines: Distributed transactions and two-phase commit.