Two-phase commit on a whiteboard

The clean path, the crash that blocks it, and what 3PC tries. Press Next to step through it.

Turn your phone sideways for a bigger board.

→ or Space: next · ←: back

One transaction, two nodes

A transaction touches two nodes. Either both commit or neither does. A coordinator drives the protocol; the nodes are participants.

Read the whole walkthrough as text
  1. One transaction, two nodes

    A transaction touches two nodes. Either both commit or neither does. A coordinator drives the protocol; the nodes are participants.

    Open: the “The Protocol” section

  2. Phase 1: PREPARE

    The coordinator sends PREPARE to every participant.

    Open: the “The Protocol” section

  3. Participants get ready

    Each participant writes the transaction to a durable log and acquires the locks it needs. From here on it can commit if asked.

    Open: the “The Protocol” section

  4. Everyone votes YES

    Each participant replies YES, ready to commit. A participant that hit a problem would reply NO.

    Open: the “The Protocol” section

  5. Phase 2: COMMIT

    All votes were YES, so the coordinator sends COMMIT. Each participant commits and releases its locks. Every node ends in the same state.

    Open: the “The Protocol” section

  6. If anyone says NO

    A single NO changes the decision: the coordinator sends ABORT to everyone, and every participant aborts and releases its locks.

    Open: the “The Protocol” section

  7. The coordinator crashes

    Run it again, but crash the coordinator after phase 1 and before phase 2. Both participants voted YES and are holding their locks.

    Open: the “The Fatal Flaw” section

  8. Stuck in both directions

    Committing might be wrong if another participant said NO. Aborting might be wrong if COMMIT was about to arrive. So they wait, locks held, until the coordinator recovers. That is the blocking problem.

    Open: the “The Fatal Flaw” section

  9. The attempted fix: 3PC

    Three-phase commit adds PRE-COMMIT between the two. A participant that received it knows the coordinator saw every YES, so it can commit alone if the coordinator disappears. It costs an extra round of messages and still has edge cases under network partitions.

    Open: the “The Attempted Fix: 3PC” section

  10. What systems do instead

    Most large systems avoid 2PC for anything user-facing. Sagas use compensating transactions, consensus protocols like Paxos and Raft give strong guarantees at more complexity, and optimistic concurrency detects conflicts at commit time.

    Open: the “What Systems Actually Do” section

  11. Recap

    2PC gives you distributed atomicity, and you pay for it with availability when the coordinator fails. The other approaches are different points on that curve.

    Open: the “What Systems Actually Do” section