Saga Pattern: Distributed Transactions in Microservices
When a customer places an order in a microservices system, you need to:
- Reserve payment
- Update inventory
- Schedule shipment
- Send confirmation
In a monolith, you'd use a database transaction: all-or-nothing.
In microservices, each step is a separate service. The Saga pattern orchestrates these steps, with compensating transactions that undo previous steps if later ones fail.
Two Patterns
Orchestration
A saga orchestrator directs each service in sequence.
- Pros: Centralized control, easy to understand
- Cons: Tight coupling, orchestrator is bottleneck
Choreography
Services communicate through events.
- Pros: Loose coupling, scales well
- Cons: Hard to debug, complex error handling
Key Principles
- ✅ Compensating Transactions: Undo steps in reverse order
- ✅ Idempotency: Same request = same result
- ✅ Eventual Consistency: Not all steps succeed immediately
- ✅ Failure Handling: Plan for compensation failures
Implementation
Orchestration (Java)
@Service
public class OrderSagaOrchestrator {
public void execute(OrderCommand cmd) {
try {
paymentService.reserve(cmd);
inventoryService.reserve(cmd);
shipmentService.schedule(cmd);
emailService.send(cmd);
} catch (Exception e) {
// Compensate in reverse
shipmentService.cancel(cmd);
inventoryService.release(cmd);
paymentService.refund(cmd);
}
}
}
Choreography (Kafka)
Services listen to events and publish new events:
- Order Service publishes OrderCreated
- Payment Service listens, reserves payment, publishes PaymentReserved
- Inventory Service listens, reserves stock, publishes InventoryReserved
- Shipment Service listens, schedules shipment
If any step fails, compensating events trigger rollbacks.
Tools
- Axon Framework (event sourcing + sagas)
- Apache Camel (choreography)
- Temporal (workflow engine)
- AWS Step Functions (serverless)
Best Practices
- Define compensations first - Know how to undo each step
- Ensure idempotency - Retries must be safe
- Monitor end-to-end - Track saga execution and failures
- Test failure scenarios - What if step 3 fails?
- Handle compensation failures - What if compensation fails?
Read the full article for real-world examples (airline bookings), failure scenarios, and distributed tracing patterns.
Top comments (0)