A periodical about version control, git, and the future of agentic version control.

Saga Pattern for Long-Running Agent Transactions

Saga-style compensation gives agent workflows a crash-safe way to undo.

· 8 min read
Cover illustration for “Saga Pattern for Long-Running Agent Transactions”
Idempotency & Concurrency Patterns · November 10, 2026 · 8 min read · 1,872 words

Long-running agent transactions need a recovery architecture. The saga pattern gives that architecture by pairing each action across external systems with a clear compensation path. For it to work, it needs durable logging before execution, idempotent recovery, and a plan for handling irreversible effects. Independent verification then addresses a separate question, whether a recovered or completed workflow actually serves the product’s intent.

Why agent workflows fail mid-flight in ways that retries cannot fix

An agent books a flight, charges a card, and attempts to reserve a hotel. The hotel reservation fails, leaving a confirmed flight and a charged card without the hotel booking. The earlier actions have already committed, each in its own system. There is no shared transaction to roll back. A distributed lock across a payment provider and a hotel API is not something an agent can hold while a model reasons.

Retrying does not resolve that fragmented state. A tool call may finish before its response fails, so the agent cannot tell whether the call failed or succeeded. Repeating the request can produce duplicate charges, emails, or calendar entries. Robust Agent Compensation (RAC), published at ACM CAIS’26, identifies another complication, namely that ReAct execution order is determined at runtime. Recovery therefore needs a durable account of what actually happened.

What the saga pattern is and where it comes from

Garcia-Molina and Salem created the saga pattern for long-running distributed transactions before there were AI agents. A saga replaces one distributed transaction with a sequence of local transactions, each paired with a pre-declared compensation. Each transaction commits within its own system. If a later step fails, compensation works backward through the steps that have already committed. For a workflow T₁, T₂ … Tₙ, failure at Tₖ triggers Cₖ₋₁ … C₁.

Compensation restores consistency without pretending history can be erased. A refund compensates for a charge, but it does not undo the charge in one atomic operation. A correction can address a sent email, but it cannot un-send it. Human review can also be a legitimate compensation outcome. SagaLLM, published at VLDB 2025, applies this structure to multi-agent planning and demonstrates travel scenarios in which a failed flight reservation triggers reversal of related hotel and train bookings.

Orchestrated vs. choreographed sagas and which fits agent systems

An orchestrated saga puts recovery authority in a central coordinator that tracks the workflow, holds the compensation log, and initiates reverse execution after failure. This is the right default for most agent applications. LLM-driven planning already has a coordinating role, while supervisor graphs and state machines provide a natural place to represent it. Keeping the plan and the record of recovery together also makes the compensation path easier to audit and test.

A choreographed saga distributes that authority across participants. Each agent reacts to events, and a failure event prompts previously completed participants to compensate independently. This can fit organizational boundaries or multi-vendor ecosystems where the parties cannot all trust one coordinator. The A2A-SAGA proposal brings an Execute → Verify → Compensate protocol extension to the A2A ecosystem. Within one application, however, scattered event handlers make recovery harder to inspect, and neither model removes the need for a single durable compensation artifact that survives a crash.

The two non-negotiable rules — log compensation before acting, and make compensations idempotent

The compensation entry must be written durably before the forward action executes. If an external action completes and the process dies before registering its compensation, recovery has no record of the required repair. The external state survives while the recovery plan disappears. This is how a workflow accumulates silent inconsistency despite having compensation functions in its code.

If the process stops after registration but before execution, recovery finds a declared action that never ran and has nothing to compensate. That distinction requires execution state. A registered compensation does not prove that its forward action committed, and a missing response does not prove that it failed. Ambiguous outcomes require a status check.

Compensations must also remain safe when repeated. A refund or cancellation can time out just as its forward action can, so recovery must tolerate another attempt without duplicating the effect. Forward actions need deterministic idempotency keys made from stable identifiers such as session ID, customer ID, action type, and sequence number. A fresh random UUID on every retry defeats deduplication because it identifies each retry as a new request.

The same rule applies to state updates. Appending data again creates another entry, while writing the full desired state as an overwrite can make repetition idempotent. These properties must belong to the operation itself. RAC reports substantial latency and token-economy improvements over LLM-based recovery approaches on complex problems. That evidence supports log-based recovery as an architectural choice.

A concrete saga for a realistic agent workflow

An outreach agent makes the compensation boundary visible. Its first step, T₁, loads a candidate record and needs no compensation because it is read-only. T₂ generates a draft email, whose compensation is to discard the draft. T₃ sends the email, an irreversible effect requiring a correction or a voided-thread marker. T₄ creates a CRM activity that can be deleted, while T₅ schedules a follow-up whose compensation cancels the scheduled task.

Suppose T₃ succeeds but T₄ fails before it commits. There is no CRM activity to delete. The coordinator moves backward to T₃ and queues a correction email as a human-readable task, with human review explicitly included in the recovery path. The other compensations then run in the reverse order declared for them.

Each pairing belongs in the compensation definition before execution. That makes the recovery path auditable and repeatable. The example also exposes where the data model can preserve options. Draft states before confirmed sends, soft deletes instead of hard deletes, and staged commits before immediate writes reduce the number of irreversible effects that require correction.

Implementing a saga on a graph-based agent runtime

A graph-based runtime provides the state machine, branching, and checkpointer needed to implement this design. In a LangGraph-style structure, a state graph represents the workflow and a database-backed checkpointer provides persisted checkpoints. The state includes completed step IDs, a compensation_log, and an error field as recovery inputs. After a process restart, enough state must be kept to tell which work was declared and which work committed.

Each step first appends its compensation entry and persists it before invoking the external action. Only after the forward action commits does the runtime record the step as completed. The ordering is the essential implementation detail. Updating compensation_log only in memory before a tool call does not meet the durability requirement. A persisted checkpointer backed by SQLite or Postgres protects the record that recovery will need after a crash.

On failure, the graph enters a compensation branch and walks the log in reverse, using completion state to determine which actions require compensation. Each compensation runs through safe_retry, with idempotency making repeated attempts safe. Retry budgets still impose a stopping point. Work that exhausts its budget remains in the log and routes to a quarantine queue with full execution telemetry. Graph interrupts can also pause chosen actions for human sign-off, while RAC shows that recovery infrastructure can wrap existing agent frameworks without changes to agent code.

How irreversible steps should be handled — and when to route to a human

Irreversible actions must be planned for in the design so they are not treated as unexpected exceptions. Before execution, the compensation definition should name each such step and state whether it calls for a technical reversal, a correction action, or human escalation. Those outcomes have different operational meanings. Sending a correction acknowledges an external effect that cannot be erased, while human review reserves a consequential decision for someone authorized to make it.

Escalation is an engineered outcome of the saga. When compensation keeps failing, payment state is unclear, or actions affect customers, further attempts by the agent may need to give way to a review task. That task needs the full compensation log, a recording or trace of the agent’s actions, and clear reproduction steps. A pending review must remain visible as an unresolved state.

RAC frames reliable execution around avoiding unintended side effects rather than guaranteeing successful completion every time. A known pending-review state is therefore valid when the system enters it on purpose. Metis handles a related boundary before tool calls have effects in external systems. Its runtime makes permission decisions, interference classes, terminal results, and lifecycle transitions explicit and inspectable. Per-call mediation governs whether an action proceeds, while saga compensation governs recovery across the larger sequence.

State tracking and observability as the operational backbone of a running saga

The compensation log is a first-class operational artifact. It must record the step ID, the compensating action, whether the forward step finished, and whether compensation ran. An on-call engineer needs that record to determine which external effects remain after a failure. Trace IDs should connect every step and compensation attempt, including retries, into one auditable timeline.

Monitoring must spot stuck states as well as collect errors. A step still marked as retrying after its budget expires needs attention, as does a webhook pending beyond its expected window. Repeated unsuccessful compensation attempts also require alerting. Before replaying an action, the agent should use its idempotency key to query the receiving service’s stored result. If that lookup fails, the outcome remains uncertain, and blind replay can still lead to duplicate effects.

Persistent dead-letter queues keep failed or malformed events in quarantine so they can be reconciled even after a crash. Without that record, poison-pill events can cause repeated consumer restarts and fail to reach human review. What ran, what committed, what failed, and what recovery attempted are the same facts needed to detect a stuck saga and decide its next action. Building that record once avoids a split between what automation sees and what a human can inspect.

What independent verification adds on top of saga recovery

A saga can recover from an execution failure without establishing that the product behaves correctly. Every step may return 200 while the user journey violates the intended behavior. No compensation branch fires in that case. The workflow has succeeded according to its implementation, but the implementation may encode the wrong goal. Recovery cannot detect that mismatch merely by tracking commits and errors.

Verification therefore needs independence from the agent that wrote the code or orchestrated the workflow. Its reference should be the product’s specs and docs. Continuous Agent Validation runs AI browser agents through the key user journeys after every change, taking the same paths as real users. This addresses behavioral regressions that passing tests and clean deploys can miss. It tests the intended forward outcome rather than only the reliability of the recovery path.

Composal reads a team’s specs, docs, and product discussions to learn intended behavior, then deploys agents to explore flows, roles, permissions, and edge cases in parallel. Each failure report comes with a recording, logs, and reproduction steps. That evidence gives teams a basis for investigating the gap between what was built and what was intended, including teams without a dedicated QA engineer. Teams that ship quickly with coding agents need confidence in both their recovery and their releases. Sagas make failures recoverable, while independent verification tests whether the product deserves trust.

Sources

  1. Robust Agent Compensation (RAC): Teaching AI Agents to Compensate
  2. Metis: Typed Runtime Mediation for Tool-Using Software Agents

More in Idempotency & Concurrency Patterns