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
17.8 What is a deadlock?
3 min read+10 XP
On the train: Clerk A holds seat 14 and wants seat 15 (a couple booking together). Clerk B holds seat 15 and wants seat 14. Each waits for the other. Forever.
In the system: A deadlock is a cycle of transactions each waiting for a lock another holds.
Figure: the database breaks the cycle by aborting one transaction; you prevent most cycles by locking in a fixed order.
What the database does: it keeps a wait-for graph, spots the cycle (the chapter's code does this with a simple loop), aborts one transaction (the victim) with a deadlock error, and lets the other continue.
What you do:
- Lock in a consistent order: always lock the lower seat number first. If everyone locks 14 before 15, the cycle can't form.
- Keep transactions short, so locks are held briefly.
- Lock what you need up front where possible, instead of adding locks gradually.
- Retry the victim. Deadlocks under load are normal; unhandled deadlock errors are bugs.
Memory code: "Grab seats in the same order and nobody waits in a circle."