In this lesson · topic 1 of 7
Topic 1
An order that spans four services
3 min read
The order
Placing an order reserves stock, charges a card, books a courier and sends a confirmation. Each of those lives in a different service with its own database. There is no single transaction around all four.
Two-phase commit could wrap them. It would hold a lock in every service for the whole order, wait on the slowest one, and block when its coordinator died. A payment provider cannot take part in it at all.
What a saga does instead
A saga commits each step on its own, at once. Locks are held for one step, not for the whole order. If a later step fails, the saga does not roll back. It runs a new action that cancels the old one. A charge is followed by a refund.
That works because each step has a compensating action. The cost is that the middle of the saga is visible. Someone can see the charge before the refund. A saga is atomic in the end and not isolated on the way.
Failure grows with length
Every step is another chance to fail. If each of four steps fails 8 percent of the time, a saga needs no compensation 72%measured of the time. With eight steps it is 51%measured. Compensation is a normal path here, not a corner case.
Predict first