Two-Phase Commit: Atomic Commits Across Machines and Why They Block
A payments team shards its ledger across two Postgres clusters. A transfer debits account 1042 on shard A and credits account 7781 on shard B, and both changes must land or neither. They wire up two-phase commit with PREPARE TRANSACTION, and for months it works.
Then the coordinator process is OOM-killed during a deploy. It had already received “prepared” from both shards but had not yet sent the commit. Both shards now hold a prepared transaction that neither can finish alone: committing might be wrong if the coordinator decided to abort, aborting might be wrong if it decided to commit. The row locks on both accounts stay held.
Every transfer touching those two accounts queues behind the locks. The prepared transactions also pin the oldest-transaction horizon, so autovacuum stops reclaiming dead rows on the busiest table. It takes 40 minutes for someone to find pg_prepared_xacts, read the coordinator’s log and run COMMIT PREPARED by hand. That is the blocking problem, and it is the single most important thing to understand about 2PC.
What it is
Two-phase commit (2PC) is an atomic commitment protocol. It makes a set of independent databases, called participants (or resource managers), all commit a transaction or all abort it, under the direction of a coordinator (or transaction manager).
It is about atomicity across machines, the A in ACID. It says nothing about isolation between concurrent transactions; each participant still uses its own locking or MVCC, as described in transaction isolation levels.
The key idea is that a participant gives up its right to abort. After it votes yes in phase one, it has promised that it can commit no matter what happens, including a crash and restart. It must then wait for the coordinator’s decision.
How it works
The two phases
Phase 1, prepare (voting). The coordinator sends PREPARE to every participant. Each participant does all the work needed to guarantee it can commit: acquires locks, checks constraints, and force-writes its changes plus a “prepared” record to its durable log. Then it votes YES. If anything fails, it votes NO and aborts locally.
Phase 2, commit (decision). If every vote is YES, the coordinator force-writes a COMMIT decision to its own log, then sends COMMIT to all participants. If any vote is NO or a participant times out, the decision is ABORT. Participants apply the decision, release locks and acknowledge. When all acks arrive, the coordinator can forget the transaction.
sequenceDiagram participant C as Coordinator participant A as Shard A participant B as Shard B Note over C,B: Application has done its writes on A and B C->>A: PREPARE C->>B: PREPARE A->>A: lock rows, fsync prepare record B->>B: lock rows, fsync prepare record A-->>C: YES B-->>C: YES C->>C: fsync COMMIT decision (commit point) C->>A: COMMIT C->>B: COMMIT A-->>C: ACK (locks released) B-->>C: ACK (locks released) C->>C: write END, forget txn
The commit point is the moment the coordinator’s COMMIT record is durable. Before it, the transaction can still abort. After it, the transaction is committed, even if no participant has heard yet, and the coordinator must keep retrying COMMIT until every participant acknowledges.
Participant states
stateDiagram-v2 [*] --> Working Working --> Aborted: vote NO or local failure Working --> Prepared: fsync prepare record, vote YES Prepared --> Committed: COMMIT from coordinator Prepared --> Aborted: ABORT from coordinator Prepared --> Prepared: coordinator silent (in doubt, locks held) Committed --> [*] Aborted --> [*]
A participant in Working can abort unilaterally on a timeout. A participant in Prepared cannot. It is in doubt: it does not know the outcome and is not allowed to guess.
Coordinator log and recovery
The coordinator’s log is the source of truth for every decision. On restart, the coordinator reads it:
- Transactions with a COMMIT record and no END: resend COMMIT to all participants until acknowledged.
- Transactions with an ABORT record: resend ABORT.
- Transactions with no decision record: the coordinator never reached the commit point, so it can safely abort them.
A participant restarting in the Prepared state does the reverse. It reacquires the locks for its prepared transactions (Postgres keeps prepared transactions across a restart for exactly this reason) and asks the coordinator for the outcome.
Presumed abort
Every forced log write costs an fsync. Presumed abort is the standard optimisation: if the coordinator has no record of a transaction, the answer is “abort”. That means the coordinator never needs to force-write an ABORT record, and participants do not need to acknowledge an abort, because forgetting it is the same as aborting it. Commits still need the forced COMMIT record and acknowledgements. Read-only participants can also vote “read-only” in phase one and skip phase two entirely. Since most failures happen before the commit point, presumed abort removes a lot of disk and network work from the failure path.
The blocking problem
2PC is a blocking protocol. If the coordinator crashes after participants voted YES and before they learn the decision, those participants are stuck. They cannot commit, because another participant might have voted NO. They cannot abort, because the coordinator might have logged COMMIT and told someone else. They hold their locks until the coordinator recovers.
The participants could ask each other: if any one of them already received COMMIT or ABORT, or any of them voted NO, the others can follow. But if every participant voted YES and none got the decision, only the coordinator knows. Waiting is the only safe choice.
Two things make this worse in practice:
- Locks spread the outage. A stuck prepared transaction holds row locks. Any other transaction needing those rows waits, and a hot row turns one stuck transaction into a queue of thousands.
- Heuristic decisions. XA allows an operator or resource manager to unilaterally commit or roll back an in-doubt transaction to release locks. If the guess differs from the coordinator’s real decision, you get a heuristic mixed outcome: atomicity is broken and someone must reconcile by hand.
The fix is not a smarter protocol between the same nodes. It is making the coordinator itself fault tolerant, by replicating its log with consensus. That is what modern distributed databases do, covered below.
Why three-phase commit is not the answer
Three-phase commit (3PC) adds a PRE-COMMIT phase between voting and committing. After everyone votes YES, the coordinator first tells everyone “we are going to commit”. A participant that has received PRE-COMMIT knows all votes were YES, so if the coordinator dies, the remaining participants can elect a new coordinator and finish without blocking.
It is non-blocking only under assumptions that real networks break: nodes fail by stopping, and message delays are bounded so a timeout reliably means a crash. Under a network partition, one side can time out and commit while the other side times out and aborts, which violates atomicity. It also costs an extra round trip on every commit. So 3PC is a textbook protocol, not a production one. The practical non-blocking answer is to run 2PC with a coordinator whose state lives in a consensus group (Gray and Lamport’s Paxos Commit formalises this), so the coordinator effectively never “disappears”.
Worked example: what 2PC costs
Round trips are the dominant cost. Use the widget to compare a same-datacentre round trip with a cross-continent one; 2PC pays at least two of the latter for every cross-region commit.
Real-world systems
XA and where it still exists
XA is the X/Open standard interface between a transaction manager and resource managers. In the Java world it surfaces as JTA, and application servers or libraries such as Narayana and Atomikos act as the coordinator. The databases expose the participant side directly:
- Postgres has
PREPARE TRANSACTION 'gid',COMMIT PREPAREDandROLLBACK PREPARED. The feature is disabled by default becausemax_prepared_transactionsdefaults to 0. Open prepared transactions are listed inpg_prepared_xacts, survive restarts, hold their locks, and hold back VACUUM. The Postgres docs advise leaving the feature off unless you run a transaction manager that closes prepared transactions promptly. - MySQL (InnoDB) supports
XA START,XA END,XA PREPARE,XA COMMITandXA ROLLBACK, withXA RECOVERlisting in-doubt transactions after a crash. - Message brokers like IBM MQ and ActiveMQ have XA support, which is why XA lingers in banking and mainframe-adjacent stacks.
Kafka has no XA support. Kafka transactions make a set of writes to Kafka partitions (plus consumer offsets) atomic, which is the basis of its exactly-once processing, but they cannot enlist a database in the same atomic commit. Kafka is now adding opt-in hooks for an external coordinator (KIP-939, off by default), but the standard way to update a database and publish an event atomically is still the outbox pattern, and delivery semantics explains the guarantees on each side.
How distributed SQL does it internally
Distributed SQL databases run 2PC every time a transaction touches more than one shard, but they remove the blocking problem by making every participant and the coordinator a replicated consensus group.
- Google Spanner shards data into Paxos groups. A multi-group transaction picks one group’s leader as the 2PC coordinator; the other group leaders are participants. Each participant logs its prepare record through Paxos, and the coordinator logs the commit record through Paxos and performs commit wait for TrueTime before releasing the outcome. A crashed leader is replaced by another replica that already has the log, so the “coordinator vanished” case becomes a leader election measured in seconds, not an outage.
- CockroachDB stores a transaction record in a Raft-replicated range. Its parallel commits protocol (since 19.2) writes the record as STAGING in parallel with the final writes; once all those writes are replicated, the transaction is committed even though the record still says STAGING, and the client is acknowledged after roughly one round of consensus instead of two. The record is moved to COMMITTED asynchronously, and any reader that finds a STAGING record can check the writes to determine the outcome.
- TiDB uses a Percolator-style 2PC where the transaction’s primary key acts as the commit point, with each region replicated by Raft.
The lesson: 2PC is fine, and everywhere, when the participants are tightly coupled parts of one database with replicated coordinators and short transactions. It is painful when the participants are independent systems owned by different teams.
Why microservices avoid it
Across services, almost every assumption 2PC needs is false:
- Participants must support prepare. An HTTP API like a payment provider’s charge endpoint has no “prepare and hold”. Neither do most managed queues, search clusters or SaaS APIs.
- Locks cross team boundaries. A slow or stuck inventory service would hold locks in the payments database. That is exactly the coupling service boundaries exist to remove.
- Availability multiplies down. Every participant must be up for every commit, as the worked example shows.
- Latency stretches lock hold time, which caps throughput on hot rows.
So microservices replace atomic commit with a sequence of local transactions plus compensations, which is the saga pattern, and they publish events reliably with an outbox. You give up isolation between steps and gain independence.
How to apply it
| Situation | Use 2PC? | Instead |
|---|---|---|
| Multi-shard transaction inside a distributed SQL database | Yes, the database does it for you | keep transactions short |
| Two Postgres shards you operate | Only with a real transaction manager and monitoring | re-shard so the transaction stays on one shard |
| Database write plus publish an event | No (Kafka has no XA) | outbox pattern |
| Order spanning inventory, payment, shipping services | No | saga with compensations |
| Legacy JTA stack with XA-capable DB and MQ | Acceptable, it is what it was built for | keep in-doubt monitoring |
If you do run 2PC yourself:
- Make the coordinator log durable and, ideally, replicated.
- Alert on any prepared transaction older than a few seconds (
pg_prepared_xactsin Postgres,XA RECOVERin MySQL). - Use presumed abort and read-only optimisations.
- Keep participants in the same region, keep transactions small, and set timeouts for the Working phase so slow participants abort before they prepare.
- Write the runbook for manual resolution before you need it, and never resolve an in-doubt transaction without checking the coordinator’s log.
Interview questions
1. The coordinator crashes after all participants voted YES. What happens, and how is it resolved?
The participants are in the Prepared state and in doubt. They must not commit or abort on their own, because they do not know whether the coordinator logged COMMIT. They keep their locks and wait. When the coordinator restarts it reads its log: if a COMMIT record exists it resends COMMIT; if no decision record exists it never reached the commit point and aborts. If the coordinator cannot be recovered, an operator can resolve the transaction manually, but only after determining the true decision, otherwise atomicity breaks. Systems avoid this entirely by replicating the coordinator log with Paxos or Raft.
2. Why is three-phase commit not used in practice?
3PC is non-blocking only if failures are crash-stop and message delays are bounded, so that a timeout reliably means a crash. Real networks partition. During a partition, participants on one side can time out and commit while the other side aborts, violating atomicity. It also adds a round trip to every commit. Replicating the 2PC coordinator with consensus gives non-blocking behaviour that is safe under partitions, so that is what production systems do.
3. How does Spanner run 2PC without the blocking problem?
Each participant is a Paxos group rather than a single machine, and the coordinator is the leader of one of those groups. Prepare and commit records are written through Paxos, so they survive the loss of any minority of replicas. If the coordinator leader crashes, another replica of its group becomes leader with the log intact and continues the protocol. The protocol is still 2PC; what changed is that the participants and coordinator no longer disappear.
✅ Key takeaways
- 2PC makes participants commit or abort together: prepare (vote, force-write, hold locks), then a coordinator decision.
- Once a participant votes yes it is in doubt until it hears the decision. A coordinator crash blocks it with locks held.
- The coordinator log is the source of truth; presumed abort means “no record” equals abort and saves forced writes.
- 3PC is unsafe under partitions. The real fix is a coordinator replicated by consensus, as in Spanner and CockroachDB.
- Cost: at least two round trips per commit, lock hold time that caps hot-row throughput, and availability that multiplies down.
- Microservices use sagas and the outbox instead; Kafka has no XA and most APIs cannot prepare.
🧠 Check your understanding
0 / 4-
1A participant has voted YES and then loses contact with the coordinator for 10 minutes. What should it do?
After voting YES the participant gave up the right to decide. Aborting on timeout is the tempting choice, but the coordinator may have logged COMMIT and told others, which would break atomicity. Committing is wrong for the mirror reason. Participants can learn the outcome from each other only if one already knows it.
-
2Under presumed abort, what happens when a participant asks a restarted coordinator about a transaction it has no record of?
No record means the commit point was never reached, so the answer is abort. That is what lets the coordinator skip forced abort records. Replying commit would describe presumed commit, a different variant that logs at transaction start.
-
3Why does three-phase commit fail to guarantee atomicity in real networks?
3PC treats a timeout as a crash. Under a partition that assumption is false and the two sides can reach different decisions. Clock sync is not a 3PC requirement, and participant count is irrelevant.
-
4A service must update its Postgres table and publish an event to Kafka atomically. What is the standard approach?
Kafka is not an XA participant, so a 2PC across both is not available. Writing to Kafka then Postgres is a dual write that can leave them inconsistent if the second step fails. The outbox makes the event part of the local transaction and a relay publishes it at least once.
Where to go next
- Saga pattern: the alternative for multi-service workflows, with compensations instead of locks.
- Outbox, inbox and CDC: how to make a database write and an event publish consistent without 2PC.
- Distributed consensus: the Raft and Paxos machinery that makes a replicated coordinator possible.
- Sharding and partitioning: how to choose shard keys so most transactions never cross a shard.
Finished this lesson?
Mark it complete to track your progress across the roadmap.