Temporal saga pattern for distributed transactions

A saga in Temporal gives you compensating steps that run in reverse when a later step fails, but it does not give you atomicity across systems. This page covers how to design, build and verify one.

On this page

When a Temporal saga pattern fits a distributed transaction

A saga fits when one business operation touches several services or databases that cannot share a single transaction, and a failure partway through leaves effects that must be undone. Typical examples include reserving inventory, charging a payment, and creating a shipment, where each step commits in its own system. If the payment succeeds and the shipment call fails, the system cannot roll back with a database rollback. It needs a planned way to reverse the completed steps. In Temporal, the workflow code is where that plan lives: after each step succeeds, the code records a matching compensating action, so that a later failure can run those actions in reverse order. Because Temporal persists the workflow's progress, the compensation plan survives worker restarts and retries without being rebuilt from logs.

A single database transaction is the better choice when all the writes sit in one database that can commit or roll back together. A plain retry loop is enough when a step is safe to repeat until it succeeds and never needs undoing. Teams reach for a saga when neither holds: the steps span independent systems, some steps cannot be retried indefinitely, and a half-finished result is a business problem rather than a technical one. Before committing to this design, confirm with the owners of each downstream system whether they offer a cancel or reversal API, whether that API can be called more than once, and how long a reversal may take to become visible to customers.

The pattern has limits you should accept up front. A saga gives you eventual consistency with compensations, not atomicity: between a forward step and its compensation, other readers may see intermediate state, and a compensation can itself fail. Some effects, such as a sent email or a fee already disclosed to a customer, cannot be truly undone and need a business decision about how to handle them. Ask your product and finance owners which states are acceptable to expose temporarily and which must never occur, because that answer determines how much of the design is compensation logic and how much is ordering and locking.

Forward steps, failure and reverse compensation

The diagram starts when the saga workflow runs its forward activities in order. Each completed step's result is written to the workflow event history, which Temporal persists in the configured database, so progress survives worker restarts. When a step fails after its retries are exhausted, the workflow runs the compensations registered for the completed steps in reverse, here step two and then step one. Check that every compensation is idempotent and that the failed step's own cleanup is handled explicitly.

Forward steps run in order, then compensations unwind completed steps.

Choosing between orchestration, choreography and a single transaction

A Temporal orchestrated saga places the whole sequence in one workflow definition. The workflow calls an activity for each step, records the compensating activity for every step that succeeded, and runs those compensations in reverse order when a later step fails. The workflow's event history is the record of what ran, what failed and what was compensated, so operators can see the state of one business transaction in one place.

  • Flow ownership: A single workflow owns the sequence, branching and compensation order, so the logic can be read and changed in one codebase.
  • Failure visibility: Each step, retry and compensation appears in the workflow history and the Temporal Web UI, which makes stuck or partially compensated transactions easier to find.
  • Retries and timers: Retry policies and timeouts are handled by the platform, so a step can wait out a downstream outage without custom scheduling code.
  • Coupling: The orchestrator must know every participating service and its compensating action, which adds a central dependency to plan for.
  • Non-Temporal systems: Any system reachable from an activity can participate, including legacy systems and third-party APIs that offer no transaction support.

Before committing, confirm that every participant can accept a compensating call that is safe to repeat, and that your self-hosted service has the persistence and access controls your team requires.

Building a saga workflow step by step

This sequence turns a multi-service business operation into a Temporal saga whose forward steps and compensations are each idempotent, tested under failure, and verified in a non-production namespace before any real traffic touches it.

  1. Map the operation into ordered steps

    Write down every service call in the business operation in the order it must happen, then mark which calls change state outside Temporal's control, such as a payment capture, an inventory reservation or an email sent to a customer. Each of those is a candidate saga step. Owners from the business and the service teams should sign off on the list, because the sequence decides which compensations you must build. The output is a short table of steps with their owning systems, reviewed by the people who run those systems.

  2. Define the inverse effect for each step

    For every forward step, write the compensating action that undoes its business effect, such as a release for a reservation or a refund for a capture. Some steps have no true inverse, for example a notification that was already delivered, so record a business decision for those, such as sending a correction message instead. Ask the service owners to confirm that each compensation is possible after the forward step succeeds and that the system exposes an API for it. The check is a reviewed table where every step has a compensation or a documented reason it has none.

  3. Implement forward and compensating activities

    Write each forward and compensating action as a Temporal activity that calls the external system with a stable idempotency key, usually derived from the workflow ID and step name, so a retried call does not repeat the business effect. Attach a retry policy that suits each downstream service and mark errors that will never succeed on retry as non-retryable. Compensations need the same idempotency treatment because they are retried too. The check is unit and integration tests showing that running the same activity twice produces one effect in the target system.

  4. Register compensations as the workflow runs

    In the workflow code, push each compensating action onto a list immediately after its forward activity completes successfully, not before. On any failure, run the list in reverse order, so the most recent successful step is undone first. Decide whether a failed compensation should retry until it succeeds or stop and alert a human, and encode that choice explicitly. The check is a workflow whose history shows each compensation appearing only after its matching forward step has completed.

  5. Test failure at every step

    Write tests that inject a failure at each forward step and at each compensation, then assert the final state of every downstream system. Include cases where the failure happens after the external call succeeded but before Temporal recorded the result, because that is where duplicate effects appear. Use Temporal's test environment for fast checks and run a subset against real dependencies. The check is a test matrix covering every step-and-failure combination, with all cases passing and the expected end state recorded for each.

  6. Verify in a non-production namespace

    Deploy the workflow and its workers to a non-production Temporal namespace connected to test copies of the downstream systems, then run the failure matrix end to end and inspect the event histories in the Temporal Web UI. Confirm that compensations appear in reverse order and that no business records are left half-changed. Confirm that workers can restart mid-saga and resume. Access to this namespace should be restricted, because the self-hosted Temporal default authorizer allows every API request unless you configure one. The check is a signed-off run log showing the matrix results and the audit of namespace access.

  7. Document the atomicity gaps before production

    Record where the saga cannot give you atomicity: a window where other readers see intermediate state, compensations that can fail, external effects that cannot be reversed, and steps that call systems outside your control. For each gap, agree with the business owner whether to accept it, add a reconciliation job, or change the design. Share this record with the people who approve production change. The check is a written list of accepted gaps, each with an owner and a decision, approved before the workflow is promoted.

Making compensations idempotent and safe to retry

A compensation runs in the same failure conditions that caused the saga to roll back, so it has to survive retries, duplicates and partial outages. The cards below cover the design choices that make compensations safe to repeat, the error classes that should stop retries, and the records operators need when something still goes wrong.

Pass idempotency keys downstream

Derive a stable key from the workflow ID and the step name, then send it with every charge reversal, release or cancellation call to the downstream system. Temporal activities can be retried or re-executed after a worker failure, so the downstream system must recognize a repeated request and return the original result. Check that each partner API documents key lifetime and whether it accepts the key on refund and cancel endpoints, not only on create.

Accept compensations that find nothing to undo

A compensation may run after the forward step failed before it took effect, or after a previous attempt already undid it. Write each compensation to check current state first and treat 'already reversed' or 'never created' as success. Illustrative example: a release-hold compensation that finds the hold already gone should return success and record that no change was needed, rather than fail and block the rest of the rollback.

Handle a compensation that fails

A compensation can fail for reasons that retries will not fix, such as a closed account or a rejected reversal. Decide in advance whether the workflow keeps retrying with a bounded policy, moves the step to a manual queue, or opens a human task with the saga state attached. Do not let an unresolved compensation leave the workflow silently completed, and confirm with each downstream owner what a permanent refusal looks like in their API.

Mark business errors non-retryable

Separate transient faults, such as timeouts and 503 responses, from business refusals, such as an invalid account state. Retry transient faults with the activity retry policy, and raise a non-retryable application error for refusals so Temporal stops retrying and the saga moves to its next decision. Mistakes here are costly in both directions: retrying a refusal wastes time and can repeat side effects, while marking a transient fault as final can leave a reversal undone.

Record compensation outcomes for operators

Store each compensation's attempt count, last error, downstream reference and final status as workflow state or in a searchable record, so operators can see which steps reversed and which did not. Use Search Attributes or your own audit table keyed by workflow ID. Confirm with your operations team which view they need during an incident and how long these records must be kept under your retention rules.

Temporal visibility docs

Saga configuration options and when each fits

This table compares the main configuration choices for a Temporal saga: compensation ordering, retries, timeouts, child workflow structure and manual intervention. Read each row against the situation your saga is in, then check the trade-off column before you fix the design.

Design optionUse it whenTrade-off
Reverse-order compensation registered per stepEach completed step has a clear undo and later steps depend on earlier onesCompensations must be idempotent, and the saga code grows with every step added
Parallel compensation of independent stepsCompleted steps touch unrelated resources and none depends on another's undoOrdering errors can surface if a hidden dependency exists between steps
Default retry policy on compensationsCompensations call systems that recover quickly and their failures are transientEndless retries can hold a failed saga open for a long time if the downstream system stays down
Bounded retries with a non-retryable error for business rejectionsA compensation can fail for a reason that retrying will not fix, such as a closed accountRequires classifying errors correctly, and a misclassified error can leave money or stock in an unresolved state
Short activity timeouts on forward stepsDownstream calls are fast and a hung call should fail the step so compensation can runToo short a timeout causes compensation of work that actually succeeded, so the call must be idempotent
Longer timeouts on compensationsUndo operations are slow, such as batch reversals or external settlement reversalsA stuck compensation keeps the saga open, so monitoring and alerting must cover it
One workflow per sagaEach saga has its own identity, lifecycle and audit trail that operators need to queryMany concurrent sagas increase workflow count and the visibility load on the cluster
Child workflows for sub-sagasA step is itself a multi-step process that needs its own compensation scopeParent close policy and cancellation must be designed, or child compensations can be skipped
Automatic compensation onlyFailures are expected, fully reversible and need no human decisionCases the compensations cannot resolve stay in an unknown state with no operator path
Manual intervention path via signal or updateSome failures need an operator to choose a fix, retry a step or accept a partial resultOperators need authorization, an audit record of each decision and a runbook for the states they can act on

Where a saga still cannot give you atomicity

A saga gives you eventual consistency with a defined way to back out completed steps, not the all-or-nothing guarantee of a single database transaction. The cards below cover the gaps that remain after compensations are written, and the design checks that narrow each one for Temporal workflows.

Visible intermediate state

Between the first committed step and the final one, other users and systems can see the partial result. An order may show as reserved while its payment is still pending. Decide which intermediate states are acceptable to readers, label them in the data model, and check whether downstream reports or notifications react to a state that a later compensation will reverse.

Temporal deployment docs

Effects outside your system

A compensation can undo a database row but cannot unsend an email, unsettle a card payment that the network already cleared, or recall a message published to a partner. For each external effect, record the provider's reversal options, such as a refund or a correction notice, and agree with the business owner what the saga does when that reversal fails.

Non-reversible steps placed too early

Order matters in a saga. Put steps that cannot be undone, such as dispatching goods or sending a regulatory filing, at the end of the sequence, after every step that can still fail has succeeded. Review the step order with the same care as the code itself, because moving an irreversible step earlier later can turn a routine failure into a manual cleanup.

Concurrent sagas on one resource

Two sagas that touch the same account or inventory item can interleave, so one compensation may restore a value that the other saga has already changed. Serialize access to shared resources with a lock workflow or conditional updates keyed on a version, and test pairs of overlapping runs that share a resource, not only single runs.

Reads that see partial state

Queries, API reads and analytics jobs can return values from a saga that is halfway through or about to compensate. Decide whether readers should see a status field such as pending or reversing, and make read paths honor it. A Temporal query returns workflow state, but it does not make your downstream database reads consistent with that state.

Questions teams ask before building a saga on Temporal

What drives the cost and effort of a saga build on Temporal?

The main driver is the number of steps that change state in other systems, and how many of those systems offer a reliable way to reverse their changes. Each step needs a forward action, a compensating action, and a decision about what happens when the compensation itself fails. Cost also rises with the number of distinct failure modes you must handle, such as timeouts where the outcome is unknown, partial writes, and manual reversal rules that a business owner must approve. Costs fall when steps are few, when downstream APIs support idempotency keys or reversals, and when the business accepts a defined manual queue for the rare cases automation cannot close. Ask any partner for a quote that lists each step, its compensation, the test environments needed, and the operations handover, separately, so you can see which items are one-time work and which recur as the workflow changes. Self-hosting costs such as infrastructure and on-call are separate from the build itself.

How long does a typical saga implementation take?

Duration depends mostly on step count, on how many downstream systems you must integrate, and on whether those systems expose compensating operations. A saga with a few steps against well-documented APIs is a different project from one that spans a core ledger, a payments provider and a legacy system with no reversal endpoint. Discovery work on each downstream system's failure behavior often takes longer than writing the Temporal code itself. Testing of failure paths, including compensation failures and timeouts, usually takes a large share of the schedule. Ask for a timeline that is tied to a written scope, with milestones for each step's forward and compensating logic, a test environment with realistic downstream behavior, and a cutover plan. Any duration you are given should be checked against the number of systems and the availability of your domain owners.

What does the work need from our engineers and domain owners?

Your engineers must supply access to each downstream system in a non-production environment, documentation of their error codes and idempotency behavior, and a named owner for each system who can answer questions about partial failures. Domain owners, such as finance or operations leads, must decide what a correct end state looks like when a compensation cannot run, and who approves manual resolution. Without those decisions, the saga will compensate in ways the business has not accepted. Expect your team to review the workflow design, the compensation rules and the operator runbook before go-live. Plan time for these people in the schedule, because a build that waits on a business decision or a sandbox credential stalls regardless of engineering speed.

Can our team build a saga on Temporal without a partner?

Yes, a team with production experience in Temporal workflows, idempotent API design and distributed failure handling can build a saga in-house. The harder parts are rarely the Temporal APIs. They are deciding which steps can be reversed, writing compensations that tolerate retries and duplicates, and proving the behavior under failure. A partner adds the most value when your team lacks that experience, when several systems must be integrated at once, or when the saga must pass a compliance review that asks for test evidence. Whichever path you choose, agree on who owns the workflow code after launch, how it will be versioned, and who responds to alerts. DeployOpen plans and builds these engagements under a written scope, and can hand over documentation and runbooks for your team to run.

How are compensations tested before they run in production?

Compensations should be tested at three levels: unit tests of each compensating activity against mocked responses, workflow tests in the Temporal test framework that inject failures at every step, and integration tests against sandbox versions of each downstream system. The most important cases are the ones that are easy to miss, such as a forward call that times out after the downstream system has already committed, a compensation that returns an error on its first attempt, and a duplicate delivery of the same compensation. Each test should assert the final state in the downstream system, not only the workflow's return value. Ask whether the sandbox behaves like production for error codes and latency, because a mock that always succeeds hides the cases that matter. Keep these tests in version control so they run on every change to the workflow.

What changes when a saga is versioned for a running workflow?

A saga that is already running keeps executing the code path it started with unless you handle versioning deliberately. Changing the order of steps, adding a compensation, or removing an activity can break replay of in-flight workflows, and Temporal reports that as a non-determinism problem. The usual approach is to gate new behavior with versioning markers so that old executions follow the original path while new executions use the updated logic. Compensations are the most sensitive part, because an in-flight saga may be partway through a rollback when you deploy. The work includes an inventory of open executions, a rule for when old versions can be retired, and tests that replay recorded histories against the new code before deployment. Ask for that replay testing to be included in the scope, since it is where versioning mistakes usually surface.

Does a saga give us full atomicity across systems?

No. A saga gives you eventual consistency by running compensations after a failure, but between a forward step and its compensation, other processes can see the intermediate state. A compensation can also fail, and some actions cannot be reversed at all, such as a notification already sent or a regulatory filing already submitted. Temporal makes the orchestration durable, so the saga resumes after worker or server restarts, but it cannot roll back a commit in a downstream database. Where strict atomicity is required, you need to redesign the steps, reduce the number of systems involved, or accept a defined manual process. Decide these trade-offs with your risk and compliance owners before the build starts, and document the states a customer or operator can observe during a saga.

How DeployOpen scopes and delivers saga workflows on Temporal

DeployOpen plans, builds, documents and supports Temporal saga workflows inside infrastructure you control, with the compensation logic reviewed alongside the business process it protects. Engagements start from a written scope that names the transactions, steps and failure cases to be covered, so the team can see exactly what a saga does and does not guarantee before build work begins.

How we scope

  • Map each cross-system transaction, its steps, and the owning system for every step and its compensation.
  • Agree in writing which failure paths, timeouts and manual reconciliation cases the saga will handle.
  • Confirm deployment model, namespaces, and whether self-hosted Temporal or Temporal Cloud fits your environment.

How we build

  • Implement workflows with a registered compensation per step, run in reverse order on failure.
  • Make every compensating activity idempotent, with idempotency keys stored in the systems being called.
  • Test failure injection, worker restarts and replay so compensation paths run as designed before release.

How we hand over

  • Deliver design notes, compensation matrix, runbooks for stuck or partially compensated sagas, and version rules.
  • Document the cases where the saga cannot provide atomicity, and the reconciliation steps your team owns.
  • Walk your engineers and operators through the code, dashboards and a retest of the handed-over paths.

How we support

  • Support upgrades of Temporal Server and SDK versions and check saga workflows against workflow versioning rules.
  • Offer ongoing support, upgrades and continuous testing as a retainer after the initial delivery.
  • Confirm support terms, response expectations and access arrangements in the written scope before work starts.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.