A saga is a sequence of local transactions in which every completed step publishes an event or message that triggers the next one, and any failure produces compensating actions that undo the work already committed. The key condition: sagas don't give you atomicity, they give you a controlled, observable path back to a consistent state. In practice you implement one by classifying your business transaction's steps, choosing between choreography and orchestration, defining each step plus its compensation, and making step execution and message publication atomic with something like the transactional outbox. Everything else—idempotency, ordering, timeouts, and recovery—exists to keep that skeleton honest when messages get lost, duplicated, or delivered late.
The pattern matters because distributed transactions across modern services and databases are impractical: two-phase commit needs participants that hold locks and support the protocol, and it degrades badly when services span different stores or cloud boundaries. Sagas trade isolation for availability. That trade has a price you'll feel in production: intermediate states are visible to other readers, and compensation only semantically undoes a step—it can't un-send an email or un-charge a card without a refund path.
Classify your transaction's steps before you choose a coordination style
Start by writing down the business transaction as a sequence of local transactions, one per service. For each step, note three things:
The state change it commits (a row inserted, an inventory count decremented, a payment authorized). Whether it's reversible in business terms, not just technical ones. What a compensation would actually do (delete the order, increment inventory back, void or refund the authorization).
Steps fall into three practical buckets. Compensable steps happen early and can be undone (create order, reserve stock). Pivot steps are the point of no return—the transaction can't meaningfully be rolled back after them without manual intervention, because something external and irreversible happened (the carrier picked up the package, funds left the account). Retriable steps come after the pivot and can be retried until they succeed, because they're guaranteed to eventually work.
Design so that irreversible actions sit as late as possible. A common ordering is: create order (compensable) → reserve inventory (compensable) → authorize payment (compensable, since authorizations can be voided) → capture payment (often the pivot) → arrange shipment (retriable). If capture fails, you compensate backward: void the authorization, release inventory, cancel the order. This ordering minimizes the window in which you'd need a human to fix something.
Two properties you must accept up front: there is no isolation between saga steps, so other transactions can observe intermediate states, and compensation is not rollback. If you need stricter isolation, an alternative is to keep the transaction inside one service or one database. Sagas are the right tool when the work genuinely spans services and you can tolerate eventual consistency.
Choose choreography or orchestration—and know the failure mode of each
Choreography has no central coordinator. Each service listens for events and reacts: Order Service creates an order and publishes OrderCreated; Inventory Service reserves stock and publishes StockReserved; Payment Service listens and charges. Failure events travel the same way—PaymentFailed triggers Inventory to release stock and Order to cancel. It's simple for short flows and avoids a central bottleneck, but the flow is implicit. Nobody owns the end-to-end picture, and as you add steps the graph becomes hard to reason about, test, and debug. Cyclic dependencies between services are a warning sign.
Orchestration introduces a coordinator—a saga orchestrator—that tells each participant what to do and processes their replies. The orchestrator holds the state machine: which step is active, what has completed, what needs compensating. Participants stay dumb: they execute a command and reply. The cost is a new component to build, deploy, and monitor, plus a risk of centralizing too much business logic in the orchestrator.
| Criterion | Choreography | Orchestration |
|---|---|---|
| Coordination | No central component; services react to events | Central orchestrator drives each step |
| Coupling | Services coupled through event contracts | Services coupled to orchestrator commands/replies |
| Flow visibility | Emerges from event graph; hard to see end-to-end | Explicit in the orchestrator's state machine |
| Adding a step | Add a subscriber; risk of unintended fan-out | Add a step to the orchestrator; localized change |
| Debugging a stuck saga | Trace events across services | Inspect one saga instance's state |
| Testing | Needs integration tests across many services | Orchestrator logic unit-testable in isolation |
| Best fit | Short flows (2–4 steps), few participants, simple branching | Long flows, many participants, complex compensation |
A reasonable default for anything beyond three or four steps: orchestrate. The orchestrator's explicit state also gives you something choreography lacks—a single record of where each saga instance is, which is exactly what you need for recovery and support.
Define the saga's state machine and its compensations first
Before writing code, write the state machine. For each saga type, specify:
1: The ordered steps, each with the command it issues and the reply that advances the saga. 2: The compensation for each completed step, with the same participant. Compensation for step N must only run if step N actually completed—otherwise you'd compensate work that never happened. 3: Failure transitions from every active state, including compensations already in progress. 4: Terminal states: completed, compensated, and a distinct needs_review state for sagas that can't be compensated automatically. 5: Timeouts per step and what a timeout means (usually: retry a bounded number of times, then compensate or escalate).
Compensations run in reverse order and must themselves be idempotent and retriable. They can also fail; define a compensation-failure transition that stops automatic handling and flags the saga for human intervention rather than retrying forever. That stop condition is important: once a pivot step has happened and a later step irrecoverably fails, automated compensation may be impossible, and no amount of code should pretend otherwise.
Document the business meaning of each compensation alongside the technical call. "Delete the order row" is not the same as "cancel the order and notify the customer," and auditors or support staff will ask the difference.
Make step execution and message publication atomic with an outbox
The most common implementation bug in sagas: a service commits its local transaction, then publishes an event, and the publish fails. The database and the broker are now out of sync, and the saga stalls or double-executes. You can't fix this with a distributed transaction; you fix it with the transactional outbox pattern.
Within one local transaction, the service writes its business change and inserts the outgoing message into an outbox table in the same database. A separate relay process (a poller or a change-data-capture stream) reads the outbox and publishes messages to the broker, marking them sent. If the process crashes between commit and publish, the relay publishes on restart. If the relay publishes twice, consumers deduplicate. The transactional guarantee moves to the database, where it belongs.
Concretely:
1: Begin a local transaction. 2: Apply the business change (e.g., decrement inventory for the reservation). 3: Insert {message_id, aggregate_id, type, payload, created_at} into outbox. 4: Commit. 5: A relay publishes unsent outbox rows to the broker, at-least-once, marking them sent after acknowledgment.
Success check: kill the service between step 4 and step 5 and confirm the message still reaches the consumer after restart. A simple way to verify: temporarily stop the relay, perform the operation, confirm the outbox row exists, restart the relay, and confirm exactly-once processing downstream (delivery will be at-least-once; deduplication provides exactly-once effects).
If you use an orchestrator, the orchestrator's own state and its outgoing commands go through the same outbox mechanism. The orchestrator is a participant in the same discipline, not an exception to it.
Make every consumer idempotent and ordering-aware
At-least-once delivery is the realistic contract of most message brokers, so every step handler and every compensation must tolerate seeing the same message more than once. Standard approaches:
Business-key deduplication: store processed message IDs in a table (or an idempotency key tied to the business operation) in the same transaction as the state change, and reject duplicates. Natural idempotency: design operations so repeating them is harmless—set inventory to 42 rather than decrement inventory by 1, or a reservation record keyed by (saga_id, step) that only inserts once. Conditional updates: use compare-and-set semantics (UPDATE ... WHERE status = 'PENDING') so a duplicate no-op fails cleanly.
Ordering is separate. Most brokers guarantee order only within a partition, so route messages for one saga instance to the same partition using the saga ID as the partition key. Do not assume cross-saga ordering. Handlers should also validate that a command is applicable in the saga's current state—a late StockReserved arriving after the saga has already moved to compensation should be recognized as stale and acknowledged without effect, not blindly applied.
Timeouts belong here too. Each step request carries a deadline; the orchestrator treats an expired deadline as a failure and moves to compensation (or retries, if the step is retriable and hasn't hit its limit). Without deadlines, a lost reply means the saga waits forever.
Handle the hard cases: partial failure, compensation failure, and human review
A worked example makes the failure paths concrete. Consider an e-commerce order saga: create order → reserve stock → authorize payment → capture payment → create shipment. Suppose capture fails after a successful authorization.
The orchestrator marks capture as failed and transitions to compensation. It sends VoidAuthorization to Payment Service (idempotent, retried on transient errors). Payment acknowledges, and the orchestrator sends ReleaseStock to Inventory Service. Inventory acknowledges, and the orchestrator sends CancelOrder to Order Service. The saga reaches compensated.
Now suppose ReleaseStock fails because the Inventory Service is down past its retry budget. The orchestrator stops automatic compensation, marks the saga needs_review, and pages an operator with the full state: what completed, what was compensated, what remains. A support tool lets a person retry the compensation or resolve the inconsistency manually. This is the honest answer to "what if compensation fails?"—you surface it and stop, rather than pretending the system can always self-heal.
A second hard case: a late reply arrives for a step the saga already gave up on. The orchestrator must compare the reply's step and attempt number against its current state and discard stale replies. Without this, a late StockReserved after CancelOrder can leave a phantom reservation.
A third: the same saga being initiated twice (a retried client request). Deduplicate at the entry point using a client-supplied idempotency key or a business uniqueness constraint on the order ID, so you never run two sagas for one business transaction.
Operate and test sagas like production systems
Sagas are state machines living in a distributed system, so observability and testing deserve first-class treatment.
Observability. Give each saga instance a correlation ID and log every state transition with it. Expose counters for sagas started, completed, compensated, and in needs_review, plus per-step latency and failure rates. An alert on needs_review accumulating is often the first sign something downstream broke. For choreography, tracing across services replaces the missing orchestrator's view.
Testing. Unit-test the orchestrator's state machine exhaustively—every state, every failure transition, every compensation path—against in-memory participants. Then run integration tests with a real broker and fault injection: kill a service mid-step, drop replies, deliver duplicates, deliver out of order. Confirm each case leads to the correct terminal state and no orphaned records.
Idempotency audits. For each handler, write a test that invokes it twice with the same message and asserts one effect.
Timeouts and retries. Verify that a step with no reply eventually compensates, and that retriable steps exhaust their budget and escalate.
Reconciliation. Some teams run a periodic job that scans for sagas stuck in a non-terminal state beyond an expected duration and flags them, catching bugs that fault-injection tests missed.
A practical implementation sequence
If you're starting from scratch, work in this order—each step depends on the previous:
1: Write the business transaction's step list with compensations and identify the pivot step. This is a design task, not a coding one, and it determines everything else. 2: Implement the transactional outbox and an idempotent consumer base in each participating service. Do this before the saga logic; it's infrastructure the saga stands on. 3: Choose choreography or orchestration using the criteria above (orchestration for anything with more than a few steps or complex compensation). 4: Implement the saga state machine, with explicit states for completed, compensated, and needs_review, plus per-step timeouts. 5: Implement each participant's command handler and compensation handler, idempotent and keyed by saga ID. 6: Add correlation-ID logging, per-state metrics, and an alert on needs_review. 7: Exercise failure paths in integration tests with fault injection, including duplicate and out-of-order delivery. 8: Build a small operator tool to inspect, retry, and manually compensate stuck sagas before you need it.
Expected result: a business transaction that either completes every step or reaches a consistent compensated (or flagged) state, with no step silently lost. The check: for every failure you can induce in testing, the saga ends in a defined terminal or review state and leaves no partial data unexplained. If a failure produces an undefined state or silent data loss, the outbox, idempotency, or state machine needs fixing—not more retries.
The limits worth internalizing
Sagas are a coordination pattern, not a consistency guarantee. They give you eventual consistency and forward recovery at the cost of visibility into intermediate states and the constant possibility of human review. They don't fit transactions that need strict isolation or that span an irreversible external action with no compensation path; for those, redesign the boundary so the irreversible part sits alone or accept manual reconciliation. And the pattern's real cost is operational: the outbox, idempotency, ordering, timeouts, and observability you build around it are most of the work. Build those primitives first, and the saga itself becomes a readable state machine over reliable parts.