← All Concepts
Distributed Systems
Two-Phase Commit (2PC)
A distributed protocol that ensures all participants in a transaction either commit or abort together. Provides atomicity across multiple nodes.
**2PC** coordinates a distributed transaction across multiple nodes to achieve atomic commit.
**Phase 1 — Prepare (Voting):**
1. Coordinator sends PREPARE to all participants
2. Each participant executes the transaction locally (but doesn't commit)
3. Each participant responds YES (can commit) or NO (abort)
**Phase 2 — Commit/Abort (Decision):**
4. If ALL vote YES → Coordinator sends COMMIT to all
5. If ANY votes NO → Coordinator sends ABORT to all
6. Participants execute the decision and acknowledge
**Failure scenarios:**
- **Participant fails before voting**: Coordinator times out → ABORT
- **Participant fails after voting YES**: Must recover and check coordinator
- **Coordinator fails**: Participants are BLOCKED until coordinator recovers (this is the main weakness)
**Improvements:**
- **3PC**: Adds a pre-commit phase to reduce blocking (rarely used in practice)
- **Saga pattern**: Breaks transaction into compensatable steps (preferred in microservices)
**Used by**: MySQL (XA transactions), PostgreSQL (PREPARE TRANSACTION), distributed databases.
Common Use Cases
- Cross-database transactions in distributed systems
- Financial transfers between accounts on different nodes
- Distributed lock acquisition across services
- Schema migrations across sharded databases
Advantages
- +Guarantees atomicity across all participants
- +Well-understood protocol with formal proofs
- +Supported by most databases (XA standard)
- +Ensures data consistency
Disadvantages
- -Blocking protocol — if coordinator fails, all participants wait
- -High latency — two round trips minimum
- -Locks held during prepare phase reduce throughput
- -Not partition tolerant — network split can cause inconsistency