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.10 What is two-phase commit?
3 min read+10 XP
Across services
On the train: A journey needs a seat from the train company, a meal from the caterer and a payment from the bank. A coordinator phones each: "Can you commit?" Only if all say yes does it phone again: "Commit." If any says no, it tells everyone "cancel".
In the system: Two-phase commit (2PC) makes one transaction span several databases or services:
- Prepare: the coordinator asks every participant to get ready. Each does the work, writes it durably, locks what it needs, and votes yes (promising it can commit) or no.
- Commit or abort: if every vote is yes, the coordinator tells all to commit; otherwise, all abort.
It's all-or-nothing across systems, and standards like XA support it.
The problems:
- Blocking: a participant that voted yes must wait, holding its locks, until it hears the decision. If the coordinator crashes at that moment, participants can be stuck until it recovers.
- Slow: at least two rounds of messages to every participant, with locks held throughout.
- Everyone must support it, which many services and message brokers don't.
So 2PC is used inside some distributed databases and between a few tightly controlled systems, but rarely between independent microservices.
Memory code: "Everyone says 'ready', then everyone says 'done'; one 'no' cancels all."