Home / Articles

Layered Retries for Production AI Agents

Layered retries for production AI agents: LLM call backoff, tool-error recovery, checkpoints and durable workflows, so flaky APIs and crashes don't kill runs.

Publisher: REACTAPP.TOP10 min read2377 words

This article is published in English.

Sources: Building Retries in Agents: How to Build AI Agents That Survive Failures

Agent retries that survive real failures

A toy agent with two tools and a while loop looks fine until the first rate limit, flaky API, or mid-plan crash. Production agents need layered resilience — not one try/except around the LLM.

Failures are not alike

Classify before you retry:

  • Transient LLM/API errors (429, 503, timeouts)
  • Tool errors the model can fix (bad args, missing fields)
  • Logic dead-ends (wrong plan) needing replanning
  • Process/infra crashes losing in-memory state

Blind retries on the wrong class waste money and amplify bad actions.

Layer 1 — Retry the LLM call

Idempotent completion requests get exponential backoff with jitter:

from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
import anthropic

llm_retry = retry(
    stop=stop_after_attempt(2),           # 2 total attempts (1 retry)
    wait=wait_exponential(multiplier=2, min=4, max=60),
    retry=retry_if_exception_type((
        anthropic.RateLimitError,          # 429
        anthropic.APITimeoutError,         # Timeout
        anthropic.APIConnectionError,      # Network errors
        anthropic.InternalServerError,     # 500s (often transient)
    )),
)

@llm_retry
async def call_llm(messages, tools):
    response = client.messages.create(
        model="claude-sonnet-4-5-20250929",
        messages=messages,
        tools=tools,
    )
    return response

Cap attempts; surface a typed error when budget is gone.

Layer 2 — Let the model handle tool errors

Return tool failures as observations, not hard crashes, so the agent can correct arguments:

# Inside the agentic loop
for block in response.content:
    if block.type == "tool_use":
        try:
            result = run_tool(block.name, block.input)
            tool_results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": json.dumps(result),
            })
        except Exception as e:
            tool_results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": f"Error: {str(e)}",
                "is_error": True,
            })

Claude Code–style loops treat stderr/stdout as context for the next thought.

@agent.tool
async def process_document(ctx, file_path: str) -> dict:
    """Process a document through the enrichment pipeline."""
    try:
        result = await run_enrichment(file_path)

        if result.status == "error":
            raise RuntimeError(f"Processing failed: {result.error}")

        return {
            "status": "success",
            "records_processed": result.count,
            "output_path": result.output_path,
        }
    except Exception as e:
        return {
            "status": "error",
            "error": str(e),
            "traceback": traceback.format_exc(),
        }

Layer 3 — Agent-level resilience

Progressive checkpointing

Persist plan steps, tool results, and conversation slices so a restart continues instead of redoing paid work:

async def execute_with_resilience(agent, prompt, deps, max_retries=3):
    """Execute agent with checkpoint-based retry."""
    message_history = []

    for attempt in range(max_retries):
        try:
            result = await agent.run(
                prompt,
                deps=deps,
                message_history=message_history,  # Resume from last checkpoint
            )
            return result

        except (RateLimitError, APITimeoutError, APIConnectionError) as e:
            if attempt == max_retries - 1:
                raise  # Final attempt failed

            # Checkpoint: save what we have so far
            # How you access partial messages depends on your framework.
            # PydanticAI exposes all_messages() on the result; other frameworks
            # may store it differently. The key is: grab whatever history exists.
            if hasattr(e, '_partial_messages'):
                message_history = e._partial_messages

            # Also save context that tools have accumulated
            save_checkpoint({
                "message_history": message_history,
                "context_fields": deps.get_context_snapshot(),
            })

            wait_time = min(2 ** attempt * 5, 60)
            logger.warning(
                f"Agent run failed (attempt {attempt + 1}/{max_retries}), "
                f"retrying in {wait_time}s with {len(message_history)} messages"
            )
            await asyncio.sleep(wait_time)

Checkpoint after successful tool side effects especially.

Layer 4 — Infra crashes and Temporal

Durable workflows shine when steps must survive worker death:

# After each successful tool call, save a checkpoint
async def on_tool_complete(tool_name, result, current_messages):
    """Called after each tool completes successfully."""
    save_checkpoint({
        "message_history": current_messages,
        "last_completed_tool": tool_name,
        "context_fields": get_current_context(),
    })
    logger.info(f"Checkpoint saved after {tool_name}")

Where Temporal helps

Long-running approvals, human-in-the-loop, multi-hour tool chains.

Where it gets heavy

Simple chat agents may not need a workflow engine; the ops cost can exceed the risk.

When to use it

Use Temporal (or similar) when side effects must be exactly-once and runs outlive a process. Skip it for short request/response agents with cheap retries.

A lighter production pattern

Many teams combine: LLM retries + tool-error observations + Redis/DB checkpoints + a supervisor that resumes from the last completed step — without full workflow orchestration on day one.

from temporalio.common import RetryPolicy

TOOL_RETRY_POLICY = RetryPolicy(
    maximum_attempts=2,
    initial_interval=timedelta(seconds=5),
    backoff_coefficient=2.0,
)

Checklist

SandboxRestrictions.default.with_passthrough_modules(
    "anthropic", "httpx", "httpcore", "os", "anyio",
    "anyio._backends", "anyio._backends._asyncio", "threading",
    "pydantic_ai", "pydantic_ai.agent",
    "pydantic_ai.durable_exec", "pydantic_ai.durable_exec.temporal",
    "pydantic_graph", "pydantic_graph.beta", "fitz",  # ... and more
)
  • Backoff on transient LLM errors
  • Tool errors as messages, not silent kills
  • Checkpoints after mutating tools
  • Timeouts and max-step budgets
  • Idempotency keys on writes
  • Metrics: retry rate, step latency, abandon rate

Next

Add chaos tests: kill the process mid-tool, inject 429s, and assert resume behavior. Resilience is a product feature for agents, not an afterthought.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.

Budget max steps and max dollars per run; kill switches belong next to retry knobs.