Distributed transactions and two-phase commit
Why committing atomically across databases is hard, how two-phase commit works and where it blocks, and how to decide whether you need it at all.
The problem
A shop keeps orders in one database and account balances in another. Placing an order must insert the order and debit the customer, and the two must both happen or both not happen. Inside one database that is an ordinary transaction. Across two, the obvious code is: commit the debit, then commit the order.
Now list what can happen between those two commits. The process crashes. The orders database rejects the insert because of a constraint. The network drops and the second commit times out, leaving you unsure whether it happened. In every case the customer has paid for an order that does not exist. Reversing the order of the commits only changes which half is missing. The same problem appears as soon as you shard a database and a transfer moves money between accounts on two shards.
A commit cannot be taken back, and two machines cannot commit at the same instant. So a protocol is needed in which every party first promises that it is able to commit, and only then is anyone allowed to. Jim Gray described that protocol, two-phase commit, in 1978, and it is still the basis of almost every distributed transaction.
Atomic commit
The property we want is atomic commit: either every participant commits or every participant aborts, even when machines crash and messages are lost. A node that has committed must never be asked to undo it, so no node may commit until all the others are certain to.
Note what this leaves out. Atomic commit says nothing about isolation between concurrent transactions. Systems that offer distributed transactions add locking or multi-version concurrency control across nodes for that. And two-phase commit (2PC) has nothing to do with two-phase locking, despite the name.
Two-phase commit step by step
One node is the coordinator, often a library inside the application or a separate transaction manager. The databases are participants.
- Do the work. Each participant executes its part of the transaction and takes its locks, but does not commit.
- Prepare (phase one). The coordinator sends
prepareto every participant. Each one checks that it can definitely commit, writes everything it needs to durable storage, and votes yes. If it cannot, it votes no. A yes vote is a promise: the participant gives up the right to abort, and must be able to commit even after a crash and restart. - Decide. If every vote is yes, the coordinator writes
committo its own durable log. If any vote is no or missing, it writesabort. That log write is the commit point. Before it the transaction can still abort. After it the outcome is fixed. - Commit (phase two). The coordinator sends the decision to every participant and retries until each one acknowledges. Participants apply it and release their locks.
Step 1 of 9
The order service must insert an order in one database and debit an account in another, as one atomic change. It asks the coordinator to run both. Each database does the work and takes locks, but does not commit.
Read the steps as text
- The order service must insert an order in one database and debit an account in another, as one atomic change. It asks the coordinator to run both. Each database does the work and takes locks, but does not commit.
- Phase one. The coordinator sends prepare to every participant. The question is: can you promise to commit this transaction, whatever happens next?
- Each participant writes the transaction to its durable log and votes yes. A yes vote is a promise. From now on the participant cannot abort on its own, even after a crash and restart.
- Both votes are yes, so the coordinator writes commit to its own log. That single disk write is the commit point. If any vote had been no, or had timed out, it would have written abort.
- Phase two. The coordinator sends commit to the orders database, which commits and releases its locks. Then the coordinator crashes, before it has told the payments database.
- The payments database is now in doubt. It voted yes, so it may not abort. It has not heard commit, so it may not commit. It keeps its locks, and every other transaction that needs those rows waits behind it.
- A timeout cannot help. If payments aborted now, the order would exist with no payment. Asking the orders database would work in this case, but in general the other participants may be in doubt or unreachable too.
- The coordinator restarts, reads its log, finds the commit decision and sends it again. The payments database commits and releases its locks. Had the log held no decision, the coordinator would have aborted.
- Two-phase commit does deliver all or nothing. The cost is the in-doubt window: one crashed coordinator leaves locks held in other databases until it returns. Production systems therefore replicate the coordinator log.
What happens when something fails
| Failure | Result |
|---|---|
| A participant crashes before voting, or votes no | The coordinator aborts. Nothing is lost. |
| A participant crashes after voting yes | On restart it finds the prepared transaction in its log, keeps its locks and asks the coordinator for the outcome. |
| The coordinator crashes before logging a decision | Participants that have not voted time out and abort. Any that voted yes are stuck until it recovers and aborts. |
| The coordinator crashes after logging commit | Participants that have not heard are stuck until it recovers and resends the decision. |
The stuck state is called in doubt. A participant that has voted yes and has not heard the decision cannot commit, because another participant may have voted no. It cannot abort, because the coordinator may already have told someone else to commit. It can only wait, holding its locks. Every other transaction that needs those rows queues behind it, so one failed coordinator becomes stalled queries in several databases. This is why 2PC is called a blocking protocol.
Participants can ask each other, and if any one of them knows the decision the rest can follow it. If all of them are in doubt, nobody knows.
Three-phase commit (3PC) adds a pre-commit round between voting and committing, so that no participant is uncertain while another has already committed. That makes it non-blocking, but only if message delays are bounded and a crashed node can be told apart from a slow one. Real networks partition and stall, and then 3PC can let two sides reach different outcomes. It is rarely used in practice.
XA
XA is the standard interface for 2PC across products, published by X/Open in 1991. A transaction manager drives resource managers through calls such as prepare and commit. PostgreSQL exposes its side as PREPARE TRANSACTION and COMMIT PREPARED, MySQL as XA PREPARE and XA COMMIT, and Java applications reach it through JTA.
XA works, and it has a poor operational reputation. The coordinator is often an application server with a log on its local disk, so losing that machine leaves in-doubt transactions for an operator to resolve by hand. A forgotten prepared transaction in PostgreSQL holds its locks and stops vacuum from removing old row versions, which is why the feature is off by default (max_prepared_transactions is 0). And many things you want inside the transaction cannot join it: a third-party payment API has no prepare call.
2PC on top of consensus
The weak point of 2PC is that the coordinator, and each participant, is a single machine. Spanner removed that weakness. Each shard is a group of replicas that agree on a log using Paxos (see consensus). A transaction that spans shards runs 2PC between the group leaders, and every prepare and commit record is written through the group’s replicated log.
If the coordinating leader dies, another replica in its group is elected, reads the decision from the log and carries on. The transaction blocks only if a group loses its majority. CockroachDB, YugabyteDB and TiDB layer 2PC over Raft groups in the same way.
The cost is latency. A cross-shard commit needs several rounds of replication, and if the replicas are in different regions each round is a wide-area round trip. Transactions that stay on one shard skip 2PC entirely, which is one more reason to choose the shard key well.
Why many teams avoid it
- Availability multiplies. The transaction succeeds only if every participant is up. Three services at 99.9% each give about 99.7% together.
- Locks are held across network round trips, so throughput drops and one slow participant slows everyone.
- It couples systems. Every participant must support prepare, trust the same coordinator and be reachable at the same time. Message brokers and external APIs usually cannot.
Choose a distributed transaction when an invariant truly needs atomicity and isolation, such as moving money between two accounts, and the participants are shards of one database that implements it for you. Avoid it across services owned by different teams, across different products, or for anything that includes a slow or external step. In those cases, restructure so that the data that must change together lives in one database, or use a saga with idempotent steps.
In the interview
Bring this up when one operation must change data in two places: two shards, two services, or a database and a queue. First ask whether the data can live together so that a local transaction is enough. If it cannot, explain 2PC in four words: prepare, vote, decide, commit. Then state its weakness precisely. A participant that has voted yes blocks, holding locks, until it learns the decision, so the coordinator must not be a single machine. Finish with a decision: a database with built-in distributed transactions for strict invariants, a saga for workflows across services.
Key takeaways
- Atomic commit means every participant commits or every participant aborts. Two commits issued one after the other cannot give you that.
- In two-phase commit a yes vote is a binding promise, and the coordinator writing its decision to disk is the commit point.
- A participant that has voted yes and has not heard the decision is in doubt. It must hold its locks and wait, which is why the protocol is called blocking.
- Three-phase commit avoids blocking only under timing assumptions that real networks break, so it is rarely used.
- Spanner-style databases run two-phase commit between consensus groups, so no single machine failure can strand a transaction.
- Distributed transactions cost availability, latency and coupling. Keep data that changes together in one place where you can, and use sagas across services.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What is atomic commit?
A guarantee that all participants in a transaction commit or all abort, even when machines crash and messages are lost. It says nothing about isolation.
What are the two phases of two-phase commit?
Prepare: each participant makes the transaction durable and votes yes or no. Commit: the coordinator logs the decision (commit only if all voted yes) and sends it to everyone until acknowledged.
What does "in doubt" mean?
A participant has voted yes but has not learned the decision. It can neither commit nor abort safely, so it holds its locks until the coordinator or a peer tells it the outcome.
Why is two-phase commit called a blocking protocol?
If the coordinator fails after participants vote yes, they must wait for it to recover, holding locks that stall other transactions.
What is XA?
The X/Open standard interface for two-phase commit between a transaction manager and resource managers such as databases and message brokers. PostgreSQL and MySQL both implement the resource side.
How does Spanner avoid a single point of failure in two-phase commit?
Each shard is a Paxos group. Two-phase commit runs between group leaders and every prepare and commit record goes through the replicated log, so a new leader can finish any transaction.