Two-Phase Commit (2PC) Protocol
Understand the Two-Phase Commit protocol, its role in distributed ACID transactions, and why it's largely replaced by Saga in microservices.
srikanthtelkalapally888@gmail.com
Two-Phase Commit (2PC) Protocol
2PC is a distributed algorithm that ensures all participants in a distributed transaction either all commit or all abort.
The Problem
Distributed transaction spanning multiple databases:
Transfer $100: DB1 (debit) + DB2 (credit)
If DB1 succeeds but DB2 fails → inconsistent state.
2PC Phases
Phase 1 — Prepare
Coordinator asks all participants: "Can you commit?"
Coordinator → DB1: Prepare
Coordinator → DB2: Prepare
DB1 → Coordinator: Yes (locks resources)
DB2 → Coordinator: Yes (locks resources)
Phase 2 — Commit
If ALL say Yes, coordinator sends Commit. If ANY says No, coordinator sends Abort.
Coordinator → DB1: Commit
Coordinator → DB2: Commit
Problems with 2PC
Blocking
Participants hold locks until coordinator decides. Coordinator crash = participants blocked indefinitely.
Single Point of Failure
Coordinator is critical. If it crashes between phases, system is stuck.
Performance
Two network round trips for every transaction.
3PC — Three-Phase Commit
Adds a "pre-commit" phase to reduce blocking, but still not fault-tolerant.
Modern Alternative: Saga
2PC: All-or-nothing, synchronous, blocking
Saga: Eventual consistency, async, non-blocking
Most microservices use Saga pattern instead of 2PC.
Where 2PC Is Still Used
- Traditional RDBMS with XA transactions
- Google Spanner (uses Paxos-based variant)
- Financial systems with strict ACID requirements
Conclusion
2PC guarantees strong consistency but at the cost of availability and performance. Modern distributed systems prefer Saga for flexibility.