Saga Pattern for Distributed Transactions

Keeping data consistent across services without a distributed lock: a chain of local transactions, each with a compensating step that undoes it if a later step fails.

Overview

A saga is a way to make a change that spans several services or databases without one big transaction. The change is split into a sequence of local transactions, each committed at once by the service that owns the data. If a later step fails, the saga runs compensating transactions for the steps that already committed, in reverse order, so the business ends up in a consistent state.

The idea comes from a 1987 paper by Hector Garcia-Molina and Kenneth Salem. They were solving long-lived transactions inside one database, which held locks for minutes or hours and blocked everything else. Microservices brought the idea back: each service owns its database, a distributed lock across them is slow and fragile, and many stores cannot take part in two-phase commit at all.

A saga trades isolation for availability. Each step is visible to others as soon as it commits, so other requests can see a half-finished saga. Designing a saga is mostly about handling that: choosing the order of steps, writing compensations that really undo the business effect, and delivering every step reliably.

What you will be able to do

  • Break a cross-service operation into steps, compensations and a point of no return.
  • Choose between choreography and orchestration, and explain the failure behavior of each.
  • Make every step reliable with an outbox, retries and idempotency.
  • Name the anomalies a saga allows and the countermeasures for each.

Key concepts

  • Local transactions
  • Compensating transactions
  • Backward and forward recovery
  • Compensable, pivot and retryable steps
  • Choreography
  • Orchestration
  • Transactional outbox
  • Idempotent steps
  • Missing isolation
  • Semantic locks

Interview questions

  • Design the saga for placing an order: payment, inventory and shipping.
  • Choreography or orchestration: how do you choose?
  • What does a saga give up compared with an ACID transaction?
  • Why must saga steps and compensations be idempotent?
  • What happens if a compensating transaction fails?
  • How do you make each saga step publish its event reliably?
  • How would you debug a saga that seems stuck?

Sign up free to read the full topic

More System Design topics

Start free on Cariara · Coding problems · System design studio