Video in progress
What is the saga pattern?
A saga splits a business operation that touches several services into a sequence of local transactions. Each step commits in its own database; if one step fails, the earlier steps are undone with compensating operations.
📖 Answer
In the order example:
1. order: create the order (PENDING) | undo: set it to CANCELLED
2. payment: charge the money | undo: refund the money
3. inventory: reserve the goods | undo: release the reservation
4. order: set the order to CONFIRMED
If step 3 fails with "not enough stock", the saga walks backward: first the money is refunded, then the order becomes CANCELLED.
There are two ways to coordinate a saga:
- choreography: no center, services respond to each other's events;
- orchestration: a separate orchestrator gives the commands: "now payment, now warehouse".
An important difference: a saga is not an ACID transaction. Intermediate states are visible to others, for example the money has been charged but the order isn't confirmed yet. That's why you need states like PENDING and a message in the UI like "your order is being processed".
Sign up to mark studied questions and save your progress.