
An order service can reserve stock, charge a card, and create a shipment without sharing one database transaction. The Saga pattern turns that business transaction into a sequence of local commits and compensating actions, so a partial failure has a defined recovery path. Continue from distributed transactions, idempotent APIs, and webhook delivery.
Table of Contents
Open Table of Contents
What a Saga Guarantees
A saga is a workflow of local transactions. Each step commits in its own service; if a later step fails, the workflow invokes business-specific compensations for completed steps. Compensation is not a database rollback: sending an email cannot be unsent, so the business may issue a refund or mark the order for review.
flowchart TD
A[Create order] --> B[Reserve inventory]
B --> C[Authorize payment]
C --> D[Create shipment]
D --> E[Order confirmed]
C -. failure .-> F[Release inventory]
D -. failure .-> G[Refund payment]
G --> F
Define a state machine before writing code. Persist the current step, attempt number, correlation ID, and compensation status so a worker can resume after a crash without guessing what happened.
Orchestration vs Choreography
An orchestrator sends commands and records transitions. It gives operators one place to see progress and makes ordering explicit, but the orchestrator becomes a dependency and must be highly available. Choreography has services react to events; it removes the central coordinator but makes the workflow harder to visualize and can create accidental event cycles.
Use orchestration for five or more steps, strict ordering, or explicit compensation. Choreography fits short flows where each service owns a clear event and teams can enforce event contracts. In both styles, use an outbox to publish a committed state change atomically with the local database write.
Compensation and Idempotency
Every command needs an idempotency key such as sagaId:stepName. A retried reserve-inventory must return the original reservation rather than decrementing stock again. Compensation also needs an idempotency key because timeouts make it possible for the caller to retry after the remote service already succeeded.
Compensation order is normally the reverse dependency order, but not always. A shipping label may incur a fee, so the business action could be a refund request rather than deletion. Keep irreversible steps late, expose PENDING_COMPENSATION to clients, and send exhausted failures to a review queue.
Reliable Implementation
type Step = {
name: string;
run: () => Promise<void>;
compensate: () => Promise<void>;
};
async function runSaga(steps: Step[]) {
const completed: Step[] = [];
try {
for (const step of steps) {
await recordStep(step.name, "STARTED");
await step.run();
completed.push(step);
await recordStep(step.name, "COMPLETED");
}
} catch (error) {
for (const step of completed.reverse()) {
await retryIdempotently(
() => step.compensate(),
`${step.name}:compensate`
);
}
await markSagaFailed(error);
throw error;
}
}
The durable recordStep writes are the difference between a resumable workflow and an in-memory script. Add timeouts, bounded retries with jitter, a dead-letter queue, and metrics for duration by step and compensation age.
Interview Questions
1. How is a saga different from two-phase commit?
A saga commits each local transaction independently and repairs business state with compensations. Two-phase commit keeps participants prepared until one global commit decision, which provides atomicity but holds locks and can block. Sagas improve availability and autonomy at the cost of temporary inconsistency and more application logic.
2. What if a compensation fails?
Persist the failure, retry with backoff, and move exhausted work to a durable operator queue. The workflow should expose a recoverable state rather than claiming success. Operators need a safe replay command that preserves the same idempotency key.
3. When should you choose choreography?
Choose it for a small, stable workflow where events already represent the business boundaries. Avoid it when the flow has many branches or compensation rules; those become hidden in event handlers and are difficult to audit. A hybrid can keep local reactions while an orchestrator tracks the global state.
4. How do you prevent duplicate side effects?
Use an idempotency key at every command boundary, store the first result, and enforce a unique constraint on the key. Consumers should acknowledge a duplicate only after confirming the original result. This protects against retries, redeliveries, and orchestrator failover.
5. Can a saga provide strict atomicity?
No; between local commits, other readers may observe intermediate state. If strict atomicity is a legal or financial requirement, keep the invariant in one transactional boundary or use a protocol designed for that guarantee. Otherwise, design explicit statuses and reconciliation.
Conclusion
The Saga pattern is a workflow and recovery design, not a generic “event-driven” label. Choose orchestration or choreography deliberately, persist every transition, make commands and compensations idempotent, and put irreversible work late. The quality of the compensation path determines whether the system is actually reliable.
References
- AWS: Saga orchestration pattern
- Microsoft: Saga distributed transactions pattern
- microservices.io: Saga pattern
YouTube Videos
- “Distributed Transactions, 2PC and Saga Pattern” - Gaurav Sen [https://www.youtube.com/watch?v=DOFflggE_0Q]