Advanced Concepts · Concept lesson
Distributed Workflows: Sagas, Compensation, and Durable Progress
Coordinate business work across services with explicit state, bounded retries, and honest compensation rather than pretending there is one global transaction.
Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.
Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.
What you will be able to explain
- Model a multi-service workflow as durable, observable state transitions.
- Distinguish forward retry, compensation, and human resolution.
- Choose orchestration or choreography based on ownership and visibility.
A workflow is a durable business state machine
When a customer operation spans multiple services, each service owns its database and can commit only its own transaction. A global ACID transaction would require all participants to remain available and coordinate locks or a commit protocol; many modern service boundaries deliberately avoid that dependency. A saga accepts that local commits happen at different times. It gives the overall business operation a durable identity and explicit states such as `requested`, `inventory_reserved`, `payment_authorized`, `shipment_created`, and `completed`. If a later step fails, the workflow may retry, take a compensating action, or stop for an operator. This is not merely a chain of HTTP requests. The state must survive process restart, and every transition needs a clear owner, timeout, and recovery rule. The user-facing state should also be honest: 'processing' is not the same as 'complete.'
Compensation deserves especially careful language. If a hotel reservation is made and later canceled, the cancellation is another business event and may incur a fee; it does not erase the reservation from history. A refund may fail or arrive later than the original charge. Some actions, such as sending a message or revealing information, cannot be undone at all. For each step, ask whether failure means retrying that step is safe, whether an explicit inverse exists, or whether the workflow must ask a human to resolve an ambiguity. Persist enough evidence to explain the final outcome without treating a saga log as an unbounded copy of sensitive payloads. A workflow is correct when its permitted terminal states match domain rules, not when every path ends with a green check.
Persist intent before making the next remote call
An orchestrator typically loads a workflow record, validates its expected state and version, records a step intent, then dispatches a command through a durable outbox. The remote service handles the command idempotently and returns a result containing the workflow and step IDs. The orchestrator records the result and advances only if it still owns the expected version. This protects against duplicate callbacks, delayed replies, and two workers racing the same workflow. Leases help workers divide processing, but a lease can expire while a slow worker is still running; a fencing token or compare-and-swap version prevents the old worker from overwriting newer state. Never hold a database lock while waiting on a remote network call. That converts remote slowness into lock contention and can make unrelated user operations fail.
For each step record the command ID, attempt number, deadline, last classified error, and any remote idempotency key. A timeout is ambiguous: the remote participant may have committed even though the response did not arrive. Query by stable command ID or retry idempotently rather than assuming failure. Store a workflow definition version so an in-flight workflow is not silently interpreted by incompatible new code. Migration can route old executions through their original definition, or apply an explicit state migration with audit evidence. Define terminal and operator-owned states, such as `needs_review`, rather than retrying forever. Workflow state retention should match audit, privacy, and recovery requirements; full request bodies can be stored separately with access controls and expiration.
An order workflow with explicit arithmetic and boundaries
Consider checkout with four independent steps: reserve inventory, authorize payment, create shipment, and send confirmation. Suppose each remote action has a 99.9% probability of succeeding on its first attempt in a given time window. Under the simplifying and often false assumption of independent failures, the chance all four succeed on the first attempt is 0.999⁴, approximately 99.60%. That does not mean 0.4% of customers lose an order: durable retry and compensation improve completion, but they add time and partial states. Give each step a 3-second timeout and the entire user-visible pending phase a 20-second budget; a 3-second call repeated with unbounded backoff can violate the business deadline. Inventory reservation may expire after 15 minutes. The workflow must decide whether to release it, retry payment, or request operator action before expiry.
If shipment creation fails after payment authorization, first query the shipping provider using the original idempotency key. If the provider confirms no shipment, retry within the deadline. If it confirms shipment but the reply was lost, record success and continue. If the answer remains unknown, do not immediately release inventory and issue a second order; place the workflow in `needs_review` and reconcile. If no shipment can be created, void the payment authorization, which is a compensating step and can itself fail. The customer should see a pending or refunded state only after the corresponding evidence exists. Dashboard age of each in-flight state, retry count, compensation failure, and manual-review queue age. Overall workflow success alone hides which dependency causes long partial completion.
Workflow ID and version are durably created.
Participant handles a stable command ID.
Timeout is ambiguous; query or retry idempotently.
Shipment success advances the order.
A new action; its own outcome is recorded.
Operator reconciles unknown external state.
Customer-facing terminal state has evidence.
- Order requested → Reserve stock: durable command
- Reserve stock → Authorize payment: confirmed
- Authorize payment → Create shipment: authorized
- Create shipment → Completed: confirmed
- Authorize payment → Void authorization: permanent shipment failure
- Void authorization → Needs review: void outcome unclear
- Authorize payment → Needs review: timeout cannot be reconciled
Orchestration and choreography solve different coordination problems
Orchestration centralizes the sequence in a workflow engine or application service. It provides a visible state history, deadlines, and a place to decide compensation. This is useful when a business process has conditional branches, human approval, or a long lifetime. The cost is a central component that must be highly available, versioned, and owned; poor orchestration can become a giant service that knows every domain detail. Choreography lets services react to events and publish their own outcomes. It can reduce a central bottleneck and preserve local ownership, but the path can become difficult to reconstruct when many listeners trigger one another. A new consumer may accidentally change the process, and teams can disagree about who owns an incomplete operation.
A short, stable sequence with clear domain ownership may fit a simple application-level coordinator. A long-running process with waits and human actions may justify a managed workflow engine, after checking its execution history limits, retry semantics, regional availability, and cost. A saga should not be used to fake a strongly consistent invariant across services if the business cannot tolerate temporary inconsistency. In that case, keep the invariant within one service and one transaction, or redesign the domain boundary. Do not split one table into several services just because a diagram depicts independent boxes. Distributed workflow tooling makes partial failure visible; it does not make partial failure disappear.
Timeouts, late messages, and compensation failure
A late response must not blindly move a workflow backward. Suppose a payment authorization times out, the workflow starts compensation, then a delayed authorization-success message arrives. Use expected state and step generation in every callback; store late results for reconciliation and decide whether to void the authorization. A callback for an old workflow version should be recorded but not applied to the current state without validation. Duplicate callback delivery is expected, so each transition has an idempotency key and version guard. Retry transient errors with bounded exponential delay and jitter, but do not retry permanent validation errors. Circuit breaking may stop new attempts while preserving the durable step intent. Set an overall deadline so automated recovery eventually yields to an explicit business or operator decision.
Compensation can fail because the same dependency is down, because the external action is irreversible, or because state is unclear. Model compensation as its own retryable step with its own status, evidence, and alert. Never mark an order 'canceled' merely because a cancellation command was sent; wait for confirmation or label it `cancel_pending`. Reconciliation compares workflow records with participant state using stable IDs and a limited time window, then reports discrepancies for controlled repair. A runbook should identify which team can authorize a refund, release inventory, or declare an external provider action final. Test crashes between state persistence and command dispatch, duplicate and out-of-order callbacks, orchestrator failover, definition rollout, and compensation outage. These tests expose the actual hard parts better than testing only the happy path.
When a saga is the wrong consistency model
A saga is not appropriate if temporary partial state violates law, safety, or a core financial invariant. Two account balances that must never create money cannot be updated independently and later 'compensated' without a carefully designed ledger model. For monetary transfer, an append-only double-entry ledger and explicit pending/settled states may preserve the invariant more reliably than two mutable balance writes. Likewise, do not make a workflow durable merely to coordinate two operations that can safely share one database transaction. Local atomicity is simpler and has fewer recovery states. If a customer action needs an immediate yes-or-no answer, a long asynchronous process may be a poor user contract; either return an accurate pending status or keep the operation narrow enough to complete synchronously.
Avoid choreography if an operator cannot tell why a customer is stuck after several events crossed team boundaries. Avoid central orchestration when one team must not own domain decisions that belong to another bounded context. A workflow engine is not a place to copy all business data for convenience; retain references and minimal transition facts. If compensation is not truly reversible, name it as a new corrective action and account for its possible failure. Strong consistency, availability, and independent ownership cannot all be obtained simply by adding retries. State which requirement wins for each operation and make the partial states visible to both customers and responders.
Senior questions for workflow design
Ask for the state machine before reviewing technology. Which states are externally visible, which transitions are legal, and what durable evidence authorizes each one? What is the workflow's unique identity, how are commands deduplicated at participants, and how are stale workers fenced? For every remote timeout, can the participant be queried by idempotency key? Which actions are reversible, compensatable, or irreversible? Who owns a failed compensation and how quickly will the system surface it? The answer should identify a bounded automated recovery window and a human escalation point, not just say 'retry until it works.'
Then challenge failure behavior and operational capacity. What fraction of workflows may remain pending during a dependency outage, and how does that consume connection pools, locks, workflow storage, or provider quota? How will a new workflow definition coexist with executions created before deployment? Can operators safely replay a step without repeating a charge? Is the audit trail access-controlled, privacy-minimized, and retained only as long as needed? Does a dashboard show transition age and compensation failure, not just throughput? What alternative keeps the invariant in one service, and why is that insufficient? Senior reasoning makes the business meaning of partial completion explicit and tests recovery across a full process restart.
Terms in plain language
- Saga
- A sequence of local transactions with defined recovery actions when a later step cannot complete.
- Compensation
- A new business action that offsets an earlier effect where possible; it is not a rollback of history.
- Workflow orchestrator
- A component that persists workflow state and directs steps, deadlines, and recovery.
References and boundaries
Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.
Primary AWS guidance on orchestrated saga steps and compensating transactions.
Primary workflow-engine documentation describing durable workflow execution; product behavior is not a substitute for domain compensation design.