100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What is Two-Phase Commit (2PC)?

Learn how two-phase commit works, why it guarantees atomicity, its blocking failure mode, and alternatives like sagas.

hardQ108 of 224 in System Design Est. time: 6 minsLast updated:
Open Code Lab
108 / 224

Expected Interview Answer

Two-phase commit (2PC) is a distributed transaction protocol where a coordinator asks every participant to vote on whether it can commit a transaction (the prepare phase), and only tells everyone to actually commit once all participants voted yes, otherwise it tells everyone to abort, guaranteeing atomicity across multiple databases or services.

In the prepare (voting) phase, the coordinator sends a prepare request to every participant, which does all the work needed to commit (writing to a durable log) and replies yes if it can guarantee commit, or no if it cannot. If every participant votes yes, the coordinator moves to the commit phase and tells all participants to make the change permanent; if any participant votes no, or times out, the coordinator tells everyone to abort instead. The protocol guarantees atomicity — either every participant commits or every participant aborts — but it is blocking: if the coordinator crashes after participants voted yes but before sending the commit decision, those participants must hold their locks and wait, since they cannot unilaterally decide to commit or abort. This makes 2PC unsuitable for highly available, latency-sensitive systems, which is why many distributed systems prefer eventual consistency with compensating transactions (the saga pattern) instead.

  • Guarantees strict atomicity across multiple independent databases or services
  • Simple, well-understood protocol with broad support (XA transactions)
  • Ensures no partial commits leave the system in an inconsistent state
  • Well suited for a small number of tightly coupled, short-lived transactions

AI Mentor Explanation

Two-phase commit is like a match umpire polling both team captains before confirming a result overturn: first each captain privately signals whether they agree to accept the review outcome (the prepare/vote phase), and only if both say yes does the umpire officially announce the change (the commit phase). If either captain objects, the umpire cancels the overturn entirely rather than applying it for one team and not the other. The danger is that if the umpire collapses after both captains agreed but before announcing anything, both teams are stuck waiting, unable to proceed on their own. That all-or-nothing, coordinator-blocking behavior is exactly how two-phase commit works.

Step-by-Step Explanation

  1. Step 1

    Coordinator sends prepare

    The coordinator asks every participant to do all commit-ready work and durably log it, then vote yes or no.

  2. Step 2

    Participants vote

    Each participant replies yes (it can guarantee commit) or no (it cannot), and yes-voters hold locks pending the final decision.

  3. Step 3

    Coordinator decides

    If all votes are yes, the coordinator decides commit; if any vote is no or times out, it decides abort.

  4. Step 4

    Coordinator broadcasts outcome

    The coordinator sends the final commit or abort decision to all participants, who apply it and release their locks.

What Interviewer Expects

  • Correctly describes the two distinct phases: prepare/vote and commit/abort
  • Explains the blocking problem if the coordinator crashes after votes but before the decision
  • Recognizes 2PC guarantees atomicity but sacrifices availability during coordinator failure
  • Can contrast 2PC with the saga pattern as an alternative for long-running distributed transactions

Common Mistakes

  • Describing 2PC as a single round-trip instead of two distinct phases
  • Not mentioning the blocking failure mode when the coordinator crashes mid-protocol
  • Confusing 2PC with optimistic concurrency control or simple retries
  • Assuming 2PC works well at large scale or high latency between participants

Best Answer (HR Friendly)

Two-phase commit is a way to make sure a transaction that touches multiple databases either fully happens everywhere or doesn’t happen at all. A coordinator first asks everyone involved if they’re ready to commit, and only if everyone says yes does it tell them to actually finalize the change; if anyone says no, it tells everyone to cancel instead, so the system never ends up half-updated.

Code Example

Simplified two-phase commit coordinator
class TwoPhaseCommitCoordinator:
    def __init__(self, participants):
        self.participants = participants

    def run_transaction(self, tx):
        # Phase 1: prepare/vote
        votes = []
        for p in self.participants:
            votes.append(p.prepare(tx))

        if all(votes):
            # Phase 2: commit
            for p in self.participants:
                p.commit(tx)
            return 'committed'
        else:
            # Phase 2: abort
            for p in self.participants:
                p.abort(tx)
            return 'aborted'

class Participant:
    def prepare(self, tx):
        # do the work, write to a durable log, return True/False
        ok = self.can_commit(tx)
        if ok:
            self.log_prepared(tx)
        return ok

    def commit(self, tx):
        self.apply(tx)
        self.release_locks(tx)

    def abort(self, tx):
        self.rollback(tx)
        self.release_locks(tx)

Follow-up Questions

  • What happens to participants if the coordinator crashes after they vote yes but before it sends the decision?
  • How does three-phase commit (3PC) attempt to fix the blocking problem in 2PC?
  • How does the saga pattern differ from two-phase commit for distributed transactions?
  • How would you implement a recovery coordinator that resumes an in-flight 2PC transaction after a crash?

MCQ Practice

1. What does the coordinator do if even one participant votes “no” during the prepare phase?

If any participant votes no (or times out), the coordinator must instruct all participants to abort, preserving atomicity.

2. What is the main drawback of two-phase commit compared to eventual-consistency approaches?

If the coordinator fails after participants vote yes but before broadcasting the decision, those participants are blocked holding locks until it recovers.

3. Which alternative pattern is commonly used instead of 2PC for long-running distributed transactions across microservices?

The saga pattern breaks a transaction into a series of local steps with compensating actions to undo prior steps, avoiding 2PC's blocking behavior.

Flash Cards

What are the two phases of 2PC?Prepare/vote phase, then commit/abort phase.

What is 2PC's biggest weakness?It is blocking — if the coordinator crashes after votes but before the decision, participants must wait.

What does a “yes” vote in the prepare phase mean?The participant has done all commit-ready work durably and guarantees it can commit if told to.

What alternative avoids 2PC's blocking problem for microservices?The saga pattern, using compensating transactions instead of a blocking coordinator.

1 / 4

Continue Learning