Want the details?
Why is this hard?
Inside one database, a transaction makes several changes happen all together or not at all. But payment, stock and shipping are separate services, each with its own database. No single transaction covers all three. If the third step fails after the first two succeeded, something must clean up, or the customer pays for nothing.
How to read the bench
| Part on the bench | What it means in a real system |
|---|---|
| Box at the left | The order service, which runs each order (the coordinator). |
| Three boxes at the right | Payment, stock and shipping services. |
| Ball | “Do your part” (or, in two-phase commit, “prepare your part”). |
| Flat tile | Commit or abort. A red tile is an undo (a compensating step). |
| Padlock | A service holding a prepared order locked. |
| Cards at the front | The last orders: dark shipped, white cancelled cleanly, red broken. |
The numbers
- A new order every 2 seconds. Each message takes 0.3 s; each service needs 0.4 s for its part.
- After 20 seconds: no plan with shipping down, 9 broken; saga with shipping down, 8 cancelled cleanly; saga when every third order cannot ship, 6 shipped and 2 cancelled; two-phase commit with everything working, 9 shipped.
- Coordinator crash at 3 s: all three services stay locked, and after 12 s, 12 requests wait with only 1 order shipped.
In real systems
- Sagas come in two styles. Orchestration: one service runs the steps and the undos, as here. Choreography: each service listens for events on a queue and reacts (“payment done” → stock reserves). Orchestration is easier to follow; choreography has no central point.
- Undos are new actions, not time travel: a refund is a new payment in the other direction, and it shows on the statement. Some steps cannot be undone (an email was sent), so put them last, or send a correction.
- Every step and every undo must be safe to repeat, because messages are retried. Use an idempotency key per order and step.
- The outbox pattern: a service must update its database and send “step done” together. Write the event into an outbox table in the same transaction, and let a separate process publish it. Otherwise a crash between the two loses the event.
- Two-phase commit is still used inside databases and some message brokers, where the coordinator is reliable and close. Across independent web services it is rare: it blocks when the coordinator fails, and it holds locks for a whole network round trip.
Words to know
- Saga
- A long business transaction made of small local ones, each with an undo.
- Compensating Transaction
- The undo of one saga step, such as a refund.
- Two-Phase Commit (2PC)
- Prepare everywhere, then commit everywhere; all or nothing, but blocking.
- Coordinator
- The one that runs the steps and decides commit or abort.
- Outbox
- A table where a service writes events in the same transaction as its data, to publish them reliably later.