Course contentsShow
← Databases & SQL
Lesson 1687 of 1,95316. Distributed Data ArchitecturesFree lesson

Two-Phase Commit (2PC) Protocol

Trace the lifecycle of a distributed transaction to ensure atomicity across heterogeneous nodes.

In this lesson, you will learn how the Two-Phase Commit (2PC) protocol acts as a foundational mechanism to ensure atomicity across heterogeneous distributed nodes.

The Distributed Atomicity Challenge

When a transaction spans multiple databases, we face the "atomic commit problem": either all nodes commit the transaction, or none do. If one node fails after another has already committed, the system enters an inconsistent state. 2PC solves this by introducing a central Transaction Coordinator (TC) that orchestrates the decision-making process through two distinct phases.

Phase 1: The Voting Phase (Prepare)

The TC sends a PREPARE message to all participating nodes (the cohorts). Each cohort performs the transaction locally—writing to its Undo/Redo logs—but does not finalize the commit. Instead, each node votes:

  • Yes: The node promises it can commit (it has persisted the data to stable storage).
  • No: The node encountered an error (e.g., constraint violation or lock timeout) and aborts.

Phase 2: The Decision Phase (Commit)

The TC collects all votes. If all participants voted "Yes," the TC writes a commit record to its log and sends a COMMIT message to all cohorts. If even one participant votes "No" or fails to respond within a timeout, the TC sends an ABORT message.

-- Conceptual flow of a 2PC transaction across nodes:
-- Coordinator initiates:
PREPARE_TRANSACTION(transaction_id);

-- Cohorts respond:
IF ALL_NODES_ACK(PREPARE) THEN
    SEND(COMMIT, transaction_id);
ELSE
    SEND(ROLLBACK, transaction_id);
END IF;

Critical Considerations

The strength of 2PC lies in its ability to force atomicity. However, it is a blocking protocol. If the TC crashes after sending PREPARE but before sending the final decision, participants are left in a state of uncertainty, holding locks on rows and potentially blocking other transactions. This dependency makes 2PC sensitive to the availability of the Coordinator. While it guarantees strong consistency, it essentially requires all participants to be online and responsive, which can impact the latency of your distributed architecture.

Key Takeaway: 2PC ensures atomicity by decoupling the execution of a transaction from its finalization, requiring a unanimous agreement from all participating nodes before any node permanently commits the state change.