Saga Pattern
Sequence of local transactions with compensation. No distributed locks, better scalability.
Problem: How to maintain consistency across multiple services?
Traditional solution: 2PC (Two-Phase Commit) - but it’s:
Solution: Saga Pattern - Sequence of local transactions with compensation!
The Saga pattern is a distributed transaction management pattern that breaks a long-running transaction into a sequence of smaller, local transactions. Each local transaction commits independently, and if any step fails, the saga executes compensating transactions to undo the effects of previously completed steps.
Unlike traditional ACID transactions that use two-phase commit (2PC) to ensure atomicity across services, sagas use eventual consistency. Each step in a saga is a local ACID transaction within a single service. If a step fails, instead of rolling back (which isn’t possible across services), the saga executes compensating actions in reverse order.
Key Insight: You can’t “rollback” a committed transaction in another service (the flight is already booked), but you can compensate (cancel the flight). Compensation is not the same as rollback - it’s a new business operation that undoes the effect of a previous operation.
Central coordinator orchestrates all steps.
Characteristics:
Distributed coordination. Each service knows next step.
Characteristics:
| Aspect | Orchestrator | Choreography |
|---|---|---|
| Control | Centralized | Distributed |
| Complexity | Lower | Higher |
| Coupling | Higher | Lower |
| Debugging | Easier | Harder |
| Scalability | Lower | Higher |
| Use Case | Complex workflows | Simple workflows |
Choose Orchestrator when:
Choose Choreography when:
Undo the action (if possible):
Opposite transaction:
Automatic expiration:
Saga Pattern
Sequence of local transactions with compensation. No distributed locks, better scalability.
Orchestrator
Central coordinator. Easier to understand and debug. Good for complex workflows.
Choreography
Distributed coordination. More decoupled and scalable. Good for simple workflows.
Compensation
Undo completed steps when saga fails. Not rollback, but compensating action. Critical for consistency.