Skip to content

19 · Two-Phase Commit (2PC) — Coordinated Atomic Commit

Distributed Transactions · Topic 19 of 20


The Problem

How do you atomically commit a transaction that spans multiple independent databases or services?

Either ALL participants commit, or ALL abort — the classic distributed atomicity problem.


Two-Phase Commit Protocol

A coordinator orchestrates all participants through two phases:

Phase 1 — Prepare (Voting)

Coordinator asks all participants: "Can you commit?"

Each participant: - Writes changes to WAL - Acquires locks - Replies VOTE-COMMIT or VOTE-ABORT

Phase 2 — Commit (Decision)

  • If ALL voted COMMIT → coordinator sends COMMIT to all
  • If ANY voted ABORT → coordinator sends ABORT to all
sequenceDiagram
    Coordinator->>P1: PREPARE
    Coordinator->>P2: PREPARE
    P1-->>Coordinator: VOTE-COMMIT
    P2-->>Coordinator: VOTE-COMMIT
    Coordinator->>P1: COMMIT
    Coordinator->>P2: COMMIT
    P1-->>Coordinator: ACK
    P2-->>Coordinator: ACK

Problems with 2PC

Problem Description
Blocking If coordinator crashes after PREPARE but before COMMIT, participants hold locks indefinitely
Single point of failure Coordinator failure stalls the entire transaction
Latency Two round trips across the network for every distributed transaction

3PC (Three-Phase Commit)

Adds a PRE-COMMIT phase to avoid blocking — but still vulnerable to network partitions.


Cloud Implementations

  • Uses Paxos + 2PC internally for cross-shard transactions
  • TrueTime API provides global timestamps to eliminate ambiguity
  • Fully managed — developers don't write 2PC code
  • Managed 2PC internally across partition groups
  • Up to 100 items per transaction
  • PREPARE TRANSACTION 'txid' → Phase 1
  • COMMIT PREPARED 'txid' → Phase 2
  • Used by external coordinators (XA protocol, pgbouncer)
  • No cross-partition 2PC
  • Lightweight transactions (Paxos) for single-partition compare-and-swap only
  • For long-running workflows, 2PC's blocking is unacceptable
  • See Saga Pattern for the preferred microservices alternative