0% completed
MVCC and Isolation Levels in Practice
On This Page
Part 1: The Booking Service
Part 2: How Readers and Writers Avoid Waiting
Part 3: The Cost of Old Versions
Part 4: Lost Updates
Part 5: The Isolation Levels
Part 6: Write Skew, the Anomaly That Survives
Part 7: Choosing What Your Workload Can Accept
Part 8: Using This in an Interview
Common Mistakes
Key Takeaways
A service that books meeting rooms wrote these four lines to its log within 23 milliseconds.
10:15:02.110 Ana check Room 4, 2:00 to 3:00 no overlap found
10:15:02.114 Ben check Room 4, 2:00 to 3:00 no overlap found
10:15:02.130 Ana insert booking committed
10:15:02.133 Ben insert booking committed
Each request checked for a conflict before it saved, and the database reported no error to either one. At 2 o'clock, two teams arrive at one room. The cause is the way a database runs many transactions at once. The rest of the lesson shows how Postgres lets readers and writers avoid waiting for each other, and which errors each isolation level still allows.
Part 1: The Booking Service
The running example is the service from the log above. Three of its operations matter in this lesson:
- A booking saves a new row, after checking that no other booking overlaps it.
- An allowance update subtracts the booked hours from the team's monthly allowance.
- A nightly report reads every booking and allowance of the month. It runs for about ten minutes while bookings continue.
Each operation runs as a transaction. Two terms describe one:
- A transaction is a group of reads and writes that take effect together or not at all.
- To commit a transaction is to make its changes final and visible to other transactions.
All numbers in this lesson are made-up examples. Part 2 starts with the report, because it reads for ten minutes while bookings keep writing.
Part 2: How Readers and Writers Avoid Waiting
The report must not stop bookings, and it must not see a half-saved booking. One way to protect it is a lock. A lock is a mark on a row that makes other transactions wait until it is released. If the report locked every row it read, bookings would wait for it for ten minutes.
Postgres uses multi-version concurrency control, or MVCC, instead. With MVCC, an update does not overwrite a row. It writes a new version of the row, and the old version stays on disk for a while.
Readers then choose between versions with a snapshot. A snapshot is a view of the database as of one moment: every transaction committed by then, and nothing later. Each read uses the version that was current in its snapshot. The report keeps one snapshot until it ends, using a level that Part 5 describes. The diagram below shows one allowance row while the report runs.
Step 1: The report starts at minute 0 and takes its snapshot. The design team has 10 hours left.
Step 2: A booking commits at minute 3. It writes a new version with 8 hours. The old version is marked as replaced, but it stays.
Step 3: The report reads the row at minute 8. The new version committed after its snapshot, so the report reads 10.
Notice that neither transaction waited. Readers do not block writers, and writers do not block readers. Two writers to the same row still wait for each other.
Part 3: The Cost of Old Versions
Part 2 said the old version stays on disk for a while. Something has to remove it later, and two terms describe that work:
- A dead version is one that no running transaction can still see.
- Vacuum is the Postgres process that frees the space of dead versions. A background worker called autovacuum runs it.
Vacuum may remove a version only when no open transaction might still need it. Suppose a bug leaves one transaction open for days. That one transaction holds back vacuum across the whole database.
Dead versions then pile up, and tables and indexes keep growing. This growth is called bloat. Each query then reads more pages to find the same live rows.
For this reason, when a table gets slower week after week while traffic stays the same, look for something building up. Check first for a transaction left open. Many teams also set a timeout that ends sessions left idle inside a transaction.
Part 4: Lost Updates
MVCC keeps readers and writers apart, but two writers can still produce a wrong result. An anomaly is a wrong result caused only by two transactions overlapping, when each one would be correct alone.
The allowance update shows the first anomaly. It reads the team's hours, subtracts 2 in its own code, and writes the result back. This pattern is called read-modify-write. If two bookings arrive at once, both read 10 and both write 8. The team used 4 hours, but the record shows only 2.
This is a lost update: one write silently replaced the other, because the application held the old value. There are three standard fixes.
Fix 1: Let the database do the subtraction. Send one statement that sets the hours to the hours minus 2. At read committed, the default level that Part 5 describes, the second writer waits for the first to commit. It then reads the row again and subtracts from the new value, so 10 becomes 8 and then 6.
Fix 2: Lock the row when you read it. A read with FOR UPDATE locks the row, so the second booking waits until the first commits. This fix suits logic too complex for one statement.
Fix 3: Raise the isolation level. At repeatable read, Postgres notices that the row changed after the second transaction's snapshot. It rejects that transaction with a serialization failure, and the application must retry it.
Part 5: The Isolation Levels
Fixes 1 and 3 both named a level. An isolation level is a setting that says which anomalies the database prevents. Higher levels prevent more, at the cost of more waiting or more retries.
Three more anomalies complete the list:
- A dirty read is reading another transaction's change before it commits.
- In a non-repeatable read, one transaction reads a row twice and gets two values, because another transaction committed in between.
- In a phantom read, one query run twice in a transaction returns different rows, because another transaction added or removed a matching row.
Postgres offers these levels.
- Read committed is the default. Each statement gets a fresh snapshot.
- Repeatable read uses one snapshot for the whole transaction, a design called snapshot isolation. The nightly report from Part 2 runs at this level. In Postgres, it also prevents phantom reads, which the SQL standard and some other databases allow at this level.
- Serializable gives the result of running the transactions one at a time, in some order. Postgres watches for dangerous patterns of reads and writes, and aborts one transaction when it finds one.
- Read uncommitted is accepted as a name, but Postgres treats it as read committed. No Postgres level allows dirty reads.
The diagram below shows which anomalies each level allows in Postgres.
Notice the last column. Write skew is allowed at read committed and at repeatable read, and only serializable prevents it. Part 6 explains this anomaly.
Part 6: Write Skew, the Anomaly That Survives
Repeatable read still allows one anomaly, and it is the double booking that opened this lesson. The diagram below shows Ana's and Ben's transactions side by side.
Step 1: Ana's transaction checks Room 4 from 2 to 3 o'clock. It finds no overlapping booking.
Step 2: Ben's transaction runs the same check at the same moment. Ana has not committed, so Ben also finds none.
Step 3: Each one inserts its own booking, as a different new row.
Step 4: Both commit. Room 4 now has two bookings for the same hour.
This anomaly is called write skew. Two transactions read an overlapping set of rows, and then each writes a different row based on what it read. Together they break a rule that each one kept alone.
Notice the line at the bottom of the diagram. No row was written twice, so repeatable read has nothing to reject. It rejects a transaction only when a row that it writes changed after its snapshot.
The same shape appears whenever a rule covers more than one row. Suppose at least one engineer must stay on call. Two engineers can each see the other on call and both sign off at once.
There are three fixes.
- A constraint. An exclusion constraint is a table rule that no two rows may overlap in a stated way, here in room and time. The database then refuses Ben's insert, at any isolation level.
- A lock on a shared row. Each booking first locks the room's own row with
FOR UPDATE, so Ben waits for Ana. At read committed, Ben's check then runs after the wait and sees her booking. Locking the overlapping bookings would not work, because none exist yet. - Serializable, with retries. Postgres sees that each check would have found the other's new row, and aborts one transaction. The retry sees the other booking and refuses.
Part 7: Choosing What Your Workload Can Accept
Parts 4 to 6 showed that each protection has a cost. For this reason, no single level is right for a whole service. The table below matches each operation of the booking service to the anomaly it risks.
| Operation | Anomaly it risks | Can it accept it? | Choice |
|---|---|---|---|
| Room list on the home screen | Slightly old data | Yes | Read committed |
| Nightly report | Statements from different moments | No, totals must agree | Repeatable read |
| Allowance update | Lost update | No | The database does the subtraction |
| Room booking | Write skew | No | An exclusion constraint |
Most of the service stays at the default. Serializable everywhere would also be correct, but any transaction could then need a retry.
Part 8: Using This in an Interview
The interviewer often points at a write and asks what happens when two users do it at once. Name the anomaly, the protection, and its cost.
"Two bookings could both find the room free and both insert. That is write skew, which repeatable read does not stop, because each transaction writes a different row. I'd add an exclusion constraint on the room and time range. Most of the service stays at read committed."
Expect two follow-up questions. "Why not make everything serializable?" Name the cost of retries on every path. "Why does this table get slower every week?" Name dead versions, vacuum, and a transaction left open.
Common Mistakes
Mistake 1: Assuming the default level prevents every race. Read committed allows lost updates and write skew.
Mistake 2: Raising the level to repeatable read to protect a rule that spans rows. Write skew survives it, because each transaction writes a different row.
Mistake 3: Choosing serializable without retry code. The application must retry an aborted transaction, or the user sees an error.
Key Takeaways
- MVCC keeps old row versions, so readers and writers do not block each other. Each read uses a snapshot of one moment.
- Old versions cost space until vacuum removes them. A transaction left open blocks vacuum, so a table slows with no change in traffic.
- A lost update needs the application to hold the old value. Let the database do the arithmetic, or lock the row first.
- Write skew survives repeatable read. Stop it with a constraint, a lock on a shared row, or serializable with retries.
- In a system design interview, name the anomaly each write risks, and add protection only where it would break a rule.
The next lesson, Replication: Lag, Failover, and Split-Brain, shows what changes when the same data is kept on more than one machine.
Reading Progress
0%
On This Page
Part 1: The Booking Service
Part 2: How Readers and Writers Avoid Waiting
Part 3: The Cost of Old Versions
Part 4: Lost Updates
Part 5: The Isolation Levels
Part 6: Write Skew, the Anomaly That Survives
Part 7: Choosing What Your Workload Can Accept
Part 8: Using This in an Interview
Common Mistakes
Key Takeaways