DEV Community

Cover image for The Saga Pattern
Gurudev Devops
Gurudev Devops

Posted on

The Saga Pattern

What Is the Saga Pattern?

A saga consists of multiple local transactions, each executed by a different service. After each completes, an event or message triggers the next. If any step fails, previously-completed steps are compensated via rollback actions, rather than undone via centralized rollback.

This approach suits systems with:

  • Independent databases per service
  • Long-running workflows
  • Need for eventual consistency without service-wide locking

Saga Coordination Styles

  1. Choreography (Event-Driven)
    Each service listens for events (e.g. “OrderCreated”) and autonomously acts, emitting the next event.
    Pros: Decoupled, minimal central coordination
    Cons: Harder to trace and debug complex flows

  2. Orchestration (Coordinator)
    A central orchestrator directs each step, sending commands and invoking compensations if needed (e.g., “reserveCredit”, “refundPayment”).

Pros: Easier monitoring, more control over flow
Cons: Orchestrator becomes complex, single point to scale

Benefits & Tradeoffs

Benefits

  • Avoids distributed transactions
  • Service autonomy & resilience
  • High availability & eventual consistency

Tradeoffs

  • Must design compensating logic manually
  • Saga complexity increases with steps
  • Non-isolation can lead to anomalies

Key Concepts & Patterns

  • Compensating Transactions: Undo operations—e.g. refund payment, restock items
  • Pivot Step: A point of no return after which steps can’t be compensated
  • Saga Log / State Machine: Tracks progress, supports retries and recovery after crashes
  • Idempotency: Essential for handlers to avoid double execution during retries

Implementation Tips

  • Prefer orchestration for complex sagas, choreography for simple flows
  • Use asynchronous messaging (Kafka, RabbitMQ) for decoupled flows
  • Ensure atomic write-and-publish, via outbox or transaction logs
  • Implement saga recovery: persisting state allows safe retries

Real-world Use Cases

  • E-commerce workflows (order → pay → ship)
  • Trip planning (flight, hotel, car rental), cancel all if one fails
  • Financial processes (loan approval, disbursement) with rollback

Tools & Frameworks

AWS Step Functions: Serverless saga orchestration

By using the Saga Pattern, you embrace resilience, scalability, and eventual consistency across your microservices—managing complex distributed workflows without locking to a single global transaction.

Top comments (0)