Concept · Consistency & coordination
Two-phase commit
Atomic commit across databases: prepare, then commit — and the coordinator that can block everyone.
Two-phase commit (2PC) makes a transaction atomic across several participants — databases or resource managers — so either all of them commit or none do.
The protocol
- Prepare. The coordinator asks every participant to prepare. Each one makes the transaction durable but not yet visible, takes the locks it needs, and votes yes (it guarantees it can commit) or no.
- Commit or abort. If all vote yes, the coordinator records the decision durably and tells everyone to commit. If any votes no or doesn't answer, it tells everyone to abort.
coordinator → A, B: PREPARE
A, B → coordinator: YES, YES
coordinator: write "commit" to its log
coordinator → A, B: COMMITPostgreSQL supports the participant side with PREPARE TRANSACTION and COMMIT PREPARED; the XA standard does the same across many databases and message brokers.
The blocking problem
After voting yes, a participant must wait for the coordinator's decision: it can't commit on its own (others might abort) or abort on its own (the coordinator might have decided commit). If the coordinator crashes at that point, prepared participants hold their locks until it recovers. A slow or dead coordinator stalls every participant.
Consensus-based commit (as in Spanner and CockroachDB) avoids this by replicating the coordinator's state itself, so another node can finish the decision.
Costs
- Extra round trips and durable writes per transaction.
- Locks held across the network for the duration of both phases, which limits throughput.
- Every participant must support the protocol — external services such as payment providers don't.
Alternatives
Between services, prefer sagas — local transactions with compensating actions — and the transactional outbox for reliable messaging (sagas, transactional outbox). Within one database, use ordinary transactions. Reach for 2PC only inside a system designed for it, such as a distributed SQL database that manages it for you.