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.7 What is optimistic locking?
3 min read+10 XP
On the train: No hand on the seat. You fill in the form, and just before printing, the clerk checks: "is seat 14 still exactly as it was when you started?" If someone took it, you start again.
In the system: Optimistic locking takes no lock. It reads a version (a counter or timestamp) with the row, and makes the write conditional on the version being unchanged:
sql
In the chapter's code, Asha books the last seat; Ravi's write, carrying the old version, is rejected, and his retry sees zero left.
- No waiting, no locks held, which suits web apps where a user may take minutes between reading and saving (editing a profile, a document).
- Costs: under heavy contention (thousands chasing 100 seats), most attempts fail and retry, wasting work. There, pessimistic locks, atomic updates or a queue (Chapter 43) do better.
Many ORMs support this directly with a version column.
Memory code: "Check it's still free as you sit."