Two-Phase Commit
How distributed systems achieve atomic transactions across multiple databases using the 2PC protocol.
Distributed Transaction Request
A client wants to perform a transaction across multiple databases: transfer $100 from Account A (Database 1) to Account B (Database 2), and log the transfer (Database 3).
A coordinator (Transaction Manager) orchestrates this across all participants (the databases).
- Single transaction spans multiple systems
- Coordinator manages the protocol
- Either ALL succeed or ALL fail (atomicity)
Phase 1: PREPARE - Can You Commit?
The coordinator sends a PREPARE request to each participant. Each participant must:
- Acquire necessary locks
- Write a prepare record to its log
- Determine if it CAN commit
The participant votes without actually committing yet.
- Resources are locked but not changed
- "Point of no return" — once you vote YES, you must be able to commit
Participants Vote: YES or NO
Each participant responds with its vote:
- YES: "I can commit if asked"
- NO: "Something prevents me from committing"
The coordinator waits for all votes. This is the vulnerability window — if the coordinator crashes now, participants are stuck waiting with locks held.
- Unanimous YES required for commit
- Single NO means abort
- Participants hold locks while waiting
Phase 2: COMMIT!
Since all participants voted YES, the coordinator:
- Writes "COMMIT" to its log (point of no return)
- Sends COMMIT to all participants
Participants MUST commit upon receiving this — they already promised they could.
- Coordinator logs decision before sending
- Participants are obligated to commit
- Recovery uses the commit log
All Participants Committed
Each participant commits, releases locks, and sends an ACK to the coordinator. The distributed transaction is now atomically complete — all databases are consistent.
If any ACK is lost, the coordinator will retry until confirmed.
- Atomicity achieved across multiple systems
- All or nothing guarantee
- Trade-off: availability and latency