Write Skew and Phantom Reads
The race that snapshot isolation lets through: two transactions check the same rule, write different rows, and break the rule together. How phantoms cause it and the four ways to stop it.
Overview
The check-then-write pattern
Many business rules are checked the same way: read some rows, decide whether the action is allowed, then write. Under snapshot isolation two transactions can run this pattern at once, both see the rule satisfied, both write, and the rule breaks. This is write skew.
It slips through because the two transactions write different rows. Snapshot isolation only notices two writes to the same row, so nothing conflicts.
Every write skew has the same shape, in three steps.
- Read the rows that the rule depends on.
- Decide whether the rule still holds.
- Write a row that changes the answer.
Each transaction's check is true on its own snapshot. When two run at once, their combined writes make it false, and the rule is broken.
The pattern turns up wherever a rule spans more than one row. Three everyday cases show it.
- Linked checking and savings accounts: the rule is that together they stay at or above zero. Each transaction checks the total, then withdraws from a different account.
- Hotel room booking: the rule is that no two stays overlap for one room. Each transaction checks that the dates are free, then inserts its own booking.
- Choosing a username: the rule is that names are unique. Each transaction checks that the name is free, then inserts it.
Key concepts
- Write skew
- Lost update
- Phantom
- SELECT ... FOR UPDATE
- Materializing conflicts
- Exclusion constraint
- Index-range lock
Interview questions
- How do you prevent double booking in a reservation system under concurrent load?
- What is the difference between a lost update and write skew?
- Why does SELECT ... FOR UPDATE fix some write skews but not others?
- How does serializable isolation catch write skew in PostgreSQL?
Sign up free to read the full topic
More DDIA topics
Start free on Cariara · Coding problems · System design studio