Running AI Agents in Production: Cost and Reliability

Running an AI agent in production means treating it as a distributed system with a nondeterministic step in the loop. Give every run a budget, a turn limit and a timeout. Trace every model call and tool call. Retry only what is safe to retry, and keep a tested way to stop a run and revoke what it holds. Anthropic’s Building effective agents states the trade-off directly: “The autonomous nature of agents means higher costs, and the potential for compounding errors.”

This hub covers failure modes, cost control, observability, reliability patterns and incident response, and links FindPicked’s detailed guides on each. The budget example below was run on 17 November 2026; other claims link to their primary sources.

Start simpler than you think

Anthropic separates workflows, where “LLMs and tools are orchestrated through predefined code paths,” from agents, where “LLMs dynamically direct their own processes and tool usage.” Its advice is to find “the simplest solution possible” and add complexity only when it pays off. OpenAI’s practical guide to building agents likewise recommends starting with a single agent and moving to multi-agent systems only when needed.

Multi-agent designs cost more and fail in new ways. Anthropic’s multi-agent research system write-up reports that agents typically use about 4 times as many tokens as chat interactions, and multi-agent systems about 15 times as many. It found multi-agent designs suited to work that splits into parallel parts, and less suited to tasks where agents must share context, citing most coding tasks as an example. A study of multi-agent failures, Why Do Multi-Agent LLM Systems Fail?, analyzed more than 1,600 annotated traces across 7 frameworks and grouped 14 failure modes into system design issues, inter-agent misalignment and task verification.

Failure modes and their controls

Failure mode What you see Primary control
Runaway loop The same tool call repeats while turns climb A turn limit plus repeated-call detection
Cost spike Tokens per run jump after a prompt, tool or model change Per-run and per-day budgets; provider spend limits
Rate limits and overload HTTP 429 or 529 responses Backoff that honors retry-after; gradual ramp-up
Context overflow Quality drops or errors late in long runs Compaction and bounded tool output
Tool failure Timeouts and API errors Timeouts, errors returned to the model, idempotent writes
Wrong or unsafe action A plausible but harmful change Approval gates, least privilege, rollback
Silent regression Quality falls after a model or prompt update Pinned versions, regression evals, staged rollout
Coordination failure Sub-agents duplicate or contradict work Clear roles and a verification step

The context and security rows have their own hubs: context engineering and memory and AI agent security and guardrails.

Control cost before it controls you

In an agent loop, input tokens grow with every turn: each turn resends the conversation, and tool results make it larger. Controls work best in layers:

  • Turn limits. Anthropic recommends “stopping conditions (such as a maximum number of iterations).” The OpenAI Agents SDK has a max_turns setting and raises MaxTurnsExceeded when a run passes it.
  • Per-run budgets. Claude Code’s CLI (version 2.1.326) has a --max-budget-usd flag, which works only in non-interactive --print mode.
  • Provider limits. The Claude API lets you set an organization spend limit below your tier’s monthly cap, plus lower limits for individual workspaces. Use them as a backstop, not as your only control.
  • Caching. Repeated prefixes such as tool definitions and system prompts can be cached. At the time of writing, cache reads cost 0.1 times the base input price on most Claude models, and Anthropic’s cache-aware rate limits do not count cache reads toward input tokens per minute.
  • Batching. Work that can wait suits Anthropic’s Message Batches API, which costs 50% less, and most batches finish in under an hour.
  • Smaller scope. Fewer tools, shorter instructions and a cheaper model for simple sub-steps all reduce the per-turn cost.

OWASP calls the failure to set these limits Unbounded Consumption (LLM10:2025) and lists rate limiting, resource allocation management, timeouts and throttling, logging and anomaly detection, and graceful degradation among its mitigations.

A tested run-budget guard

Framework limits differ, so a small guard in your own loop gives one consistent set of limits. This class stops a run on too many turns, too much cost, too much time, or the same tool call repeated with identical arguments. Prices are inputs, not built-in rates.

import json
import time

class BudgetExceeded(RuntimeError):
    pass

class RunBudget:
    """Hard limits for one agent run. Token prices are inputs you supply."""

    def __init__(self, max_turns=30, max_cost_usd=2.00, max_seconds=600,
                 max_identical_calls=3, usd_per_m_input=0.0, usd_per_m_output=0.0):
        self.max_turns, self.max_cost = max_turns, max_cost_usd
        self.deadline = time.monotonic() + max_seconds
        self.max_identical = max_identical_calls
        self.rate_in, self.rate_out = usd_per_m_input, usd_per_m_output
        self.turns, self.cost, self.calls = 0, 0.0, {}

    def charge(self, input_tokens: int, output_tokens: int) -> None:
        """Call after every model response, using the usage the API reports."""
        self.turns += 1
        self.cost += (input_tokens * self.rate_in + output_tokens * self.rate_out) / 1e6
        if self.turns > self.max_turns:
            raise BudgetExceeded(f"turn limit of {self.max_turns} reached")
        if self.cost > self.max_cost:
            raise BudgetExceeded(f"cost ${self.cost:.2f} is over ${self.max_cost:.2f}")
        if time.monotonic() > self.deadline:
            raise BudgetExceeded("wall-clock limit reached")

    def check_tool_call(self, name: str, args: dict) -> None:
        """Call before executing a tool; stops loops that repeat the same call."""
        key = name + json.dumps(args, sort_keys=True)
        self.calls[key] = self.calls.get(key, 0) + 1
        if self.calls[key] > self.max_identical:
            raise BudgetExceeded(f"{name} called {self.calls[key]} times with identical arguments")

A simulated loop started at 12,000 input tokens, added 3,000 per turn as history grew, produced 500 output tokens per turn, and used illustrative rates of $3 and $15 per million input and output tokens. When the simulated agent repeated the same search, and when it varied its arguments but kept going, the guard printed:

stopped after 4 turns, $0.23: search_logs called 4 times with identical arguments
stopped after 18 turns, $2.16: cost $2.16 is over $2.00

The second run shows why input dominates: its 18 turns used 675,000 input tokens and only 9,000 output tokens. It also shows that a check after each call can overshoot by one call, so set the cap below the amount you can actually afford.

Observability: trace every run

You cannot fix what you cannot replay. For each run, record the model and prompt version, token usage including cache reads and writes, latency, every tool call with its arguments and result size, errors, cost, and the outcome of any approval. Anthropic reports that “adding full production tracing let us diagnose why agents failed and fix issues systematically.”

Use a shared vocabulary instead of inventing one. The OpenTelemetry semantic conventions for generative AI, still at Development status, define agent spans such as invoke_agent and tool spans named execute_tool {gen_ai.tool.name}, with attributes such as gen_ai.usage.input_tokens and gen_ai.usage.output_tokens. Capturing prompts, completions and tool arguments is opt-in in these conventions because the content can be sensitive. The MCP 2026-07-28 changelog documents how to pass trace context (traceparent, tracestate, baggage) in request metadata, so a span inside an MCP server can join the agent’s trace.

Alert on signals that precede damage: budget burn rate, repeated identical calls, rising tool error rates, a spike in denied actions, and any new tool or outbound destination.

Reliability patterns

  • Retry the right errors. The Claude API error reference says the official SDK retries connection errors, rate limits and server errors twice by default with exponential backoff, honoring the retry-after header. A 429 caused by the monthly spend cap has no retry-after, and retries fail until access resumes, so stop and alert instead of looping.
  • Ramp up gradually. Anthropic’s ramp limits can return 429 after a sharp jump in usage, even below your rate limits, so start batch jobs slowly.
  • Time out every tool call. The MCP tools specification asks clients to implement timeouts and to log tool usage for audit.
  • Make writes idempotent before you allow automatic retries of anything that changes state.
  • Resume instead of restarting. Anthropic’s research system resumes from where an error occurred, using checkpoints, and uses rainbow deployments so updates do not break agents that are mid-run.
  • Pin and test versions. Treat a model, prompt or tool change as a release: run regression evaluations, then roll out to a small share of traffic first.
  • Plan for provider trouble. Know which model you would fall back to and test that path before you need it.

Incident response for agents

When an agent misbehaves, speed matters more than diagnosis. A short runbook:

  1. Stop: disable the agent or its trigger, cancel running jobs and revoke or rotate its credentials.
  2. Preserve: keep traces, tool-call logs, prompts, diffs and approval records before anything is cleaned up.
  3. Scope: list what the agent’s identity could reach. Per-agent credentials make this step fast; a shared admin key makes it guesswork.
  4. Fix the control: find the guardrail that should have stopped it, then add a test or evaluation that reproduces the failure.
  5. Review without blame: Google’s SRE book says a postmortem “must focus on identifying the contributing causes of the incident without indicting any individual or team” (postmortem culture).

For a broader program, NIST’s SP 800-61 Rev. 3 (April 2025) ties incident response to the Cybersecurity Framework 2.0. The voluntary NIST AI Risk Management Framework, released in January 2023, organizes AI risk work into Govern, Map, Measure and Manage, and its Generative AI Profile (NIST AI 600-1) followed in July 2024.

A production readiness checklist

  • Every run has a turn limit, a cost budget and a wall-clock timeout.
  • Provider spend limits and alerts are set below what you can afford to lose.
  • Each agent has its own credentials, scoped to its task.
  • Every model and tool call is traced, with sensitive content redacted or kept out.
  • Retries cover only transient errors, and writes are idempotent.
  • High-risk actions need approval, and the approval is logged.
  • Model, prompt and tool versions are pinned, with regression evals before upgrades.
  • There is a tested kill switch and a written incident runbook.

Common mistakes

  • Using the provider’s monthly cap as the budget. By the time it trips, the money is spent.
  • Retrying every 429. Spend-cap errors will not clear with retries.
  • Logging full prompts by default. Logs become a second copy of secrets and personal data.
  • Starting with a multi-agent design. It multiplies tokens and failure modes before a single agent has proven the task.
  • Testing only the happy path. Simulate tool timeouts, rate limits and malformed outputs before launch.
  • Upgrading the model without evaluations. Behavior can change even when nothing in your code does.

To compare open-source agents and frameworks before you build, see the AI agent directory, which ranks projects by recorded GitHub stars; popularity alone does not show quality or fit. The workflow-first guide helps you decide whether you need an agent at all.

Frequently Asked Questions

How do I stop an AI agent from running up a large bill?

Use several limits at once: a turn limit and a cost budget for every run, timeouts on tool calls, alerts on spending rate, and a provider spend limit as a backstop. Check the budget after every model call and set it below the amount you can afford, because a check can overshoot by one call.

What should I log for an AI agent in production?

For each run, log the model and prompt version, token usage including cache reads and writes, latency, every tool call with its arguments and result size, errors, cost and approval decisions. Redact secrets and personal data, and treat prompt and output capture as opt-in.

Should I retry when the model API returns HTTP 429?

Retry with backoff when the response is a rate limit with a retry-after header. Do not loop on a 429 caused by a spend cap: on the Claude API it has no retry-after header, and retries fail until access resumes.

When is a multi-agent system worth it?

When the work splits into independent parallel parts, such as broad research, and the value justifies much higher token use. For tasks where agents must share context, such as most coding work, start with a single agent and add more only when tests show a gain.