Compensating Transactions for AI Agent Workflows
Design compensating transactions for AI agent workflows with recovery ledgers, explicit business reversals, uncertain outcomes, and irreversible boundaries.
Abhishek Raj · · 8 min read
Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.
Compensating transactions help an AI agent workflow recover when several services have already changed state and a later step cannot finish. The model may choose a plan, but recovery needs an explicit contract: which effects occurred, which can be counteracted, which must remain, and who can authorize the resulting business outcome.
A compensation is a new action in the current world. It is not a promise to restore a historical snapshot. This guide develops a hypothetical equipment-ordering agent to explain recovery ledgers, dependency ordering, ambiguous outcomes, and irreversible boundaries. The proposed policies and examples are illustrative, not a tested reference implementation.
Distinguish local rollback from business compensation
A local database transaction can roll back changes before its commit. A workflow that reserves stock, authorizes payment, and books collection with independent services normally has no single database transaction covering those operations. A saga coordinates local transactions and explicitly designed compensating actions. Chris Richardson also highlights its lack of automatic rollback and isolation. Saga pattern.
For the proposed ordering agent, releasing a reservation counteracts a stock hold. Voiding an authorization counteracts an uncaptured payment hold. Refunding a captured payment is a different business event, with potentially different processing time and fees. Deleting a local payment row would not reverse the processor's effect.
Write down the intended recovery outcome using business terms. For example: “No active stock reservation remains, no uncaptured payment authorization remains, and the customer receives an accurate cancellation status.” That statement is more useful than “run rollback,” because it can be checked against authoritative services.
Microsoft's compensation guidance explains why restoring old values can overwrite legitimate concurrent changes. Compensation must account for the current business state and may require human intervention. Compensating Transaction pattern.
Classify effects before allowing an agent to plan them
In this illustrative design, the tool registry describes recovery properties alongside input schemas:
| Effect | Recovery option | Important constraint |
|---|---|---|
| Reserve equipment | Release this workflow's reservation | Do not release another order's stock |
| Authorize payment | Void that authorization | Only while the processor permits a void |
| Capture payment | Issue a refund | Refund is a separate, observable transaction |
| Book collection | Cancel that booking | A cancellation window may apply |
| Send confirmation | Send a correction | The original message cannot be unsent |
These categories should be supplied by application owners. An agent should not invent a cancellation endpoint because a tool's name sounds reversible. Reject plans whose recovery expectations contradict the actual service contract.
Prefer reversible preparation before a meaningful commitment when the business permits it. Reserve before dispatch; prepare a draft before sending. This reduces the recovery burden but does not remove expiry races or guarantee that prepared resources remain available. The plan must still check preconditions at commitment time.
Some workflows are better completed forward than compensated. If one collection provider fails, an authorized alternative provider may finish the intended order without undoing the payment. That choice needs an explicit substitution policy and customer constraints, rather than an improvised decision made during an incident.
Persist a recovery ledger before dispatching effects
A chat transcript is insufficient evidence that a step happened. Maintain an authoritative ledger keyed by workflow and logical action. A proposed record contains:
{
"workflow_id": "order_example_42",
"step_id": "reserve-equipment",
"action_key": "order_example_42:reserve:v1",
"input_digest": "illustrative-normalized-payload-hash",
"forward_status": "outcome_unknown",
"external_operation_id": null,
"compensation_kind": "release_reservation",
"compensation_status": "registered",
"recovery_policy_version": "equipment-order-v3"
}
The identifiers and field names are illustrative. Keep sensitive payment details outside the workflow record; store appropriate references instead.
Persist the logical action identity, expected effect, and recovery intent before making the remote call. Afterwards, store the observed receipt or uncertain result. This does not make a database write and a remote API call atomic. It gives recovery enough information to investigate the interval between them.
Temporal's saga guidance recommends registering compensation before a side-effecting activity when partial completion is possible. Such a compensation must tolerate a forward action that never happened, as well as repeated execution. The framework pattern does not establish the correctness of the underlying business reversal. Temporal Saga Pattern.
In a custom coordinator, represent registration durably rather than retaining only an in-memory callback. A process crash must not erase the knowledge that a reservation may need releasing.
Walk through a failure after payment authorization
Suppose a hypothetical agent orders a replacement scanner. The application confirms its permitted budget and shipping address. The inventory service returns reservation R7. The payment processor returns authorization A8. The collection service then rejects the requested pickup because the location is unavailable.
The coordinator first stops new forward steps and records the recovery decision. It should not let a parallel agent continue toward dispatch while another worker cancels the order. Use a workflow revision or equivalent execution fence so stale workers cannot advance the old plan.
Assume this product's documented policy is to cancel when collection cannot be booked. The coordinator releases R7 and requests a void of A8, tracking each result separately. If the void succeeds but releasing stock times out, the workflow remains partially compensated. It does not mark cancellation complete merely because its last model response says so.
Now consider a different schedule: the stock release times out after the service commits it. Retrying needs the same logical release identity or a safe lookup contract. AWS describes using caller-provided request identifiers to distinguish retries from new intent, including the need to handle late requests and mismatched parameters. Making retries safe with idempotent APIs.
The design therefore gives forward actions and compensations separate stable identities. A refund is not a retry of a charge. See idempotency for agent actions for the associated service-side contract.
Treat unknown outcomes as a distinct recovery problem
A timeout establishes that the caller lacks an answer. It does not establish that the action failed. Blind compensation can be incorrect if the original effect never happened; blind forward retry can create a duplicate if it did.
For this proposed workflow, reconcile by the original action identity before deciding which compensation is applicable. Query the provider's operation status, inspect the referenced resource, or use another documented confirmation mechanism. Record the evidence and its time. If the service offers no reliable way to distinguish outcomes, route the uncertainty to a defined manual process rather than pretending the workflow is fully automated.
Late completion also matters. Imagine a reservation request completes after a cancellation worker observes “not found.” A one-time no-op release would leave an unwanted reservation. A robust service contract might support cancellation tombstones keyed by the original request, or the coordinator might continue reconciliation until the forward request is definitively resolved. These are proposed design options; their feasibility depends on the downstream service.
Do not discard the recovery ledger while such operations remain unresolved. The retention period must cover the real retry and delayed-delivery windows, not only the normal task duration.
Order compensations using dependencies and current constraints
Reverse order is a useful starting point for a linear workflow, but it is not a universal correctness rule. Microsoft notes that compensation ordering can differ from forward ordering and some steps can run in parallel. Determine the order from the actual dependencies and business risks. Compensation ordering considerations.
For the scanner example, canceling collection may need to precede releasing stock if a carrier could still collect it. A payment void might run independently when it shares no necessary resource with either operation. If a dispatch has already happened, the recovery graph changes: a return process may replace a cancellation process.
Each compensating step needs its own deadline, retry classification, success predicate, and escalation condition. Reusing the forward task's almost-expired deadline can make recovery impossible precisely when it becomes necessary. Conversely, an unlimited recovery loop can hide an abandoned customer obligation. Retries and timeouts should express a deliberate recovery policy, not nested default retries.
Handle irreversible boundaries and validate recovery sequences
Sending an email, disclosing information, or physically dispatching equipment cannot be erased by restoring application state. Put the appropriate authorization and verification before that boundary. A later correction may reduce harm or resolve the business issue, but it remains a new event with its own record.
For the proposed service, a material change in cancellation fees or refund amount should produce a new approval proposal. An earlier approval to buy equipment is not automatically authority to accept an unexpected recovery charge. Bind any required human decision to the current proposal and evidence, as described in agent approval gates.
Validate the workflow by injecting failures around every effect boundary:
- Crash after the remote effect commits but before its receipt is stored.
- Deliver a forward result after compensation begins.
- Retry a compensation with the same identity and then with conflicting arguments.
- Change the resource while recovery is waiting.
- Fail one compensation while another succeeds.
- Resume a stored run after its recovery policy changes.
Assert external business state, outstanding obligations, and the final user-facing status. Preserve evidence for unresolved effects. A workflow can terminate its automated execution while recovery work remains assigned to an operator; those must be separate statuses rather than one misleading “done” flag.
Frequently asked questions
Should an LLM choose compensating actions?
It can propose a recovery plan within documented capabilities. Application code should enforce eligibility, authority, identities, ordering constraints, and verification. The model should not create new reversal semantics.
Must every action have a compensation?
No. Some effects are intentionally retained or irreversible. Document the accepted residual state and place appropriate checks before commitment. A fictional undo function is worse than an explicit limit.
Is successful compensation the same as successful fulfillment?
No. The original order failed even if its recoverable effects were safely counteracted. Report both the task outcome and the recovery outcome so product metrics and customer messages remain accurate.
Source reference list
Related reading
- Idempotency for AI Agent Actions: Preventing Duplicate Side Effects
Prevent duplicate AI agent actions with stable intent identities, immutable request fingerprints, durable ledgers, and recovery for uncertain outcomes.
- AI Agent Retries and Timeouts: Deadlines, Jitter, and Retry Budgets
Design AI agent retries around end-to-end deadlines, classified failures, jitter, shared budgets, and cancellation without multiplying unsafe side effects.
- Human-in-the-Loop Agents: Designing Useful Approval Gates
Design human-in-the-loop agent approvals with immutable proposals, qualified reviewers, expiry, durable resumption, and checks against changed resource state.