Distributed transactions and sagas
Two-phase commit, why it blocks, and how sagas with compensations keep multi-service workflows correct.
22 min readTwo-phase commit
When one business action must update data owned by several databases atomically, two-phase commit (2PC) uses a coordinator. Phase one: the coordinator asks every participant to prepare, and each durably promises it can commit while holding its locks. Phase two: if all voted yes, the coordinator tells everyone to commit; otherwise to abort. It gives atomicity across stores, but the cost is real: at least two round trips plus forced disk writes, and locks held for the whole duration.
Why 2PC blocks
If the coordinator crashes after participants have prepared, they cannot decide on their own: committing might violate an abort, and aborting might violate a commit. They hold their locks until the coordinator recovers, which can block unrelated requests on those rows for minutes. Systems like Spanner make 2PC practical by running each participant and the coordinator as a replicated Raft group, so no single crash stalls it. Across independently owned microservices, 2PC is usually a poor fit.
Sagas
A saga splits a long business transaction into local transactions, each committed independently, with a compensating action for each step that semantically undoes it. Booking a trip: reserve flight, reserve hotel, charge card. If the charge fails, run cancel-hotel and then cancel-flight. Intermediate states are visible to others, so design them explicitly: a booking in PENDING state, a seat held for 10 minutes.
- Orchestration: a central workflow service drives steps and compensations; easy to see and monitor
- Choreography: each service reacts to events from the previous one; loosely coupled but harder to trace
- Compensations must be idempotent and retryable, because they will run after partial failures
Making sagas reliable
A service that updates its database and then publishes an event can crash between the two, losing the event. The transactional outbox fixes this: write the event into an outbox table in the same local transaction as the state change, and have a relay (or change data capture) publish it to the stream. On the canvas this is a sql component feeding a stream through a worker; the Feedback panel will flag designs that publish events outside the write path as able to lose messages.
Key takeaways
- 2PC gives atomic commits across stores but holds locks and blocks if the coordinator fails
- Sagas chain local transactions with compensating actions instead of global locks
- Model intermediate states explicitly, such as PENDING bookings and timed holds
- Use the transactional outbox so state changes and their events cannot diverge
Sign in to track lessons and earn badges.