17. Transactions and Locking
1
The picture to keep in your head2
17.1 What is a transaction?3
17.2 What does ACID mean in depth?4
17.3 What is a lost update?5
17.4 What can a transaction see that it shouldn't?6
17.5 What are isolation levels?7
17.6 What is pessimistic locking?8
17.7 What is optimistic locking?9
17.8 What is a deadlock?10
17.9 What are distributed locks, and why are they tricky?11
17.10 What is two-phase commit?12
17.11 What is a saga?13
17.12 How do seat holds with expiry work?14
Memory card and where the analogy breaks15
Practice: five levels16
Interview questions17
Solutions18
Sources19
Code lab17. Transactions and Locking
Memory card and where the analogy breaks
3 min read+10 XP
The memory card (tear this page out)
| # | Question | Memory code |
|---|---|---|
| 17.1 | Transaction? | Seat and payment, together or not at all |
| 17.2 | ACID in depth? | Whole, legal, private, permanent |
| 17.3 | Lost update? | Don't read, think and write back; let the database subtract |
| 17.4 | Read anomalies? | Unfinished, changed, or newly appeared: three ways to read a lie |
| 17.5 | Isolation levels? | The stronger the isolation, the more it's like one clerk at a time, and the more you wait or retry |
| 17.6 | Pessimistic locking? | Hand on the seat before you sit |
| 17.7 | Optimistic locking? | Check it's still free as you sit |
| 17.8 | Deadlocks? | Grab seats in the same order and nobody waits in a circle |
| 17.9 | Distributed locks? | A lock that can expire can be held twice, so number every holder |
| 17.10 | 2PC? | Everyone says "ready", then everyone says "done"; one "no" cancels all |
| 17.11 | Sagas? | Do it step by step, and keep an undo for every step |
| 17.12 | Seat holds? | Hold it, pay for it, or lose it |
The whole chapter in one line: All or nothing inside one database, a hand or a last-moment check on every contested seat, and step-by-step with undo across services.
Where the analogy breaks
- Two passengers arguing is visible. Two transactions overwriting each other is silent: a lost update leaves no error, just wrong numbers.
- A clerk can't be in two places. A transaction can be retried, aborted or replayed, so every step must be safe to run more than once.
- A refund feels like an undo. Some actions can't be undone at all (a sent email, a shipped parcel), which is why sagas put them last.
Quick check
Five questions on this chapter. Pick an answer, then check it.
quiz