Simple definition#
A saga is a sequence of local transactions, one per service. If a step fails, the saga runs compensating transactions to semantically undo the steps that already succeeded. It replaces one big distributed transaction with steps that are each atomic, plus an explicit undo plan.
The problem#
Placing an order touches the order, payment, inventory and shipping services, each with its own database. 2PC is not an option (see distributed transactions). Without a pattern, a failure halfway through leaves money taken with no stock reserved, or stock held for an order that was never paid.
Anatomy of a saga#
| Step type | Meaning | Example |
|---|---|---|
| Compensatable | Can be undone by a compensating transaction | Reserve stock (release stock) |
| Pivot | The point of no return: after it, the saga must complete | Capture payment, ship goods |
| Retriable | After the pivot; must eventually succeed, so retry until it does | Send confirmation, update loyalty points |
Order your steps so that compensatable steps come first, then the pivot, then retriable steps.
Choreography#
Each service listens for events and publishes its own.
sequenceDiagram
participant O as Order
participant P as Payment
participant I as Inventory
O->>P: OrderCreated (event)
P->>I: PaymentAuthorised (event)
I-->>P: StockReservationFailed (event)
P-->>O: PaymentVoided (event)
O->>O: mark order REJECTED
- Pros: no central coordinator; loose coupling; simple for 2–4 steps.
- Cons: the flow is implicit and spread across services, so it is hard to see the state of one order. Cyclic dependencies and “who compensates what” get messy as steps grow.
Orchestration#
An orchestrator owns the saga state and sends commands to each participant.
- Pros: an explicit, testable flow; one place for timeouts, retries and compensation; easy to see “where is order 42?”; audit-friendly.
- Cons: the orchestrator is an extra component that must be durable and highly available, and logic can creep into it. Keep business rules in the participants.
The saga as a state machine#
Persist the saga state before each step. A crash then resumes from the last durable state instead of starting over or forgetting.
Durable execution engines#
Writing a reliable orchestrator yourself (state persistence, timers, retries, versioning) is hard. Durable execution platforms do it for you:
| Tool | Model |
|---|---|
| Temporal (and Cadence) | Workflows as code (Java, Go, TypeScript, Python, .NET). Event-sourced history, automatic retries, timers, signals. |
| Camunda 8 / Zeebe | BPMN models; good when business analysts own the process |
| AWS Step Functions, Azure Durable Functions, Google Workflows | Managed state machines |
| Restate, DBOS | Lightweight durable execution embedded in services or the database |
| Axon, Eventuate Tram | Saga frameworks for event-driven Java |
// Temporal (Java): saga with compensation
public class OrderWorkflowImpl implements OrderWorkflow {
private final Activities act = Workflow.newActivityStub(Activities.class,
ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(30))
.setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(5).build()).build());
public OrderResult placeOrder(Order order) {
Saga saga = new Saga(new Saga.Options.Builder().build());
try {
act.createOrder(order); saga.addCompensation(act::rejectOrder, order.id());
act.authorisePayment(order); saga.addCompensation(act::voidPayment, order.id());
act.reserveStock(order); saga.addCompensation(act::releaseStock, order.id());
act.capturePayment(order); // pivot: no compensation after this point
act.bookShipment(order); // retriable: retries until it succeeds
return OrderResult.completed(order.id());
} catch (ActivityFailure e) {
saga.compensate(); // runs compensations in reverse order
return OrderResult.rejected(order.id(), e.getMessage());
}
}
}
Isolation: the anomalies sagas allow#
Sagas give up the “I” in ACID. Other transactions can see intermediate states:
| Anomaly | Example | Countermeasure |
|---|---|---|
| Dirty read | Another service reads an order that will be rejected | Semantic lock: a PENDING status that readers respect |
| Lost update | A compensation overwrites a concurrent change | Commutative updates (debit/credit, not “set balance”), versioning |
| Non-repeatable read | Price changes between steps | Reread value, or pass the snapshot in the command |
| Ordering | Cancel arrives before create | Handle empty compensation; idempotent, order-tolerant handlers |
Making sagas reliable#
- Every command and event goes through an outbox. Every participant is idempotent.
- Every step has a timeout. “No answer” is a state you handle.
- Compensations must be idempotent and retriable, and must eventually succeed. If they cannot, go to manual review with an alert.
- Put a saga ID and correlation ID on every message, and trace them with OpenTelemetry.
- Test failure at every step, including double delivery and out-of-order events. Durable execution frameworks offer replay and time-skipping tests.
Common mistakes#
Quick check#
What is a compensating transaction? A new business action that semantically undoes an earlier step, such as a refund or a stock release. It is not a database rollback.
What is a pivot transaction? The point of no return in a saga. After it, the remaining steps must be retried until they succeed.
Choreography vs orchestration in one sentence each? In choreography, services react to each other’s events with no coordinator. In orchestration, a central coordinator commands each step and tracks state.
Which ACID property do sagas give up, and how do you mitigate that? Isolation. Mitigate it with semantic locks (pending states), commutative updates, versioning and rereading values.
Why use Temporal or a similar engine? It provides durable state, retries, timers and history, so the orchestrator survives crashes without custom infrastructure.
Summary#
- A saga is local transactions plus compensations. Order the steps: compensatable, then the pivot, then retriable.
- Choreograph short flows; orchestrate long business processes.
- Persist state, time out every step, and make everything idempotent.
- Handle the missing isolation with semantic locks and commutative updates.
References#
- Hector Garcia-Molina and Kenneth Salem, Sagas (1987).
- Chris Richardson, Pattern: Saga.
- Temporal, Saga pattern documentation.
- Microsoft, Saga distributed transactions pattern.