Two-Phase Commit Explained: Coordinators, Blocking, XA Transactions, Percolator and Why Distributed Commit Is Hard (2026)
Every distributed database that promises atomic writes across shards is running some form of two-phase commit underneath, yet most engineers meet the protocol only when a prepared transaction gets stuck and pins locks for an hour. The protocol itself fits on an index card. The difficulty lives in the log records, the timeouts, and the window during which a participant has promised to commit but does not yet know whether it should. That window is why two-phase commit “blocks”, why three-phase commit never caught on, and why Spanner, Percolator, TiKV and CockroachDB each rebuilt commit around replicated state instead of a single coordinator. In 2026, with sharded Postgres, Kafka transactions and multi-region SQL all mainstream, knowing exactly where that window sits is a practical skill, not trivia.
What this covers: the two-phase commit protocol and its recovery log, presumed abort, blocking, a runnable Python simulation, round-trip latency math, 3PC, Paxos Commit, XA in PostgreSQL and MySQL, Spanner, Percolator, CockroachDB parallel commits, Kafka, a failure-mode table, and when to choose sagas or the outbox pattern instead.
Context and Background
The atomic commitment problem is simple to state. Several independent resource managers (databases, queues, key ranges) each perform part of a transaction. Either all of them make their part durable, or none do, even if machines crash mid-way. Butler Lampson and Howard Sturgis described what became two-phase commit in a Xerox PARC report on crash recovery in distributed storage that circulated from 1976. Jim Gray’s “Notes on Data Base Operating Systems”, published in Springer’s Lecture Notes in Computer Science volume 60 in 1978, gave the protocol its name and its place in database textbooks.
The next decade turned the idea into engineering. The IBM R project (Mohan, Lindsay and Obermarck, ACM Transactions on Database Systems, 1986) introduced the presumed-abort and presumed-commit variants that cut log forces and acknowledgement messages, and essentially every production implementation today descends from presumed abort. Dale Skeen’s 1981 SIGMOD paper “Nonblocking Commit Protocols” proved the conditions under which a commit protocol can avoid blocking and proposed three-phase commit. In 1991 X/Open published Distributed Transaction Processing: The XA Specification*, the C-level interface (xa_prepare, xa_commit, xa_rollback, xa_recover) that lets an external transaction manager drive two-phase commit across heterogeneous resources. Java’s JTA, now Jakarta Transactions, wraps the same model behind XAResource.
The modern turn came when Jim Gray and Leslie Lamport showed in “Consensus on Transaction Commit” (ACM TODS, vol. 31, no. 1, 2006) that classic two-phase commit is the zero-fault-tolerance special case of a more general Paxos Commit. That framing is the key to understanding the current generation. Google Spanner runs two-phase commit between Paxos-replicated groups. Percolator, TiKV and CockroachDB store the commit decision in replicated key-value state rather than in one coordinator’s private log.
If you have already read our explainer on how write-ahead logging and fsync let a single database survive crashes, this post is the multi-node sequel. A single node needs one forced log record to commit. Distributed transactions need several, in a specific order, on different machines, and the order is the whole protocol. The Gray and Lamport paper itself is still the clearest formal statement of why.
How Two-Phase Commit Works: Votes, Forced Logs and the Point of No Return
Two-phase commit is an atomic commitment protocol. A coordinator asks every participant to prepare. Each participant makes its changes durable and votes yes or no. If every vote is yes, the coordinator durably logs COMMIT and tells everyone to commit; any no or timeout produces ABORT. The cost is a blocking window when the coordinator fails after votes.

Figure 1: The two-phase commit message flow with the three forced log writes that make it crash-safe.
Figure 1 shows a coordinator and two participants. Phase one sends PREPARE; each participant forces a prepare record to its log while still holding its locks, then votes YES. When every YES is in, the coordinator forces a COMMIT record. That single disk write is the moment the transaction commits globally. Phase two distributes the decision; participants write their own commit records, release locks and acknowledge, after which the coordinator writes a non-forced END record and forgets the transaction.
The decision is a log record, not a message
The most common misconception is that the transaction commits when participants receive the COMMIT message. It does not. It commits at the instant the coordinator’s COMMIT record reaches stable storage. Before that write, a crashed coordinator will recover with no decision and, under presumed abort, the transaction aborts. After that write, the transaction is committed even if no participant has heard anything yet, and recovery must drive every participant to commit.
This is why the coordinator may reply to the client as soon as the COMMIT record is forced, without waiting for phase two to finish. Phase two is cleanup that can be retried indefinitely. Many engines exploit this. MySQL with XA and the binary log, for example, records the prepared part and the commit part as separate binlog events precisely so that the decision can be reconstructed independently of the data changes.
The participant side has the mirror-image rule. A YES vote is a promise: “I can commit no matter what happens to me next.” To keep that promise across a crash, the participant must force its redo information and a prepare record before replying. If it voted YES from memory and then crashed, it could come back unable to honour a COMMIT. That would break atomicity in the worst possible way: the coordinator would be correct to commit and the participant would be unable to.
Presumed abort trims the happy path
Naive two-phase commit forces a record at every step and acknowledges everything. The R* paper observed that most of this is unnecessary if the system agrees on a default answer for transactions it has no record of. Under presumed abort, a coordinator that finds no information about a transaction answers ABORT. That lets it skip forcing abort records, lets participants skip acknowledging aborts, and lets it omit the participant list from abort records entirely.
Presumed abort also enables the read-only optimisation. A participant that only read data votes READ, releases its locks immediately and writes nothing to its log; the coordinator then excludes it from phase two. A transaction that turned out to be read-only everywhere costs one round of messages and zero log forces. This matters because many “distributed” transactions in practice touch several shards for reads but write to only one.
Presumed commit flips the default. It saves the commit acknowledgement but needs an extra forced “collecting” record listing participants before PREPARE is sent, otherwise a coordinator crash before any decision would wrongly presume commit. The R* authors found presumed abort at least as good as basic two-phase commit in every case, which is why XA and most databases default to it.
Why two-phase commit blocks
Look again at Figure 1. Between forcing its prepare record and receiving the decision, a participant is in doubt. It has given up the right to abort unilaterally, because the coordinator may already have logged COMMIT. It cannot commit unilaterally, because another participant may have voted NO. If the coordinator crashes in that window, the participant must wait, holding every lock the transaction acquired.
Asking the other participants helps only sometimes. If any of them voted NO or never received PREPARE, it knows the outcome is abort. If all of them are also prepared, none of them knows anything the others don’t, and only the coordinator’s log can settle it. Gray and Lamport state the consequence plainly: if the coordinator fails after every participant has sent its prepared message, the participants cannot learn the outcome until it is repaired. This is the blocking problem, and it is a property of two-phase commit itself, not a bug in any implementation.
The practical effect is measured in lock time. A healthy commit holds locks for roughly one round trip plus two log forces. A coordinator that crashes and takes ten minutes to restart holds those locks for ten minutes. Any other transaction that needs the same rows queues behind it, and on PostgreSQL an old prepared transaction also holds back the xmin horizon that VACUUM needs. A single stuck transaction can therefore degrade an entire cluster, not just the rows it touched.
Walk-through: The Participant State Machine and a Runnable Simulation
The cleanest way to internalise two-phase commit is to treat each participant as a small state machine whose transitions are driven by log records, and then break it on purpose.

Figure 2: Participant states in the 2PC protocol. Only the Prepared state can block, and only while the coordinator is silent.
In Figure 2 a participant starts in Working, holding locks. On PREPARE it either votes NO and aborts or forces its log and enters Prepared. From Prepared the only exits are an explicit COMMIT or ABORT from the coordinator. A participant that times out in Working may abort freely, because the coordinator cannot have decided COMMIT without its vote. A participant that times out in Prepared enters the blocked loop and must keep asking. Skeen’s theorem is visible here: Prepared is adjacent to both Committed and Aborted, which is exactly the shape his paper proves cannot be nonblocking.
A simulation with recovery logs
The following Python models a coordinator and participants that each keep an append-only log, standing in for a forced write-ahead log. It uses presumed abort, supports crash injection at each interesting point, and implements recovery for both roles. It has no dependencies beyond the standard library.
"""Two-phase commit simulation with presumed abort and crash recovery.
Run: python3 twopc_sim.py (standard library only)"""
import random
class Crash(Exception):
pass
class Log:
"""Append-only list standing in for a forced write-ahead log."""
def __init__(self):
self.records = []
def force(self, rec):
self.records.append(rec) # in a real system: write + fsync
def find(self, txid):
return [r for r in self.records if r[1] == txid]
class Participant:
def __init__(self, name, will_vote_yes=True):
self.name, self.log = name, Log()
self.will_vote_yes = will_vote_yes
self.locks, self.data = set(), {}
self.pending = {} # txid -> staged writes
self.up = True
def execute(self, txid, key, value):
self.locks.add(key)
self.pending.setdefault(txid, {})[key] = value
def prepare(self, txid):
if not self.up:
raise Crash(self.name)
if not self.will_vote_yes:
self.abort(txid)
return "NO"
# Force redo info and the prepare record BEFORE voting yes.
self.log.force(("PREPARED", txid, dict(self.pending[txid])))
return "YES"
def commit(self, txid):
if not self.up:
raise Crash(self.name)
writes = self.pending.pop(txid, None)
if writes is None: # recovered from log
writes = next(r[2] for r in self.log.find(txid) if r[0] == "PREPARED")
self.data.update(writes)
self.log.force(("COMMITTED", txid))
self.locks -= set(writes)
def abort(self, txid):
writes = self.pending.pop(txid, None)
if writes is None: # recovered from log, or never prepared
writes = next((r[2] for r in self.log.find(txid) if r[0] == "PREPARED"), {})
self.log.force(("ABORTED", txid)) # need not be forced under presumed abort
self.locks -= set(writes)
def crash(self):
self.up, self.pending, self.locks = False, {}, set()
def recover(self, coordinator):
"""Re-acquire locks for in-doubt txns and ask the coordinator."""
self.up = True
in_doubt = {}
for kind, txid, *rest in self.log.records:
if kind == "PREPARED":
in_doubt[txid] = rest[0]
elif kind in ("COMMITTED", "ABORTED"):
in_doubt.pop(txid, None)
for txid, writes in in_doubt.items():
self.locks |= set(writes) # still holding locks: this is blocking
outcome = coordinator.inquire(txid)
if outcome == "UNKNOWN":
print(f" {self.name}: {txid} BLOCKED, holding {sorted(writes)}")
elif outcome == "COMMIT":
self.commit(txid)
else:
self.abort(txid)
class Coordinator:
def __init__(self, participants):
self.parts, self.log, self.up = participants, Log(), True
self.crash_at = None # None | "before_decision" | "after_decision"
def run(self, txid):
votes = []
for p in self.parts:
try:
votes.append(p.prepare(txid))
except Crash:
votes.append("NO") # timeout counts as NO
if self.crash_at == "before_decision":
self.up = False
raise Crash("coordinator")
decision = "COMMIT" if all(v == "YES" for v in votes) else "ABORT"
if decision == "COMMIT":
self.log.force(("COMMIT", txid, [p.name for p in self.parts]))
# Presumed abort: no forced ABORT record needed.
if self.crash_at == "after_decision":
self.up = False
raise Crash("coordinator")
self.finish(txid, decision)
return decision
def finish(self, txid, decision):
for p in self.parts:
try:
p.commit(txid) if decision == "COMMIT" else p.abort(txid)
except Crash:
pass # retried when p recovers and inquires
self.log.force(("END", txid)) # lazily written in practice
def inquire(self, txid):
if not self.up:
return "UNKNOWN"
recs = [r[0] for r in self.log.find(txid)]
return "COMMIT" if "COMMIT" in recs else "ABORT" # presumed abort
def recover(self):
self.up = True
self.crash_at = None
def scenario(label, crash_at=None, no_voter=False):
print(f"\n== {label}")
a, b = Participant("A"), Participant("B", will_vote_yes=not no_voter)
co = Coordinator([a, b])
a.execute("t1", "x", 1)
b.execute("t1", "y", 2)
co.crash_at = crash_at
try:
print(" decision:", co.run("t1"))
except Crash:
print(" coordinator crashed", crash_at)
a.crash(); a.recover(co) # participant restarts while coordinator is down
co.recover()
a.recover(co) # coordinator back: in-doubt txn resolves
b.recover(co)
print(f" A data={a.data} locks={sorted(a.locks)}")
print(f" B data={b.data} locks={sorted(b.locks)}")
if __name__ == "__main__":
random.seed(7)
scenario("happy path")
scenario("participant votes NO", no_voter=True)
scenario("crash before decision", crash_at="before_decision")
scenario("crash after decision", crash_at="after_decision")
Running it prints four scenarios. In the happy path both participants end with their data and no locks. When B votes NO, nothing is written anywhere. The two crash cases are the instructive ones. If the coordinator dies before forcing COMMIT, participant A recovers into Prepared, asks a dead coordinator, and prints BLOCKED while holding lock x. Once the coordinator restarts and finds no record, presumed abort answers ABORT and the locks drop. If the coordinator dies after forcing COMMIT, the same blocked interval occurs, but recovery finds the COMMIT record and drives A and B to commit.
Three details in the code carry the real-world lessons. First, prepare forces the staged writes before returning YES, which is the participant’s promise made durable. Second, the coordinator’s commit point is the single log.force(("COMMIT", ...)) line; moving it after the phase-two loop would make this two-phase commit unsafe. Third, recover on the participant re-acquires locks for in-doubt transactions before it does anything else, because releasing them would let other transactions read data whose fate is unknown.
Counting round trips: latency math for distributed commit
Latency is where two-phase commit is usually judged, so it is worth counting precisely. The numbers below are illustrative assumptions, not measurements, chosen to show the shape of the cost.
Gray and Lamport count costs for the failure-free case with N participants. Classic two-phase commit takes 4 message delays, 3N − 1 messages without co-location, and two sequential stable-storage write delays with N + 1 writes in total. Paxos Commit with 2F + 1 acceptors takes 5 message delays, and their faster variant takes 4, at the price of more messages and N + F + 1 writes. In all three, the stable-storage write delay count is 2: one participant force, then one decision force.
Turn that into wall-clock time. Assume the coordinator runs inside the client’s process, participants are in the same data centre with a 0.5 ms round trip, and each forced log write costs 1 ms on durable SSD with fsync. The client-visible commit latency is one round trip for PREPARE and votes, plus the participant force, plus the coordinator force: about 0.5 + 1 + 1 = 2.5 ms. In two-phase commit, phase two runs after the client is answered, but locks are held through it, so lock hold time is closer to 0.5 + 1 + 1 + 0.25 + 1 = 3.75 ms.
| Deployment (illustrative assumptions) | RTT | Force cost | Client commit latency | Lock hold time |
|---|---|---|---|---|
| Single DC, unreplicated participants | 0.5 ms | 1 ms fsync | ~2.5 ms | ~3.75 ms |
| Single region, each force is a 3-zone quorum write | 0.5 ms | ~2 ms quorum | ~4.5 ms | ~6.75 ms |
| Participants in 3 regions, coordinator co-located with one | 70 ms | ~2 ms quorum | ~74 ms | ~110 ms |
Lock hold time is the number that governs throughput on hot rows. A row that is touched by every transaction can commit at most once per lock hold time, so 3.75 ms caps it at roughly 270 commits per second, and 110 ms caps it at about nine. No amount of extra hardware raises that ceiling, because it is a serial dependency. This is the most useful single calculation to do before choosing cross-region two-phase commit.
The calculation also explains why optimisations target specific steps. Parallel commits remove a sequential consensus round. Async commit lets the client return before the commit phase. One-phase commit skips prepare entirely when all writes land in one shard. Each saves one term from the sum above. A sharding scheme designed so that most transactions touch one shard saves all of them.
Beyond Classic 2PC: Three-Phase Commit, Paxos Commit, Spanner, Percolator and CockroachDB
Every production system since the mid-2000s has attacked the same weakness of two-phase commit: the decision lives in one coordinator’s log. The approaches differ in where they move it.
Three-phase commit and why it is rarely used
Skeen’s analysis shows that a commit protocol is nonblocking only if no state is adjacent to both commit and abort, and no non-committable state is adjacent to commit. Two-phase commit’s Prepared state violates the first rule. Three-phase commit fixes this by inserting a PRE-COMMIT buffer state: the coordinator first tells everyone the decision will be commit, waits for acknowledgements, and only then sends the final COMMIT. If the coordinator fails, a backup coordinator elected from surviving participants can decide from its own state alone.
The catch is the failure model. Skeen assumed that the network never fails and that site failures are detected reliably. In a real network, a partition can leave one side holding PRE-COMMIT and deciding commit while the other side, which never saw PRE-COMMIT, elects its own backup and decides abort. Timeouts cannot tell a crashed node from a slow or partitioned one. Three-phase commit therefore trades blocking for possible inconsistency under partitions, adds a round trip, and still needs failure detection it cannot have. That combination is why it appears in textbooks and almost nowhere in production.
Paxos Commit: replicate the decision
Gray and Lamport took the opposite route. Instead of adding phases, run one consensus instance per participant to record its vote, with 2F + 1 acceptors shared across the transaction. The transaction commits once a majority of acceptors has recorded YES for every participant. Any F acceptors can fail and the outcome remains discoverable from the rest, so no single machine’s failure blocks progress.
Two-phase commit is precisely the F = 0 case, with one acceptor co-located with the coordinator. The paper’s cost table shows the price: for F = 1 and five participants with co-location, classic two-phase commit sends 12 messages, Paxos Commit 17, and the faster variant 20. Message delays stay at 4 or 5. The extra messages are cheap compared with an hour of blocked locks, which is the argument every later system accepted.
Spanner: two-phase commit between Paxos groups

Figure 3: Spanner-style distributed transactions. The coordinator and each participant are Paxos groups, so their prepare and commit records are replicated rather than local.
Google’s Spanner (Corbett et al., OSDI 2012) applies the Paxos Commit idea at a coarser grain. Data is split into groups, each replicated with Paxos. For a read-write transaction, the client buffers writes and picks one group as coordinator. In this two-phase commit, each participant group’s leader acquires write locks, logs a prepare record through Paxos, and votes. The coordinator leader logs the decision through Paxos and informs participants, which log it, apply writes and release locks.
Because every two-phase commit log force in Figure 3 is a quorum write, losing a leader means a new leader takes over with the prepare and decision records intact. The blocking problem shrinks from “until the coordinator machine is repaired” to “until a new Paxos leader is elected”, typically seconds. The trade is latency: each force now costs a consensus round trip across replicas, which the latency table above models as the quorum row.
Spanner adds commit wait for external consistency. The coordinator chooses a commit timestamp no earlier than TrueTime’s upper bound, then waits until that timestamp is guaranteed to have passed before releasing locks. The 2012 paper reports TrueTime uncertainty as a sawtooth of a few milliseconds (reported as roughly 1 to 7 ms, averaging around 4 ms), which bounds the extra wait. Locks held at the participant leaders are not replicated, so a leader failure aborts in-flight transactions rather than blocking them. The concepts of clock uncertainty and why bounded error matters are covered in our post on hybrid logical clocks and vector clocks for event ordering.
Percolator and TiKV: the primary lock is the coordinator
Percolator (Peng and Dabek, OSDI 2010) built cross-row transactions on top of Bigtable, which offers only single-row atomicity. It has no coordinator process at all. Each cell has data, lock and write columns. A transaction gets a start timestamp from a timestamp oracle, then prewrites every cell: it checks for conflicting writes newer than its start timestamp or any existing lock, writes the data, and writes a lock. One lock is designated primary; every secondary lock points to it.
For the second phase of its two-phase commit, the client fetches a commit timestamp, then replaces the primary’s lock with a write record in a single-row transaction. That one row update is the commit point, the exact analogue of the coordinator’s forced COMMIT record. Secondary locks are then rolled forward. If the client dies, a later reader that trips over a stale secondary lock follows the pointer to the primary. A committed primary means roll forward; a missing commit record means roll back. The coordinator’s state has been moved into the replicated data store itself.
The paper is candid about cost. Its timestamp oracle served around 2 million timestamps per second from one machine with batching, average transaction latency in its TPC-E-like benchmark was 2 to 5 seconds, and lazy lock cleanup could delay commits by tens of seconds. Percolator was built for incremental indexing throughput, not interactive latency, and it provides snapshot isolation rather than serialisability. If those isolation trade-offs are new, our guide to MVCC, snapshot isolation and write skew covers them.
TiKV, the storage layer behind TiDB, adopted the Percolator model over Raft-replicated regions and then attacked its latency. Async commit stores the list of secondary keys inside the primary lock, so a transaction’s status can be determined from the locks alone once all prewrites succeed. TiDB can then answer the client without waiting for the commit phase. Its one-phase commit (1PC) path goes further: when all keys live in one region, the transaction commits during prewrite with no second phase.
CockroachDB: write intents and parallel commits
CockroachDB uses a transaction record stored at one key with states such as PENDING, COMMITTED and ABORTED, and write intents on every modified key that point back to the record. Flipping the record to COMMITTED is the commit point. Readers that hit an intent check the record, so recovery is again distributed into the data.
Originally this two-phase commit variant cost two sequential consensus rounds: replicate the intents, then replicate the COMMITTED record. CockroachDB’s parallel commits protocol, enabled by default from version 19.2, adds a STAGING state that lists every in-flight write. The record and the intents are replicated in parallel. A transaction is implicitly committed once its record is STAGING and every listed write has achieved consensus. The client is answered after one consensus round, and the record is marked COMMITTED asynchronously. Cockroach Labs describes this as halving distributed transaction commit latency. A contending transaction that finds an abandoned STAGING record runs a recovery procedure that checks each listed intent and either confirms the commit or aborts it by preventing the missing write.
Kafka transactions and KIP-939
Apache Kafka’s transactions, introduced through KIP-98 in 2017, follow the two-phase commit pattern inside one cluster. A transaction coordinator broker records state transitions in the internal __transaction_state topic. On commit it moves the transaction to PrepareCommit, which is the durable decision, then has partition leaders append commit markers to every partition the transaction touched before moving to CompleteCommit. Producer epochs fence zombie instances, and read_committed consumers do not read past the last stable offset. A hanging transaction therefore blocks consumers, which is the Kafka form of the blocking problem; our post on Kafka exactly-once semantics covers the operational side.
Kafka transactions historically could not take part in someone else’s two-phase commit, so “write to Postgres and Kafka atomically” needed the outbox pattern. KIP-939, “Support Participation in 2PC”, was accepted to change that. It adds a transaction.two.phase.commit.enable setting on producer and broker (default false), an initTransactions(keepPreparedTxn) overload, prepareTransaction() returning a serialisable PreparedTxnState, and completeTransaction(). Third-party configuration references list the setting from the Kafka 4.1 line onward; check your version’s release notes before relying on it, since the 4.1.0 announcement did not highlight it.
XA Transactions in Practice: PostgreSQL, MySQL and JTA
XA is two-phase commit with a standard interface between a transaction manager (TM) and resource managers (RMs). The TM, typically an application server, Narayana, Atomikos or a database proxy, owns the decision log. Databases only implement the participant role.
PostgreSQL exposes the participant side directly in SQL. PREPARE TRANSACTION 'gid' dissociates the transaction from the session and stores its state on disk; COMMIT PREPARED or ROLLBACK PREPARED can later be issued from any session. The PostgreSQL documentation for PREPARE TRANSACTION is unusually blunt: the command is intended for external transaction managers, not applications; a prepared transaction keeps holding its locks; and leaving one prepared for a long time interferes with VACUUM and, in extreme cases, can force a shutdown to prevent transaction ID wraparound.
Two configuration facts trip teams up. max_prepared_transactions defaults to 0, which disables the feature, and it can only be changed at server start. The docs recommend setting it at least as high as max_connections if you use prepared transactions, and a hot standby must use the same or a higher value than the primary or it will refuse queries. Prepared-transaction identifiers must be under 200 bytes, and a transaction that touched temporary tables, created WITH HOLD cursors or used LISTEN/NOTIFY cannot be prepared. In-doubt transactions are visible in the pg_prepared_xacts view, which is the first place to look when vacuum stops making progress.
MySQL implements XA for InnoDB with XA START, XA END, XA PREPARE, XA COMMIT, XA ROLLBACK and XA RECOVER, plus XA COMMIT ... ONE PHASE for single-branch transactions. The MySQL 8.4 manual describes a two-part binary log record: the prepared portion is logged under one GTID at XA PREPARE, and the XA COMMIT or XA ROLLBACK under a second GTID later. The two parts can interleave with other transactions and even land in different binlog files. Replication filters are not supported with XA, and the manual flags XA as unsafe under statement-based replication.
The manual also notes that REPEATABLE READ may not be sufficient for distributed transactions and that SERIALIZABLE may be preferred. That deserves attention. Two-phase commit guarantees atomicity, not isolation. Each RM enforces its own isolation level locally, and nothing in XA coordinates snapshots across RMs, so a reader can observe one branch committed and another not yet committed.
On the JVM, Jakarta Transactions (formerly JTA) defines UserTransaction for applications and XAResource for drivers, mapping almost one-to-one onto the X/Open calls. The specification is mature and stable; Jakarta Transactions 2.0 shipped with Jakarta EE 9 in 2020 and mainly moved the package namespace to jakarta.transaction. The hard part is never the API. It is the TM’s own recovery log: if it lives on a container’s ephemeral disk, a pod reschedule erases the only record of which in-doubt branches should commit.
Failure Modes: What Actually Goes Wrong
Most two-phase commit incidents fall into a small set of patterns. The table summarises each with the observable symptom and the mechanism that resolves it.
| Failure | When it happens | Symptom | Resolution mechanism |
|---|---|---|---|
| Participant crashes before voting | Phase 1 | Coordinator times out | Treat as NO; abort everywhere |
| Participant crashes after voting YES | Between phases | Its locks reappear on restart | Recovery reads prepare record, asks coordinator |
| Coordinator crashes before forcing decision | Phase 1 or after votes | Participants in doubt | On restart, no record means abort under presumed abort |
| Coordinator crashes after forcing COMMIT | Phase 2 | Participants in doubt, some may have committed | On restart, re-send COMMIT until all acknowledge |
| Coordinator log lost permanently | Any time after prepare | Prepared transactions never resolve | Manual heuristic decision; atomicity may be violated |
| Network partition during phase 2 | Phase 2 | Some participants committed, others blocked | Blocked side waits; no safe unilateral action |
| Heuristic commit or rollback by an operator | Any in-doubt time | Mixed outcome across RMs | XA heuristic errors; manual reconciliation |
| Duplicate or reused global transaction ID | Prepare | Prepare fails or binds to wrong transaction | Unique, durable GIDs per transaction |
| Long-running prepared transaction | Hours to days | Vacuum or purge stalls, bloat grows | Monitoring and alerting on prepared age |
The heuristic rows deserve emphasis. XA lets an RM make a heuristic decision, committing or rolling back an in-doubt branch on its own, usually because an operator forced it. When the TM later sends the real decision and it disagrees, the TM reports a heuristic mixed or heuristic hazard outcome. At that point the database has stopped guaranteeing atomicity and a human must reconcile the data. Heuristic resolution is sometimes the right call during an outage, but it must be logged and audited as a data-integrity event.
Lost coordinator logs are the nastiest failure because two-phase commit has no answer for them. Every in-doubt branch is permanently in doubt. Teams usually discover this when a transaction manager embedded in an application server was deployed with its object store on local disk, and an autoscaler replaced the node.
Trade-offs, Gotchas, and What Goes Wrong
The first trade-off is availability. Classic two-phase commit requires every participant to be up to commit. If you span five services each with 99.9% availability, the probability that all five can commit at a given moment is about 0.999⁵, or roughly 99.5%, before counting the coordinator. Distributed transactions multiply unavailability; replicated participants as in Spanner reduce each term but do not remove the product.
The second is coupling. A participant that votes YES has handed control of its locks to another system. In a microservice architecture, that means one team’s slow coordinator can stall another team’s database. This is the main reason service-oriented systems avoid cross-service two-phase commit, and it is an organisational argument as much as a technical one.
The third is a connection pooling gotcha for two-phase commit. A prepared transaction is detached from its session in PostgreSQL, which is fine, but the TM’s prepare and commit must use stable global transaction IDs and survive the pooler. Transaction-mode pooling in PgBouncer and similar proxies reassigns server connections between transactions, which is compatible with COMMIT PREPARED from any session, but session-scoped state set around the transaction does not follow it. Our comparison of PostgreSQL connection poolers in transaction mode lists what breaks.
Fourth, atomic commit does not mean consistent reads. As noted above, XA coordinates the outcome, not visibility. Internal engines such as Spanner, CockroachDB and TiDB solve this with timestamps and MVCC across shards, which is a large part of why they exist. Bolting XA onto independent databases gives you atomicity with a visibility gap.
Fifth, two-phase commit timeouts are asymmetric. A participant may time out and abort before voting. After voting, timeouts may only trigger inquiries. Code that applies a generic “abort on timeout” to the prepared state is a correctness bug that will eventually commit on one side and abort on the other.
Finally, sagas are not a free substitute. They give up isolation entirely, so intermediate states are visible and compensations must be designed per step. The saga pattern guide covering orchestration versus choreography treats those costs in depth; the point here is that both approaches have a failure budget, and you are choosing which one to pay.
Two-Phase Commit vs Sagas vs Outbox: Choosing a Distributed Transaction Strategy

Figure 4: A decision path for distributed transactions. Native engine transactions first, outbox for database plus broker, XA only when operations can own in-doubt resolution, sagas otherwise.
Figure 4 encodes the decision most teams should make. If every write lands in one distributed database such as Spanner, CockroachDB, TiDB, YugabyteDB or a sharded Postgres with built-in coordination, use its native transactions. The engine owns the replicated decision record, recovery is automatic, and it coordinates visibility as well as atomicity. Our architecture comparison of Vitess, Citus and CockroachDB covers how each handles multi-shard writes.
If the cross-system write is “update my database and publish an event”, the transactional outbox pattern with CDC is almost always better than XA. The event goes into a table in the same local transaction, and change data capture publishes it. One local commit replaces a distributed one, and consumers handle at-least-once delivery with idempotency.
XA two-phase commit is defensible when all resources are XA-capable, latency between them is low, the transaction is short, and someone owns the transaction manager’s durable log and in-doubt resolution runbook. Legacy enterprise integrations between a relational database and an IBM MQ or similar queue are the classic fit. Everything else, especially cross-service business processes that span seconds to days, belongs in a saga with compensations and idempotency keys that make retries safe.
| Approach | Atomicity | Isolation | Blocking risk | Latency cost | Operational burden |
|---|---|---|---|---|---|
| Native distributed DB transaction | Yes | Engine-level, often serialisable or SI | Low, replicated decision | 1–2 consensus rounds | Low |
| XA two-phase commit | Yes | Per-RM only | High if TM fails | 1 RTT + 2 forces | High: TM log, in-doubt runbooks |
| Transactional outbox | Yes for DB plus event | Local only | None | One local commit | Medium: CDC pipeline |
| Saga | Eventual, via compensation | None across steps | None | Per-step | High: compensation design |
Practical Recommendations
Start by reducing the need for two-phase commit at all. Choose shard keys so that the common transaction touches one shard, and you inherit the one-phase fast path that TiKV, CockroachDB and others implement. Measure the fraction of multi-shard transactions before and after any schema change, because it drives both latency and lock contention.
When you do use XA two-phase commit, treat the transaction manager as a database. Put its log on replicated durable storage, back it up, and test recovery by killing the TM mid-commit in staging. Alert on any prepared transaction older than a few seconds, using pg_prepared_xacts in PostgreSQL and XA RECOVER in MySQL. Write the heuristic-resolution runbook before you need it, including who may approve a forced decision and how the reconciliation is audited.
For new cross-service workflows, default to the outbox pattern for “database plus event” and sagas for long-lived business processes. Reserve two-phase commit for short, low-latency transactions among resources you control. If you are evaluating a distributed SQL database, ask how its commit record is replicated, how many sequential consensus rounds a multi-range commit costs, and what happens to locks when a leader fails. Those three answers predict its behaviour better than any benchmark. For background on the consensus layer itself, see our comparison of Raft and Paxos failure modes.
Checklist:
- Count multi-shard transactions and compute lock hold time × hot-row rate.
- Keep
max_prepared_transactionsat 0 unless a real TM manages prepared transactions. - Store the TM recovery log on replicated storage and test crash recovery.
- Alert on prepared-transaction age; page on anything older than your SLO.
- Never abort a prepared branch on timeout; inquire instead.
- Use unique, durable global transaction IDs.
- Prefer outbox for DB plus broker, sagas for cross-service processes.
Frequently Asked Questions
What is two-phase commit in simple terms?
Two-phase commit is a protocol that makes several independent systems either all commit a transaction or all abort it. In the first phase a coordinator asks each participant to prepare; each one saves its changes durably and votes yes or no. In the second phase, if every vote was yes, the coordinator records COMMIT in its own log and tells everyone to commit. Any no vote or timeout leads to abort. The coordinator’s durable COMMIT record, not the messages, is the actual commit point.
Why is two-phase commit called a blocking protocol?
After a participant votes yes it may neither commit nor abort on its own, because it does not know what the others voted and the coordinator may already have decided. If the coordinator crashes in that window and all participants are prepared, none of them can learn the outcome until the coordinator recovers its log. They keep holding locks the whole time. Gray and Lamport describe exactly this case. Replicating the decision, as Paxos Commit and Spanner do, shrinks the blocking time to a leader election rather than a machine repair.
What is the difference between two-phase commit and three-phase commit?
Three-phase commit adds a PRE-COMMIT step between voting and committing so that a backup coordinator can decide safely when the original coordinator fails. Skeen proved it is nonblocking under his model, which assumes the network never fails and failures are detected reliably. Real networks partition, and timeouts cannot distinguish a crashed node from a slow one, so 3PC can produce inconsistent outcomes across a partition. It also costs an extra round trip. Production systems prefer two-phase commit replicated via consensus instead.
Are XA transactions still used in 2026?
Yes, mainly in enterprise integration where a relational database and a message queue must commit together, and in Java application servers using Jakarta Transactions. PostgreSQL supports the participant side through PREPARE TRANSACTION, and MySQL supports XA for InnoDB. New microservice designs rarely choose XA because it couples services, needs a durable transaction manager log, and coordinates only atomicity, not cross-database isolation. Most teams now use native distributed SQL transactions, the transactional outbox, or sagas, and keep XA for short transactions among resources they control.
How does Percolator differ from classic two-phase commit?
Percolator has no separate coordinator process. It stores locks and commit records in the same replicated Bigtable rows as the data. One lock is marked primary and all other locks point to it. Committing means atomically replacing the primary lock with a write record, which is the commit point. If the client crashes, any later reader can follow a secondary lock to the primary and roll the transaction forward or back. TiKV and TiDB use this model on Raft, with async commit and one-phase commit to cut latency.
Should I use two-phase commit or a saga for microservices?
For workflows spanning independent services, a saga is usually the better default. Two-phase commit forces every service to hold locks while waiting for a shared coordinator, so one slow or failed component stalls the others, and availability falls as the product of every participant’s uptime. Sagas avoid locking across services but expose intermediate states and need carefully designed compensations. If the real need is only “update the database and publish an event”, the transactional outbox pattern is simpler than either.
Further Reading
- Saga pattern: orchestration vs choreography and compensating transactions — the main alternative to cross-service 2PC.
- Database sharding with consistent hashing, rendezvous hashing and resharding — how shard-key design decides how often you need distributed commit.
- Write-ahead logging explained: fsync, group commit, checkpoints and torn pages — the single-node log forcing that every two-phase commit participant relies on.
- Transactional outbox pattern with CDC — atomic database-plus-event publishing without XA.
- Jim Gray and Leslie Lamport, “Consensus on Transaction Commit”, ACM TODS 31(1), 2006.
- Daniel Peng and Frank Dabek, “Large-scale Incremental Processing Using Distributed Transactions and Notifications”, OSDI 2010.
By Riju — about
