Compensating Transactions for Production LLM Agents in October 2026: Saga Patterns That Undo Side Effects When a Later Tool Call Fails

Multi-step LLM agents do not just answer questions. They book flights, create tickets, charge cards, send emails, and write to databases. When step three fails after steps one and two already succeeded, you cannot roll everything back with a single database transaction. The tools live in different systems, each with its own API and its own idea of "done." This post covers how to design compensating transactions—saga-style undo steps—so a failed mid-run does not leave half-applied side effects in production.

Artificial Neural Network with Chip
Image: mikemacmarketing / photo on flickr via Wikimedia Commons (CC BY 2.0)
Undo and redo controls
Image: Tafol via Wikimedia Commons (CC BY-SA 4.0)

Why ACID does not save you

In a monolith you wrap related writes in one transaction and either commit or roll back. Agent tool calls break that model:

  • A refund API and a CRM note are different services with different latency and failure modes.
  • Some actions are irreversible by design (sending an email, posting a public message).
  • The LLM decides the next tool at runtime, so you rarely know the full write set before the run starts.

What you can do instead is treat each successful side-effecting tool call as a step that records both what it did and how to undo it. If a later step fails, you walk the recorded steps in reverse and run the compensations. That pattern is a saga: a sequence of local transactions with compensating actions, not a distributed two-phase commit.

Model every write as a reversible step

Before you wire the LLM to a tool, classify the tool:

  1. Read-only. Lookup, search, fetch. No compensation needed. Prefer these early in a plan so failures cost nothing.
  2. Idempotent write. Create-or-update with a stable key. Retries are safe; compensation may still be needed if a later step fails (for example, delete the draft you created).
  3. Non-idempotent write. Charge a card, send email, open a support case with a new ID. Require an idempotency key on the request, and define an explicit compensate action.
  4. Irreversible. Actions you cannot undo (physical shipment already left, public announcement already live). Gate these behind human approval or put them last, after every reversible step has succeeded.

Store a step record after every successful write. A minimal shape:

{
  "step_id": "stp_7f3a",
  "tool": "create_draft_invoice",
  "input": {"customer_id": "cus_19", "amount_cents": 4900},
  "output": {"invoice_id": "inv_8821", "status": "draft"},
  "compensate": {
    "tool": "void_invoice",
    "input": {"invoice_id": "inv_8821"}
  },
  "status": "committed"
}

The important field is compensate: enough information to undo the step without re-asking the model. Never rely on the LLM to invent undo calls under stress; it will miss edge cases and may invent parameters.

Run the forward path with a step log

Keep agent state in a durable store keyed by run ID. After each tool result:

  • Append the step (including compensate payload) to the run log.
  • Only then continue to the next model turn.
  • If the process crashes between "tool succeeded" and "step logged," use the tool's idempotency key on retry so you do not double-write, then reconcile the log from the provider's response.

When the model finishes successfully, mark the run completed and leave compensations unused. When any step fails fatally (hard validation error, provider 4xx that will not succeed on retry, timeout after retries exhausted), mark the run compensating and start the undo loop.

Decide what "fatal" means

Not every tool error should trigger compensation. Distinguish:

  • Retryable: 429, 503, network blips. Retry with backoff and the same idempotency key. Do not compensate yet.
  • Business reject: "card declined", "slot already booked." Often you should compensate earlier writes and then surface a clean failure to the user, or ask a clarification turn instead of blindly undoing.
  • Bug / schema mismatch: Treat as fatal for the run: stop forward progress, compensate, alert.

Encode these categories in your tool error types so the orchestrator does not guess from free-text error strings.

Compensate in reverse, and make it boring

Walk the step log from newest to oldest. For each step with status committed:

  1. Call the recorded compensate tool with the recorded input.
  2. On success, mark the step compensated.
  3. On failure, mark compensate_failed, alert a human, and continue with remaining steps if safe—or stop if later undos depend on this one.

Keep compensation handlers deterministic and free of LLM involvement. A compensate function should be a normal typed API call: void invoice, cancel reservation, delete draft comment. If undo itself needs judgment ("should we email the customer?"), escalate to a human-in-the-loop queue rather than inventing a new model turn mid-rollback.

Partial compensate and poison steps

Sometimes undo fails because the external system already deleted the resource, or because a human already fixed it. Treat "already undone" as success (HTTP 404 on delete, or a status that means voided). Log it clearly so you do not page for noise. If compensate fails for a real reason, leave the run in needs_manual_repair with the failed step highlighted. Operators should see the original forward inputs, outputs, and what compensate attempted.

Order tools so sagas stay small

Saga complexity grows with every write. Practical ordering rules cut the blast radius:

  • Read and validate first. Confirm inventory, permissions, and prerequisites before any write.
  • Create drafts before committing. Prefer draft invoice → draft email → then finalize or send. Compensating a draft is cheaper than reversing a sent charge.
  • Put irreversible or hard-to-undo actions last. Send the confirmation email only after payment and booking both succeed.
  • Prefer reservation-then-commit. Hold a seat for a few minutes with an expiry; if later steps fail, let the hold expire or release it explicitly.

If a workflow regularly needs more than a handful of compensating writes, consider splitting it into smaller agent runs with an explicit human checkpoint between them.

Wire this into the agent runtime

In code, the orchestrator—not the prompt—owns the saga. Pseudocode for the control loop:

for each model tool call:
  if tool.is_write:
    result = call_with_idempotency(tool, args, run_id)
    if result.ok:
      log_step(run_id, tool, args, result, tool.compensate_for(result))
    else if result.retryable:
      retry...
    else:
      compensate_all(run_id)
      return failure_to_user(result)
  else:
    result = call_readonly(tool, args)
# model signals done
mark_completed(run_id)

Expose compensate definitions next to the tool schema in your registry so engineers cannot add a write tool without declaring how to undo it (or explicitly marking it irreversible and gated). Review that registry in code review the same way you review database migrations.

What to measure

Track per run and per tool:

  • Forward success rate and compensate rate (compensates should be rare; a spike means a broken dependency or a bad prompt).
  • Compensate success rate and time-to-compensate.
  • Runs stuck in needs_manual_repair.
  • Duplicate side effects (same idempotency key applied twice)—should be near zero if keys are enforced.

Sample failed runs weekly. Check that the user-visible state matches the log: no charged-but-unbooked customers, no open tickets with voided invoices left dangling.

Common failure modes

  • Compensating with the LLM. Asking the model "please undo what you did" is unreliable. Persist the undo plan when the forward call succeeds.
  • Missing idempotency keys. Without them, a retry after a timeout can double-charge even before you get to compensation.
  • Compensating read-only noise. Do not log compensate payloads for searches; keep the step log focused on writes.
  • Silent irreversible tools. If a tool cannot be undone, refuse to call it until prior steps are confirmed, or require an approval gate.
  • Orphan runs after deploys. On startup, scan for runs left in compensating or in_progress past a deadline and resume or escalate.

A concrete walkthrough

Suppose an agent handles "upgrade plan and email the receipt":

  1. get_subscription (read) → no compensate.
  2. create_invoice_draft → compensate: void_invoice.
  3. charge_payment_method → compensate: refund_payment (same payment id).
  4. apply_plan_upgrade → compensate: revert_plan.
  5. send_receipt_email → irreversible; only run after 2–4 succeed. If email fails, you may retry email without undoing the upgrade, or compensate everything if policy says the user must not be charged without a receipt—encode that policy in the orchestrator, not the prompt.

If step 4 fails after a successful charge, compensate runs refund then void. The user sees a clear failure, and finance does not chase a ghost upgrade.

Takeaways

Production agents that write to the world need the same discipline as distributed workflows: durable step logs, idempotent forward calls, and explicit compensations owned by the runtime. Keep the model focused on choosing the next useful action; keep undo paths boring, typed, and tested. Start with a small set of write tools, require a compensate definition for each, and measure how often you enter the compensating path. When that path is reliable, you can safely give agents more powerful tools without leaving half-finished messes behind.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)

Tencent Hy4 Preview: Open 770B MoE Built for Real Work