Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← AgentsAI guideAdvanced#agents#production#durable-execution#observability
Frame · ai-engineering / agents / 12-agents-in-production.mdGuide 036 / 103

Running agents in production

A demo agent runs once, on a laptop, while you watch. A production agent runs thousands of times, for minutes or hours, across deploys, rate limits, flaky APIs and the occasional crashed pod. Almost none of that is about prompts. This doc is the plumbing checklist I wish I had the first time I put an agent behind a real queue.

Why it matters

Agents have the worst reliability profile of any LLM feature. They make many sequential calls, so the probability that something fails during a run is high. They have side effects, so naive retries can send an email twice. They are non-deterministic, so "just rerun it" may not reproduce the bug. And their cost is unbounded unless you bound it.

Production readiness for agents comes down to five properties: runs survive failures (durability), failures are retried safely (idempotency), runs end (timeouts and budgets), you can see what happened (observability), and you can stop things quickly (kill switches).

How it works

Durable execution

Durable execution engines record each step of a workflow so that, after a crash, the run resumes from the last completed step instead of starting over. Temporal is the best-known example and ships an official integration for the OpenAI Agents SDK in Python: the agent loop runs inside a Temporal workflow while each model call becomes an activity, so model calls are retried durably and are not repeated when the workflow replays. Tools that touch the outside world should also run as activities, because workflow code must be deterministic.

You do not always need a separate engine. LangGraph checkpoints graph state per thread after each step, which gives you resume-after-failure and human-in-the-loop pauses. Whatever you use, the principle is the same: persist state at step boundaries, and make each step safe to retry.

Retries, timeouts and idempotency

  • Model calls: retry on rate limits, overloaded and network errors with exponential backoff. Official SDKs already do some of this; configure the retry count and timeout rather than stacking your own retries on top.
  • Tool calls: wrap each in a timeout. Return timeouts to the model as an error result so it can adapt.
  • Side effects: use idempotency keys (for example, run ID plus step number) so a retried "send invoice" is a no-op the second time.
  • Run-level limits: maximum turns, wall-clock deadline, and a token or dollar budget, all enforced in code.

Observability

Trace every run as a tree: one span for the agent invocation, child spans for each model call and each tool execution. The OpenTelemetry GenAI semantic conventions define operation names like invoke_agent and execute_tool, plus attributes for model, token usage and tool names. Those conventions are still marked as in development, so expect some attribute names to change, but adopting them now lets you switch tracing backends without rewriting instrumentation. Prompt and completion content capture is typically opt-in because it often contains personal data.

Rendering diagram…

Reference architecture

Rendering diagram…

A model gateway centralises retries, rate limiting, fallbacks and cost accounting so every agent does not reimplement them. The kill switch lets on-call stop a misbehaving agent globally in seconds.

Code

A Python agent loop instrumented with OpenTelemetry, with SDK-level retries and timeout, a per-run dollar budget, and tool timeouts. Prices are placeholders: load real ones from your provider's pricing page or your gateway.

import concurrent.futures as cf
import anthropic
from opentelemetry import trace

tracer = trace.get_tracer("support-agent")
client = anthropic.Anthropic(max_retries=4, timeout=60.0)
pool = cf.ThreadPoolExecutor(max_workers=4)

PRICE_PER_MTOK = {"input": 0.0, "output": 0.0}  # fill from your pricing source

class BudgetExceeded(Exception):
    pass

def cost(usage) -> float:
    return (usage.input_tokens * PRICE_PER_MTOK["input"]
            + usage.output_tokens * PRICE_PER_MTOK["output"]) / 1_000_000

def run_tool(fn, args: dict, timeout_s: float = 20.0) -> str:
    with tracer.start_as_current_span(f"execute_tool {fn.__name__}") as span:
        span.set_attribute("gen_ai.operation.name", "execute_tool")
        span.set_attribute("gen_ai.tool.name", fn.__name__)
        try:
            return pool.submit(fn, **args).result(timeout=timeout_s)
        except cf.TimeoutError:
            span.set_attribute("error.type", "timeout")
            return f"Error: {fn.__name__} timed out after {timeout_s}s. Try a narrower request."

def run_agent(run_id: str, messages: list, tools: list, registry: dict,
              max_turns: int = 10, budget_usd: float = 0.50) -> list:
    spent = 0.0
    with tracer.start_as_current_span("invoke_agent support") as root:
        root.set_attribute("gen_ai.operation.name", "invoke_agent")
        root.set_attribute("app.run_id", run_id)
        for turn in range(max_turns):
            resp = client.messages.create(model="claude-opus-5-5", max_tokens=1024,
                                          tools=tools, messages=messages)
            spent += cost(resp.usage)
            root.set_attribute("app.cost_usd", spent)
            messages.append({"role": "assistant", "content": resp.content})
            if resp.stop_reason != "tool_use":
                return messages
            if spent > budget_usd:
                raise BudgetExceeded(f"run {run_id} spent ${spent:.2f}")
            results = [{"type": "tool_result", "tool_use_id": b.id,
                        "content": run_tool(registry[b.name], b.input)}
                       for b in resp.content if b.type == "tool_use"]
            messages.append({"role": "user", "content": results})
            # checkpoint(run_id, turn, messages, spent) goes here
        raise RuntimeError(f"run {run_id} hit max_turns={max_turns}")

Configure an OpenTelemetry exporter at process start, and every run becomes a trace you can filter by run ID, cost and failing tool.

Trade-offs and pitfalls

  • Retry storms. Retrying at the SDK, the gateway and the job queue multiplies attempts. Pick one layer per failure type.
  • Retrying non-idempotent tools. Without keys, durability makes duplicates more likely, not less.
  • Checkpoint size. Storing the full conversation every step gets expensive on long runs. Store deltas or compact before checkpointing.
  • Version skew. A run paused on Monday may resume on code deployed Wednesday. Version your prompts, tools and state schema, and handle old checkpoints.
  • Silent degradation. Agents rarely crash; they get worse. Track task success, turns per run, cost per run and tool error rates, and alert on drift, alongside offline evals.
  • Logging sensitive content. Full prompts in traces are invaluable for debugging and a liability for privacy. Redact, sample, and restrict access.
  • Fallback models behave differently. A fallback that has never been evaluated with your tools is a new, untested agent.

Checklist

  • Runs execute on a durable queue or workflow engine with per-step checkpoints.
  • Model calls have one retry layer with backoff and a timeout.
  • Every tool call has a timeout and side effects use idempotency keys.
  • Each run enforces max turns, a wall-clock deadline and a cost budget.
  • Traces follow the OpenTelemetry GenAI conventions with run IDs and cost.
  • Dashboards track success rate, cost, latency and tool errors per agent.
  • A kill switch can disable an agent or a tool globally within seconds.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.