Mental model
Agent failure recovery is a deterministic state transition inside the orchestrator runtime rather than an open-ended prompt asking the LLM to "try again". Reliable agents classify faults into typed operational categories, inspect authoritative external state before repeating ambiguous writes, restore clean checkpoints, and decide systematically between jittered backoff retry, compensating rollback, or human escalation.
Learning outcomes
- Categorize runtime errors distinctly into transient infrastructure faults, deterministic schema violations, policy blocks, and ambiguous side-effect timeouts.
- Prevent duplicate external charges, emails, and CRM mutations using idempotency keys paired with read-before-retry ledger lookups.
- Implement compensating saga transactions and graceful human escalation paths when distributed mutations cannot roll back atomically.
Theory
Treating every failure identically with a naive LLM retry loop corrupts real-world production state rapidly: a payment timeout leaves the user unsure whether charge settlement committed on the upstream gateway, an OAuth permission failure loops uselessly until budget exhaustion, and malformed arguments often repeat identically unless structured schema hints accompany the correction. Durable agent orchestrators classify errors cleanly across explicit handling branches:
| Fault Class | Side-Effect Risk | Deterministic Orchestrator Response | LLM Involvement |
|---|---|---|---|
HTTP 429 / 503 / Socket Reset | None (idempotent read) or keyed | Exponential backoff + jitter within remaining step budget | None (orchestrator handles silently) |
| Schema / Argument Validation Error | Zero (rejected pre-execution) | Return typed Zod/Pydantic error message once (max 2) | Model repairs missing/wrong field cleanly |
| Policy / Auth / ACL Denial | Blocked (unauthorized) | Terminate sensitive branch immediately; never evade guardrails | Report refusal gracefully to caller |
| Ambiguous Mutating Timeout | High (charge/delete may have succeeded) | Query authoritative ledger/resource via idempotency key FIRST | Only resume after external state is confirmed |
When a multi-step agent workflow spans unrelated third-party SaaS endpoints lacking two-phase distributed commits (for example, provisioning a cloud cluster succeeded while assigning DNS records failed permanently), recovery must execute forward saga compensation (issue release_cluster(op_id) rather than hoping transient retries fix invalid quota limits). Crucially, compensation triggers strictly against verified committed receipt logs so the orchestrator never issues spurious undo actions for steps that never ran.
pythonimport timefrom dataclasses import dataclassfrom typing import LiteralFaultKind = Literal["transient_network", "schema_error", "policy_denied", "ambiguous_mutation"]@dataclass(frozen=True)class ToolFailure:step_id: stridempotency_key: strfault: FaultKindmessage: strdef route_recovery_action(err: ToolFailure,attempts_used: int,max_attempts: int = 3,remote_ledger_check=None,) -> dict[str, object]:"""Deterministically route recovery without duplicating committed side effects."""if err.fault == "policy_denied":return {"action": "halt_and_notify", "retryable": False, "reason": err.message}if err.fault == "ambiguous_mutation" and remote_ledger_check is not None:if remote_ledger_check(err.idempotency_key) == "committed":return {"action": "reconcile_as_done", "retryable": False}if attempts_used < max_attempts:return {"action": "safe_retry_same_key", "retryable": True, "backoff_s": 2 ** attempts_used}return {"action": "escalate_human_operator", "retryable": False}if err.fault == "transient_network" and attempts_used < max_attempts:return {"action": "jittered_retry", "retryable": True, "backoff_s": 1.5 * (attempts_used + 1)}if err.fault == "schema_error" and attempts_used < 2:return {"action": "inject_validation_hint", "retryable": True, "hint": err.message}return {"action": "run_saga_compensation_then_escalate", "retryable": False}
Trade-offs
Automatic orchestrator-managed retries and self-healing schema repairs boost task completion rates substantially on transient cloud hiccups and minor tool formatting glitches, saving human operator intervention cleanly. However, overly aggressive blind retries over ambiguous network timeouts duplicate customer invoices, bloat cumulative model latency budgets, and worsen downstream outages during dependency brownouts. Raising escalation conservatism (requiring read-after-write verification or human approval on any irreversible state transition exceeding defined value floors) slows recovery speed slightly on rare anomalies while completely eliminating catastrophic duplicate-mutation incidents.
Failure modes and misconceptions
- Retrying Unkeyed Mutating Tools After Timeouts: Resubmitting
send_wire_transferorcreate_ticketwithout idempotency keys doubles charges whenever responses stall in transit. - Letting Models Loop Around Policy Denials: Feeding
"403 Unauthorized"straight back into open prompt loops triggers stubborn agents to invent creative jailbreak workarounds or alternative unauthorized queries. - Resetting Budget Counters Inside Recovery: Giving each error recovery subgraph fresh token/time allocations lets broken loops run indefinitely until gateway shutdown.
- Blind Compensation Without Verification: Triggering
refundorrollbackcalls before confirming whether the original forward action actually persisted on disk.
Decision scenario
A B2B billing assistant invokes an external Stripe/ERP refund endpoint that throws an HTTPS 504 Gateway Timeout after 10 seconds. Design an idempotency-key ledger schema, primary read-before-retry probe, saga rollback rules if invoice reconciliation disagrees, and clean human escalation handoff that prevents double refunds under load.
What authoritative state check must execute before retrying any mutating agent tool whose prior timeout left outcomes ambiguous?