Saga
- https://learn.microsoft.com/en-us/azure/architecture/patterns/saga
- Sequence of Local transactions
- Use events b/w microservices
- Assume a transaction has to happen involving 3 microservices with their own 3 different DBs
- For each microservice if the operations succeeds, it sends a success event to the next microservice
- If some microservice fails in Tx then failure event is sent back to previous microservices
- Failure event causes rollback of the operations (compensation Tx) done so far
- Concepts
- Compensating Tx
- a new Tx to undo changes of original Tx
- Pivot Tx:
- Point of no return
- Last undoable Tx
- First Retryable Tx
- Retryable Tx:
- Follow the Pivot Tx
- They are idempotent
- Help the saga eventually achieve a consistent state.
- Types of SAGA implementation
- Choreography
- Orchestrator
- Data Anomalies
- Lost Updates
- Dirty Reads
- Non-repeatable reads
- Use cases:
- Payment Systems
- debit from one account, credit to another, rollback on failure
- Flight Reservation
- reserve seat, charge payment, confirm booking; if payment fails → cancel seat
- Hotel Booking
- book room, charge payment, confirm; if cancel → refund & release room
Choreography
- exchange events without a centralized controller
- each local Tx publishes domain events that trigger local Tx in other services
Orchestrator
- A centralized controller, or orchestrator, handles all the Tx
- It tells the participants which operation to perform based on events
- It stores the states of each task, and handles failure recovery by using compensating transactions.
| Choreography | Orchestrator |
|---|
| Useful for simpler workflows | Better for complex workflows |
| No other service required for coordination | Separate Orchestrator required |
| No Single Point of failure | Introduces a single point of failure |
| Risk of cyclic dependency | Avoid cyclic dependencies |
Saga vs Two Phase Commit
| Two Phase Commit (2PC) | Saga |
|---|
| Coordination | Central Coordinator | Choreographed or Orchestrated |
| Communication | Sync | Async |
| Atomicity | Strong | Eventual Consistency, uses compensating Tx |
| Flexibility | Less Flexible | More Flexible |
| Performance | Slower, Participants wait | Faster, independent operations |