Module 5 · Distributed systemsLesson 55 of 887 minAdvanced
Two-phase commit
Two-phase commit makes several databases commit or abort together, by asking everyone to promise first.
Play "All say yes", then "One says no". Finally play "Coordinator crashes" and notice what the participants are stuck holding.
Two-phase commit (2PC) is the classic protocol for an atomic transaction across several databases or resources.
The two phases
Phase 1, prepare
- A coordinator sends
prepareto every participant. - Each participant does the work, writes it durably, locks what it touched, and votes:
- yes: "I can commit, and I promise not to back out."
- no: "I can't."
Phase 2, commit or abort
- If all voted yes, the coordinator writes "commit" to its own log and tells everyone to commit.
- If any voted no (or didn't answer), it tells everyone to abort.
- Participants apply the decision and release their locks.
The blocking problem
A participant that voted yes has given up its right to decide. If the coordinator crashes before sending the decision, the participant must wait, holding locks, possibly for a long time. Other transactions needing those rows wait too.
Coordinators recover by reading their log on restart, and some systems replicate the coordinator with consensus to shrink the window. But the cost remains:
- Latency: at least two round trips to every participant, plus durable writes.
- Availability: any slow or unreachable participant stalls everyone.
Where it's used
- Inside distributed databases: Spanner, CockroachDB and others use 2PC between shards, with each participant made highly available by consensus.
- XA transactions between a database and a message broker in older enterprise systems.
Between independent microservices it's rarely used; sagas are the usual choice.