DEV Community

Said Olano
Said Olano

Posted on

Saga Pattern: Managing Distributed Transactions in Microservices

Saga Pattern: Distributed Transactions in Microservices

When a customer places an order in a microservices system, you need to:

  1. Reserve payment
  2. Update inventory
  3. Schedule shipment
  4. 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);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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

  1. Define compensations first - Know how to undo each step
  2. Ensure idempotency - Retries must be safe
  3. Monitor end-to-end - Track saga execution and failures
  4. Test failure scenarios - What if step 3 fails?
  5. 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)