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.1 What is a transaction?
3 min read+10 XP
Transactions
On the train: A ticket isn't "a seat" plus "a payment" done separately. If the payment fails, you don't keep the seat. If the seat is gone, you aren't charged. It's one deal.
In the system: A transaction is a group of database operations that succeed or fail as one unit:
sql
If anything fails in between (a constraint, a crash, a deliberate ROLLBACK), the database undoes the whole group. You never end up with a sold seat and no payment, or the reverse.
Two practical rules:
- Keep transactions short. A transaction holds locks (17.6) until it ends. Never wait for a user, an email or a slow external API inside one.
- Be ready to retry. The database may abort a transaction because of a conflict or deadlock (17.8). Well-written code retries the whole transaction.
Memory code: "Seat and payment, together or not at all."