Two-Phase Commit (2PC) Protocol
What you'll learn: How 2PC ensures all-or-nothing atomicity across multiple distributed databases through a structured two-phase voting process.
The Core Problem
When a transaction spans multiple databases (distributed transaction), you need all participants to either commit or abort together—no partial success. The Two-Phase Commit protocol solves this by introducing a coordinator that orchestrates a voting process before finalizing the transaction.
How 2PC Works
Think of 2PC like planning a group dinner: everyone must confirm they can attend before you make the reservation.
Phase 1: Prepare (Voting)
The coordinator sends a "prepare" message to all participants (database nodes):
- Each participant checks if it can commit (locks acquired, constraints satisfied, etc.)
- Participants write redo/undo logs to durable storage
- Each responds with "yes" (vote to commit) or "no" (vote to abort)
Phase 2: Commit or Abort (Decision)
Based on votes, the coordinator decides:
- If all voted "yes": Coordinator sends "commit" to everyone. All participants commit and release locks.
- If any voted "no" (or timeout): Coordinator sends "abort" to everyone. All participants rollback.
The Coordinator's Role
The coordinator is the single point of decision. It must durably log the decision before Phase 2, ensuring recovery if it crashes. This role creates a blocking problem: if the coordinator fails after Phase 1, participants remain locked waiting for the final decision.
Atomicity Guarantee
2PC ensures atomicity because once all participants vote "yes," they're obligated to commit when instructed. The protocol prevents scenarios where some nodes commit while others abort.
Key Takeaway: Two-Phase Commit uses a prepare-then-commit voting protocol coordinated by a single node to guarantee atomicity across distributed participants, though it's vulnerable to blocking if the coordinator fails.