- rtshkmr's digital garden/
- References/
- Architecture Design Basics/
- Pattern Taxonomy/
- Reliability, Consistency & Synchronisation/
- Two-Phase Commit (2PC)/
Two-Phase Commit (2PC)
Table of Contents
π΄ P0 — the classical distributed transaction protocol and why it’s limited
Problem #
A transaction spans multiple databases or services. All must commit or all must abort. How do you coordinate?
Mechanism #
Phase 1 (Prepare):
Coordinator β all participants: "Can you commit?"
Each participant: lock resources, respond YES or NO
Phase 2 (Commit/Abort):
If ALL said YES β Coordinator: "COMMIT"
If ANY said NO β Coordinator: "ABORT"
Participants execute and release locksWhy 2PC is Limited #
| Problem | Consequence |
|---|---|
| Coordinator is SPOF | If coordinator crashes after prepare, participants are stuck holding locks |
| Blocking protocol | Participants hold locks until coordinator decides β high contention |
| Latency | At least 2 round-trips; participants blocked during both |
| Availability | Any participant failure causes abort β availability decreases with more participants |
Why Not 3PC? #
Three-phase commit adds a “pre-commit” phase to avoid blocking. In practice, rarely used: doesn’t handle partitions correctly, adds latency, and Saga solves the real problem better.
Instinct #
2PC is fine for 2-3 participants within a single datacenter. Beyond that, the availability and latency costs are usually unacceptable. For cross-service transactions, use the Saga pattern instead β it trades atomicity for availability via compensating transactions. See also: Saga Pattern.
MISCONCEPTION: negative statement: “Most NoSQL databases don’t support distributed transactions.”
This was true in the early NoSQL era but is outdated. MongoDB, CockroachDB, YugabyteDB, and FoundationDB all now support distributed transactions (with performance tradeoffs). Systems like Cassandra and Redis Cluster still don’t support general cross-partition transactions. The modern accurate framing:
Early NoSQL systems generally avoided distributed transactions, but many modern distributed databases now support them, usually with performance tradeoffs. Support β free: it means “available but often discouraged for hot paths.”
References #
- Consensus Protocols: Two-Phase Commit β Henry Robinson
DDIA 2e Reference #
- Chapter 9: Distributed Transactions and Consensus