Course contentsShow
← Software Engineering
Lesson 1415 of 1,93341. Scalability and Distributed SystemsFree lesson

Two-Phase Commit (2PC)

How 2PC coordinates transactions across multiple nodes with a prepare and commit phase.

Two-Phase Commit (2PC)

You'll learn how 2PC ensures all-or-nothing transaction outcomes across multiple independent nodes in a distributed system.

What Is Two-Phase Commit?

Two-Phase Commit is a distributed consensus protocol that coordinates transactions spanning multiple databases or services. It ensures that either all participating nodes commit a transaction, or all abort it—no partial updates.

Think of it like planning a group vacation: everyone must agree to book flights and hotels together, or no one books anything. You can't have half the group committed and half backing out.

How 2PC Works

The protocol involves a coordinator (transaction manager) and multiple participants (individual databases or services).

Phase 1: Prepare Phase

The coordinator asks each participant: "Can you commit this transaction?"

Each participant:

  • Prepares the transaction (locks resources, validates constraints)
  • Writes to a transaction log
  • Responds with "YES" (ready to commit) or "NO" (cannot commit)

If any participant votes "NO" or times out, the transaction fails.

Phase 2: Commit Phase

If all participants vote "YES," the coordinator sends a "COMMIT" command to everyone. Each participant then:

  • Commits the transaction permanently
  • Releases locks
  • Acknowledges completion

If any participant voted "NO," the coordinator sends "ABORT" instead, and everyone rolls back.

The Problem with 2PC

2PC is a blocking protocol. If the coordinator crashes after the prepare phase, participants are stuck waiting—they've locked resources but don't know whether to commit or abort. This violates availability during network partitions (remember the CAP theorem).

Key Takeaway: Two-Phase Commit guarantees atomic transactions across multiple nodes using prepare-then-commit phases, but it sacrifices availability by blocking participants until the coordinator decides, making it a CP (consistency-focused) approach that struggles with network partitions.