Theory
Two-Phase Commit (2PC): Distributed Atomicity
📋 Overview
Two-Phase Commit (2PC) is a distributed consensus protocol used to ensure that a transaction is committed across multiple nodes atomically. It ensures "All or Nothing" semantics (ACID) in a distributed environment, where either every node commits the change or no node does.
🏗️ Core Principles & Characteristics
- The Roles:
- Coordinator: Orchestrates the transaction.
- Participants: The databases or services that must perform the work.
- The Phases:
- Prepare Phase (Voting): The coordinator asks everyone, "Can you commit?" Participants lock resources and vote YES or NO.
- Commit Phase (Execution): If everyone said YES, the coordinator tells everyone to COMMIT. If anyone said NO, everyone is told to ABORT/ROLLBACK.
- The Log: The coordinator keeps a persistent "Transaction Log" so it can recover the state if it crashes mid-transaction.
⚖️ Trade-offs: Pros & Cons
Pros
- Strong Consistency: Guarantees that the system never enters an inconsistent state.
- Atomic Semantics: Simplifies application logic by making distributed operations look like local ones.
Cons
- Blocking Protocol: If the coordinator crashes after Phase 1, participants are stuck with locked resources, unable to move forward (The Blocking Problem).
- Latency: Requires multiple network round-trips and synchronous disk writes, significantly slowing down performance.
- SPOF (Single Point of Failure): The coordinator is a critical bottleneck and failure point.
- Scalability Limit: The failure of a single node causes the entire transaction to fail, making it unsuitable for high-scale internet systems.
🌍 Real-World Implementation
- Relational Databases: Used internally by databases like MySQL or Oracle when performing "XA Transactions" across multiple data files or shards.
- Distributed DBs (Google Spanner): Uses a highly optimized version of 2PC combined with Paxos to minimize the blocking problem.
- Legacy Enterprise Systems: Often used in Java/J2EE applications talking to a DB and a Message Broker (JMS) simultaneously.
💡 Interview "Gotchas" & Tips
- 2PC vs. Saga Pattern: This is the most important comparison. Explain that 2PC is for Strong Consistency (high cost), while Saga is for Eventual Consistency (low cost, high scale).
- The Blocking Problem: Be ready to explain what happens if the coordinator dies. The nodes don't know the outcome and must wait, potentially causing a system-wide "hang."
- 3PC (Three-Phase Commit): Mention that 3PC exists to solve the blocking problem by adding an extra "Pre-Commit" phase, but it's rarely used due to even higher network overhead.
📐 Suggested Architecture Primitives
- XA Standard: The classic interface for distributed transactions.
- Coordinator Log: Persistent storage to ensure recovery.
- Distributed Consensus (Paxos/Raft): Modern systems use these instead of simple 2PC to elect a reliable coordinator.
Canvas