Distributed Transactions and Two-Phase Commit
Distributed transactions coordinate a decision across participants; two-phase commit can block when the coordinator or required participants are unavailable.
Distributed Transactions and Two-Phase Commit
Distributed transactions coordinate a decision across participants; two-phase commit can block when the coordinator or required participants are unavailable. During prepare, a coordinator asks participants to durably promise they can commit and retain required locks/state. During commit, it records and broadcasts the decision. Participants recover using the durable coordinator decision. Consensus-backed transaction protocols can replicate the decision log. A saga instead uses independent local commits and compensating business actions.
Mechanism and worked example
A transfer across two database shards may prepare debit and credit participants, then commit both after the coordinator's durable decision. If the coordinator fails after participants prepare, they may hold resources while recovering the decision. A timeout does not imply abort.
| Approach | Guarantee | Failure behavior |
|---|---|---|
| 2PC | Atomic commit decision across participants | May block while decision is unavailable |
| Consensus-backed commit | Replicated decision authority | Requires quorum |
| Saga | Eventual business recovery | Compensation can fail or be delayed |
| Outbox | Atomic local state plus event intent | Delivery may duplicate |
Failure modes and operations
Prepared participants can block while coordinator decision is unavailable. Network partitions can delay progress. Heuristic decisions can create inconsistency. External APIs rarely participate in a database's 2PC transaction. Holding locks across a distributed round trip raises contention.
Trade-offs and design boundary
2PC offers atomic commit under protocol assumptions but can block and increases coordination cost. Sagas improve availability through forward recovery and compensation but do not provide atomic isolation. Use a distributed transaction only when participants and operational guarantees justify it.
Interview transfer exercise
Compare 2PC and saga for a wallet transfer spanning two independently owned services. State whether atomic visibility is required, what participants support, and how unknown outcomes recover.
Read the diagram
Coordinator durably records transaction intent → Participants prepare and hold required state → Coordinator records commit or abort decision → Participants recover and apply durable decision