Data · L1Transactions and isolation levels

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.

L1 Must-knowData13 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 21 Oct 2026 · How we check content
Senior at work · lesson 5 of 26
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

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.

Section 2 of 8

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

Section 3 of 8

How it works

Step through the T-shirt bug. Two orders, A and B, buy one shirt each.

A lost update: two transactions read 10 and both write 9 Order A stock row Order B stock = 10 read stock10 read stock10 write 9commitstock = 9 write 9commitstock = 92 sold: stock should be 8 ✓ SET stock = stock - 1 → 8✓ or SELECT … FOR UPDATE → B waits SeniorPath
  1. Stock is 10. Order A starts a transaction and reads the stock row. It gets 10.
  2. At the same moment, Order B starts its own transaction and reads the same row. It also gets 10.
  3. Order A works out 10 − 1 = 9 in the app code. It writes 9 and commits.
  4. 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.
  5. 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.
Step 1 of 5

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

Section 4 of 8

Trade-offs

LevelStops 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.
SerializableYes 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.

Section 5 of 8

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 + 1 over 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.
Section 6 of 8

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.
Section 7 of 8

Check yourself

1. What is the default isolation level in PostgreSQL?

Show answer

Read committed The Postgres docs say Read Committed is the default.

2. Two requests run SELECT balance, add ₹100 in app code, then UPDATE ... SET balance = <new value>. What can go wrong under Read Committed?

Show answer

A lost update. One of the two deposits disappears. Both read the same old value, and the second write overwrites the first. Read Committed does not stop this.

3. Two doctors are on call. Each checks "at least 2 on call", then removes only themselves. Both commit, and nobody is on call. What is this?

Show answer

Write skew They read the same data but wrote different rows. Only Serializable stops it in general.

4. Your service runs at Serializable in Postgres. What must the code do?

Show answer

Catch serialization failures and retry the whole transaction. Postgres aborts one transaction when it finds a conflict. The app must retry it from the start.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 5 sources and related lessons
  1. Martin Kleppmann, Designing Data-Intensive Applications (O'Reilly)
    1st edition (2017): chapter 7, Transactions (ACID, weak isolation levels, lost updates, write skew, serializability).
  2. PostgreSQL documentation: Transaction Isolation (opens in a new tab)
    The default level, what each level allows in Postgres, and the errors you must retry.
  3. PostgreSQL documentation: Explicit Locking (Row-Level Locks) (opens in a new tab)
    What SELECT … FOR UPDATE locks, and who has to wait.
  4. 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.
  5. 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.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper