FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Agent Failure Recovery

Design retries, compensation, escalation, and safe termination around typed agent failure states.

Freshness: current•15 min read•Agentic Systems and Protocols

Key Learning Outcomes

  • ✓Explain the operating model behind Agent Failure Recovery.
  • ✓Evaluate trade-offs and failure modes for Agent Failure Recovery.
  • ✓Apply Agent Failure Recovery to a production decision.
Full Technical Reference Document

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.

Tool / model failure caught
Classify into typed fault taxonomy
Inspect remote state & idempotency log
Execute backoff, saga undo, or pause
Resume checkpoint or escalate cleanly
Conceptual teaching model synthesized from:Trustworthy Agents in PracticeSite Reliability Engineering

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 ClassSide-Effect RiskDeterministic Orchestrator ResponseLLM Involvement
HTTP 429 / 503 / Socket ResetNone (idempotent read) or keyedExponential backoff + jitter within remaining step budgetNone (orchestrator handles silently)
Schema / Argument Validation ErrorZero (rejected pre-execution)Return typed Zod/Pydantic error message once (max 2)Model repairs missing/wrong field cleanly
Policy / Auth / ACL DenialBlocked (unauthorized)Terminate sensitive branch immediately; never evade guardrailsReport refusal gracefully to caller
Ambiguous Mutating TimeoutHigh (charge/delete may have succeeded)Query authoritative ledger/resource via idempotency key FIRSTOnly 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.

python
import time
from dataclasses import dataclass
from typing import Literal
​
FaultKind = Literal["transient_network", "schema_error", "policy_denied", "ambiguous_mutation"]
​
@dataclass(frozen=True)
class ToolFailure:
step_id: str
idempotency_key: str
fault: FaultKind
message: str
​
def 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_transfer or create_ticket without 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 refund or rollback calls 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.

Reflect before revealing the guide

What authoritative state check must execute before retrying any mutating agent tool whose prior timeout left outcomes ambiguous?

Prerequisites & Related Concepts (4)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-301Agentic Systems Engineer

Engineer bounded tool-using systems with explicit workflows state protocols evaluation observability security and human control.

27 concepts~29h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next