Two-Phase Commit: Why the Oldest Distributed Transaction Protocol Still Blocks

A payment is debited in the billing service, a shipment row is created in the warehouse database, and the ledger gets an entry. All three must happen together or none of them should. Inside a single database, that guarantee is a transaction — one commit, atomic, done. Across two or more independent systems, it is one of the hardest problems in distributed systems, and the classic answer is the two-phase commit protocol. It is also the answer engineers most love to hate, because it trades the error “some systems committed and some didn’t” for a subtler and stranger one: “everybody is waiting, indefinitely.”

This post walks through the mechanics of 2PC, why its blocking behavior is not a bug but the price of its guarantees, how real implementations recover from the crash scenarios, and where it fits in modern architectures.

The contract: one decision, everywhere

Two-phase commit involves one coordinator and any number of participants, each holding a resource — usually a local database — capable of durable local writes. The protocol’s job is narrow: ensure every participant arrives at the same commit-or-abort decision, and that once any of them acts on that decision, none can ever act differently. Atomicity across nodes is the whole product. Performance, availability, and lock hold times are, famously, not.

The two phases split the work cleanly. In the prepare (or voting) phase, the coordinator asks every participant whether it is able to commit. A participant that answers yes has first done everything needed to make either outcome possible later: it has written its changes durably to its own log, marked a “prepared” record, and acquired whatever it must hold to freeze the transaction’s state — typically the locks on the modified rows. From that moment it has surrendered control. It cannot commit, cannot abort, cannot release the locks. It simply waits for a decision.

In the commit phase, the coordinator collects the votes. If every participant voted yes, it makes the decision durable in its own log — this ordering is essential — and then tells everyone to commit. If any participant voted no, or timed out without answering, the coordinator decides to abort and tells everyone. Unanimity is required for commit; a single no is a global abort.

Why it blocks — and must

The protocol’s infamous flaw appears when the coordinator crashes after participants have voted yes but before the decision reaches all of them. Each participant that voted yes is now stuck in the in-doubt state. It cannot abort: the coordinator might have decided commit and already told another participant, in which case aborting breaks atomicity. It cannot commit either: the decision might have been abort. Its only correct move is to stay blocked, holding its locks, until the coordinator recovers and replays its decision. Everyone else trying to read or write those rows queues behind a transaction that is neither committed nor rolled back.

This is not an implementation defect. It is a logical consequence of the guarantees: a participant that voted yes has promised both outcomes are still possible, so it cannot choose either one alone. 2PC trades availability for consistency — if the coordinator dies at the wrong moment, the whole transaction set is unavailable until it returns. The three-phase commit protocol tried to remove this window by inserting an intermediate “pre-commit” state that lets participants proceed on timeout. It works when exactly one node fails at a time, but under a network partition — where a partitioned participant can’t tell “coordinator dead” from “I’m cut off” — it can decide differently from the survivors. Since partitions are unavoidable in real networks, 3PC is a rarity in production systems; 2PC’s blocking is accepted as the cost of not being wrong.

Recovery: logs and presumptions

Every crash scenario resolves through write-ahead logs, and the write ordering is the entire safety argument:

On the participant side: write the prepared record before answering yes. If it crashes right after voting yes, recovery finds the prepared record and re-enters the in-doubt state, asking the coordinator for the verdict. If it crashes before voting, recovery aborts — it never promised anything.

On the coordinator side: write the decision record before sending any commit or abort message. If it crashes mid-commit-phase, on restart it reads its log: decision found, re-broadcast; no decision but all yes-votes recorded, it may now decide (and a common optimization lets it abort, since no participant has been told commit); some participants unknown or voted no, abort. If the log shows nothing at all for this transaction, most implementations apply the presumed-abort rule: an absent coordinator record means the transaction was never fully prepared, so recovery aborts and any lingering participant inquiry gets the answer “roll back.” Presumed abort is why in-doubt participants in practice poll the recovered coordinator rather than waiting forever — the protocol blocks, but not permanently, as long as the coordinator’s host comes back.

A minimal coordinator in Go

The core of the protocol is small enough to fit on one screen, which is useful for seeing where the durability points sit:

type Participant interface {
    // Prepare writes changes durably and votes yes/no.
    Prepare(txID string) error // nil = yes
    // Commit or Rollback finalize a prepared transaction.
    Commit(txID string) error
    Rollback(txID string) error
}

type Coordinator struct {
    participants []Participant
    // persist must fsync before returning — this log is the protocol.
    persist func(txID string, decision string) error
}

func (c *Coordinator) Commit2PC(txID string) error {
    // Phase 1: prepare, unanimous or abort.
    for _, p := range c.participants {
        if err := p.Prepare(txID); err != nil {
            return c.abortAll(txID) // any no, or timeout, is a global abort
        }
    }
    // Decision must be durable before it is announced.
    if err := c.persist(txID, "commit"); err != nil {
        return c.abortAll(txID) // cannot prove commit happened; abort
    }
    for _, p := range c.participants {
        if err := p.Commit(txID); err != nil {
            return err // participant will retry-query on recovery
        }
    }
    return nil
}

The unpictured parts — retry loops, recovery replay on startup, in-doubt query handling on the participant side — are where production implementations earn their complexity.

How real systems expose it

The enterprise version is the XA standard: a transaction manager coordinates resource managers (a database, a message broker) through the same prepare/commit contract. PostgreSQL makes the raw protocol directly visible. PREPARE TRANSACTION detaches a transaction’s fate from the session: the transaction becomes a durable, orphanable object that survives even a server restart, finalized later with COMMIT PREPARED or ROLLBACK PREPARED. The feature is disabled by default (max_prepared_transactions = 0), and for a reason — an application that prepares a transaction and then dies leaves the in-doubt transaction holding row locks and blocking vacuum cleanup until a human resolves it. Operations teams that enable it invariably add monitoring for prepared transactions older than a few minutes.

Kafka’s transactional producer is a modern example of the same shape: clients write messages across partitions, then a coordinator-driven prepare/commit sequence makes the whole batch atomically visible or invisible to consumers, as described in the Kafka delivery-semantics documentation. The pattern survives wherever a single atomic decision must span independent storage engines.

When not to use it

2PC’s costs concentrate exactly where microservice architectures are most sensitive: it holds locks across network round trips and process crashes, so throughput collapses as participants multiply or any participant is slow. A single straggler stretches every other participant’s lock hold time. That is why distributed transactions across service boundaries are usually avoided rather than optimized — long-running business processes get coordinated with application-level compensation flows instead, and message-driven designs put atomicity inside one system while propagating changes as events.

The honest summary: 2PC is the only general protocol that gives you atomic commit across independent storage engines without assuming a perfect failure detector, and it achieves that by being willing to stop the world. Use it inside a boundary you control, with fast participants and a coordinator whose log is on reliable storage. Reach for it across service boundaries only when a temporary outage of the whole transaction set is genuinely preferable to inconsistent data — and know, before you deploy it, who gets paged when a prepared transaction sits in limbo at 3 a.m.

Leave a Reply

Your email address will not be published. Required fields are marked *