Course contentsShow
← Databases & SQL
Lesson 808 of 1,9537. Transaction ManagementFree lesson

Two-Phase Commit Protocol Mechanics

Understand the prepare and commit phases required to synchronize multiple database nodes.

In this lesson, you will learn how the Two-Phase Commit (2PC) protocol acts as a "digital handshake" to ensure that multiple database nodes either all commit a transaction or all roll it back together.

The Problem of Distributed Transactions

When a single transaction spans across multiple database nodes, you face a synchronization nightmare: what if Node A successfully updates its data, but Node B crashes before it can do the same? To maintain transactional integrity, we need a coordinator to manage the consensus between nodes.

Phase 1: The Prepare Phase

The coordinator sends a PREPARE message to all involved nodes (the participants). Each participant performs the necessary operations—like acquiring locks and writing changes to their local Undo/Redo logs—but does not commit yet.

Crucially, each participant must ensure they are in a state where they can guarantee success. They reply with a VOTE_COMMIT if they are ready, or VOTE_ABORT if they encounter a conflict.

Phase 2: The Commit Phase

If—and only if—every participant sends a VOTE_COMMIT, the coordinator moves to the second phase:

  1. The coordinator logs the decision to commit to its own persistent storage.
  2. The coordinator sends a COMMIT command to every participant.
  3. Each participant finalizes the transaction, releases locks, and acknowledges the completion.

If any participant votes to abort, or if the coordinator doesn't receive a vote in time, the coordinator sends an ABORT command to everyone, ensuring the database remains in a consistent state across all nodes.

Simplified Logic

Think of it like a group of people trying to agree on a dinner location.

  • Phase 1: "Can everyone make it to the restaurant?" (Nodes verify they have the capacity).
  • Phase 2: "Everyone confirmed; let’s go." (Nodes execute the plan).
-- Conceptual Flow
-- 1. Coordinator: "PREPARE"
-- 2. Participants: "READY / CAN_COMMIT"
-- 3. Coordinator: "COMMIT"
-- 4. Participants: "ACKNOWLEDGE"

Because each node writes its "readiness" to its log during Phase 1, the system can recover even if a power loss occurs mid-protocol. Upon reboot, a node checks its log, sees it was in a "prepared" state, and asks the coordinator for the final verdict.

Key Takeaway: The Two-Phase Commit protocol guarantees atomicity across distributed systems by ensuring that all participating nodes reach a unanimous agreement before any local changes are made permanent.