Library
LearnDatabasesChapter 04
7 min read

Isolation levels

Two people press "Book" on the last seat of a tatkal train at the same instant. Both requests read the seat as available. Both write a booking. Both see a confirmation. One passenger turns up at the station with a ticket for a seat that is already taken.

Every statement in that story ran inside a transaction, and the transactions were atomic and durable. What failed was isolation: how much two transactions running at the same time are allowed to affect each other. Databases do not give you full isolation by default, because it is expensive, and most of the bugs in this chapter come from not knowing that.

Your answer

Two transactions each read a balance of 1,000, then one adds 500 and the other subtracts 200, each writing back what it calculated. What is the final balance, and what should it be?

What can go wrong#

Each of these has a name, and interviewers use the names.

Dirty read. You read a change another transaction has made but not committed. If it rolls back, you acted on data that never existed.

Non-repeatable read. You read a row twice in the same transaction and get two different answers, because someone committed a change in between.

Phantom read. You run the same query twice, SELECT count(*) FROM bookings WHERE seat = 'S4-32', and new rows have appeared, because someone inserted them in between.

Lost update. Two transactions read the same value, both compute a new value from it, and both write. The second write silently overwrites the first. This is the question at the top, and it is the one that costs money.

Write skew. Two transactions each check a condition, each change a different row, and together break the condition. The classic example: a hospital rule that at least one doctor must be on call. Two doctors on call both ask to go off at once, each sees the other still on call, and both are approved.

Here is the lost update, step by step.

1/6 A wants to add a 500 refund. It reads the current balance into application code.