The Two-Phase Commit (2PC) protocol is an atomic commit protocol for distributed systems, ensuring that all participants either commit or rollback a transaction in unison.

The Protocol Phases

Phase 1: Voting (Prepare)

  1. The Coordinator sends a PREPARE message to all participants.
  2. Each Participant executes the local transaction, acquires necessary locks, and writes a "Prepare" record to its Write-Ahead Log (WAL).
  3. Participants respond with VOTE_COMMIT or VOTE_ABORT.

Phase 2: Completion (Commit/Abort)

  1. If all participants voted COMMIT, the Coordinator writes a "Global Commit" record and sends COMMIT to all nodes.
  2. If any participant voted ABORT (or timed out), the Coordinator sends ROLLBACK to all nodes.
  3. Participants release locks and acknowledge completion.

Failure Modes and the "Blocking" Problem

The primary weakness of 2PC is that it is a blocking protocol.

Comparison: 2PC vs. 3PC vs. Consensus

Metric2PC3PC (Three-Phase Commit)Paxos / Raft
AtomicityGuaranteedGuaranteed (mostly)Guaranteed
BlockingYes (on Coord failure)No (uses Pre-Commit)No
Network Rounds233+
Partition TolerancePoorPoorHigh (Quorum-based)
Typical UseXA Transactions, Java EEAcademic / SpecializedDistributed DBs (Spanner, Cockroach)

Implementation Risks

Modern Alternatives

Due to the blocking nature of 2PC, modern distributed architectures prefer:

  1. SagaPattern: Replaces atomicity with eventual consistency and compensating transactions.
  2. OutboxPattern: Atomically links a local DB write with a message emission to a queue.
  3. Deterministic Execution: (e.g., FaunaDB, Calvin) Pre-orders transactions to eliminate the need for an interactive commit protocol.