The Morning Our AI Agent Cost $0.90 Per Run — Runaway Loops, Context Snowballs, and the Tiering Fix That Took It to $0.12
Our agent cost $0.90 per run — dead unit economics. Cost = price x tokens x iterations: the runaway loops, the real fix, and the $0.12 result.
- Author
- Randhir Jassal
- Published
- Reading time
- 22 min read
- Views
- 6 views
AI in Production: War Stories, Scenario #2. One real production incident per post: the alert, the triage (dead ends included), the root cause, the fix with runnable code, the measured result — then how to tell it in a senior interview, with the follow-ups you'll actually get. Scenario #1 was the hallucination incident. This one is about money.
The incident
Mattrx Insights is the agentic side of our marketing SaaS: a user asks "why did the Northwind campaign's conversion drop last week?", and an agent plans the investigation, calls governed analytics APIs through our MCP layer, cross-references segments, and writes a finding. In the pilot it was magic. Then finance forwarded the model-provider invoice with one cell highlighted.
The math was simple and ugly. The pilot cohort was running about 400 agent runs a day. Average cost per run: $0.90. That's $360 a day — a ~$11,000/month run-rate for a feature we planned to roll out to a customer base 20x the pilot's size. At full rollout, the unit economics were dead on arrival: the feature would cost more to serve than the plan tier it shipped in.
Nobody had done anything wrong, exactly. Every individual decision — "use the strong model, it's smarter", "let the agent keep working until it's done", "pass the tool output back so it has full context" — was locally reasonable. Together they compounded into a money fire. This is the most common agent incident there is, and almost every team hits it in their first quarter of running agents.
Architecture: where the money leaked
MATTRX INSIGHTS - AGENT LOOP (BEFORE)
User question
|
v
+-------------------------------------------------------------+
| AGENT LOOP |
| |
| one premium model for EVERY step [C1] |
| | |
| v |
| +---------+ tool_use +-----------------+ |
| | model |------------->| execute tool | |
| | call |<-------------| (analytics API) | |
| +---------+ raw JSON +-----------------+ |
| | (10-50 KB per result) [C4] |
| | |
| append EVERYTHING to history, resend it all, |
| no caching -> input grows every iteration [C3] |
| | |
| loop until the model stops. No iteration cap, |
| no token budget, no cost budget [C2] |
| | |
| tool failed? model retries the same call again |
| (and again) [C5] |
+-------------------------------------------------------------+
[C1] Premium model prices applied to routing, glue, and summary
steps a cheap model handles fine.
[C2] Unbounded loop: the agent decides when it's done, with no
budget pressure. Worst run we found: 41 iterations.
[C3] Context snowball: full history resent every iteration ->
input tokens grow roughly quadratically with iterations.
[C4] Raw tool output: 10-50 KB of JSON per result, re-billed on
every subsequent iteration via [C3].
[C5] Failure loops: a tool erroring at iteration 3 gets retried
by the model itself at 4, 5, 6... each retry re-bills the
whole snowball.
Triage: what we checked first (including the dead ends)
- "The provider is expensive — negotiate or switch." Dead end. Price-per-token was maybe 20% of the story. We modeled it: switching everything to a cheaper provider at the same architecture still left us ~$0.55/run. The architecture, not the rate card, was the bill.
- "Cap max_tokens hard." Dead end — and a user-facing bug. Someone set
max_tokens=800globally. Findings came back truncated mid-sentence; runs then retried, costing more. Output tokens were never the problem — fewer than 8% of spend. - Token telemetry per run — first real signal. We logged
usage.input_tokensper iteration and plotted them. The curve was the tell: iteration 1 cost 4k input tokens, iteration 8 cost 38k. Input tokens, re-billed history, dominated everything. - Iteration histogram — second real signal. p50 was 5 iterations. p95 was 18. And 12% of runs exceeded 10 — almost all of them hammering a failing or misparameterized tool in a loop. One run hit 41 iterations overnight: $7+ for one unanswered question.
Root cause, stated plainly: agent cost is price x tokens x iterations, and we were managing none of the three. The strong model multiplied the price, the snowballing context multiplied the tokens, and the unbounded loop multiplied the iterations. Multiplication is the whole story — that's why agent bills surprise teams that are used to linear, per-request LLM costs.
The broken loop — a POC you can run
A faithful miniature of the before-state. Give flaky_tool a few failures and watch the bill meter climb.
# broken_agent.py - reproduces the cost explosion. Do NOT ship this.
import json
import anthropic
client = anthropic.Anthropic()
TOOLS = [{
"name": "query_analytics",
"description": "Run an analytics query against campaign data",
"input_schema": {
"type": "object",
"properties": {"metric": {"type": "string"}, "segment": {"type": "string"}},
"required": ["metric", "segment"],
"additionalProperties": False,
},
}]
def query_analytics(metric: str, segment: str) -> str:
# Real tool returned 10-50 KB of raw JSON. Simulate the bloat:
return json.dumps({"metric": metric, "segment": segment,
"rows": [{"day": d, "value": 100 + d} for d in range(500)]})
def run(question: str) -> str:
messages = [{"role": "user", "content": question}]
while True: # [C2] no budget of any kind
response = client.messages.create(
model="claude-opus-5-5", # [C1] premium model, every step
max_tokens=4096,
tools=TOOLS,
messages=messages, # [C3] full history, no caching
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return next(b.text for b in response.content if b.type == "text")
results = []
for block in response.content:
if block.type == "tool_use":
out = query_analytics(**block.input) # [C4] raw dump
results.append({"type": "tool_result",
"tool_use_id": block.id, "content": out})
messages.append({"role": "user", "content": results})
# [C5] if the tool errors, nothing stops the model retrying forever
Nothing here is exotic — this is the agent loop from every quickstart tutorial. Quickstarts optimize for "works"; production optimizes for "works at a price."
The fix: manage all three multipliers
Price, tokens, iterations. One mechanism per multiplier, plus a meter so regressions can't hide.
# governed_agent.py - the production loop. Python 3.11+, pip install anthropic
import hashlib
import json
import logging
import os
from dataclasses import dataclass, field
import anthropic
log = logging.getLogger("mattrx.insights.agent")
client = anthropic.Anthropic(max_retries=3, timeout=60.0)
# ---- Multiplier 1: PRICE - model-per-role tiering --------------------------
# Routing/classification is a small-model task. Synthesis is a mid-model
# task. Only genuinely hard planning earns the premium model, per run,
# by escalation - never by default.
MODEL_ROUTER = os.getenv("AGENT_MODEL_ROUTER", "claude-haiku-5-5")
MODEL_WORKER = os.getenv("AGENT_MODEL_WORKER", "claude-sonnet-5-5")
MODEL_ESCALATION = os.getenv("AGENT_MODEL_ESCALATION", "claude-opus-5-5")
# $/1M tokens (input, output) - keep in config, prices change.
PRICES = {
"claude-haiku-5-5": (0.10, 0.50),
"claude-sonnet-5-5": (2.00, 10.00),
"claude-opus-5-5": (4.00, 20.00),
}
# ---- Multiplier 3: ITERATIONS - explicit budgets ---------------------------
MAX_ITERATIONS = int(os.getenv("AGENT_MAX_ITERATIONS", "10"))
MAX_COST_USD = float(os.getenv("AGENT_MAX_COST_USD", "0.25"))
WRAP_UP_AT = 0.8 # at 80% of any budget, tell the agent to conclude
@dataclass
class RunMeter:
"""Cost accounting from actual API usage - the number finance sees
must be computable from our own logs, not reverse-engineered from
the invoice at month end."""
cost_usd: float = 0.0
iterations: int = 0
tool_signatures: dict[str, int] = field(default_factory=dict)
def add(self, model: str, usage) -> None:
inp, out = PRICES[model]
# Cached reads bill at ~10% of input rate - count them honestly.
cached = getattr(usage, "cache_read_input_tokens", 0) or 0
fresh = usage.input_tokens
self.cost_usd += (fresh * inp + cached * inp * 0.1
+ usage.output_tokens * out) / 1_000_000
def over(self) -> bool:
return self.iterations >= MAX_ITERATIONS or self.cost_usd >= MAX_COST_USD
def near(self) -> bool:
return (self.iterations >= MAX_ITERATIONS * WRAP_UP_AT
or self.cost_usd >= MAX_COST_USD * WRAP_UP_AT)
# ---- Multiplier 2: TOKENS - compact tool results, cache the prefix ---------
def compact_tool_result(raw: str, run_id: str, tool_use_id: str) -> str:
"""The model needs the SHAPE and the HEADLINE numbers, not 500 rows.
Full payload goes to the run store; the context gets a digest + a
reference the model can ask to expand (it almost never needs to)."""
try:
data = json.loads(raw)
except json.JSONDecodeError:
return raw[:2000]
rows = data.get("rows", [])
digest = {
"metric": data.get("metric"),
"segment": data.get("segment"),
"row_count": len(rows),
"first_rows": rows[:5],
"last_rows": rows[-5:],
"full_result_ref": f"{run_id}/{tool_use_id}", # stored server-side
}
return json.dumps(digest)
def detect_loop(meter: RunMeter, name: str, args: dict) -> bool:
"""[C5] killer: the same tool with the same arguments twice is a retry
loop, not progress. Deterministic, zero cost."""
sig = hashlib.md5((name + json.dumps(args, sort_keys=True)).encode()).hexdigest()
meter.tool_signatures[sig] = meter.tool_signatures.get(sig, 0) + 1
return meter.tool_signatures[sig] > 2
SYSTEM = ("You are Mattrx Insights, an analytics investigation agent. "
"Work efficiently: plan before calling tools, never repeat a "
"call that failed with the same arguments, and prefer one "
"well-chosen query over several exploratory ones.")
WRAP_UP = ("Budget notice: you are near your run budget. Stop gathering "
"data and write your best conclusion from what you already "
"have, stating any caveats.")
def run(question: str, run_id: str, execute_tool, tools: list[dict],
complexity: str = "standard") -> tuple[str, RunMeter]:
# Escalation is a per-run decision made by a cheap router upstream;
# 'complex' is earned (multi-entity causal questions), not default.
model = MODEL_ESCALATION if complexity == "complex" else MODEL_WORKER
meter = RunMeter()
messages: list[dict] = [{"role": "user", "content": question}]
wrap_up_sent = False
while True:
meter.iterations += 1
response = client.messages.create(
model=model,
max_tokens=4096,
# Stable system prompt + stable tool list cached across
# iterations AND runs; history grows after the breakpoint.
system=[{"type": "text", "text": SYSTEM,
"cache_control": {"type": "ephemeral"}}],
tools=tools,
messages=messages,
)
meter.add(model, response.usage)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
text = next((b.text for b in response.content if b.type == "text"), "")
log.info("run_done", extra={"run_id": run_id,
"cost_usd": round(meter.cost_usd, 4),
"iterations": meter.iterations})
return text, meter
if meter.over():
log.warning("budget_exhausted", extra={"run_id": run_id,
"cost_usd": meter.cost_usd})
return ("I hit the investigation budget before finishing. "
"Partial findings above; a human analyst has been "
"notified to complete this."), meter
results = []
for block in response.content:
if block.type != "tool_use":
continue
if detect_loop(meter, block.name, block.input):
results.append({"type": "tool_result", "tool_use_id": block.id,
"is_error": True,
"content": "Repeated identical call blocked. "
"Change your approach or conclude."})
continue
raw = execute_tool(block.name, block.input)
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": compact_tool_result(raw, run_id, block.id)})
messages.append({"role": "user", "content": results})
if meter.near() and not wrap_up_sent:
# Mid-conversation system message: operator instruction that
# doesn't invalidate the cached prefix.
messages.append({"role": "system", "content": WRAP_UP})
wrap_up_sent = True
The design decisions that matter:
- Budgets end runs gracefully, not abruptly. At 80% of budget the agent gets a system-channel instruction to conclude with what it has. Hard-stopping at 100% still exists, but it's the fallback — a wrapped-up partial answer with caveats beats a dead cursor, and the human-escalation path (same pattern as Scenario #1's abstention) owns the remainder.
- The loop detector is deterministic. Same tool + same arguments, third time: blocked, with an error message that redirects the model. The 41-iteration run would have died at iteration 5, having spent cents.
- Compaction keeps a reference, not just a summary.
full_result_refmeans the model can request the full payload through a fetch tool if the digest isn't enough. In practice it asked for an expansion in under 2% of runs — the other 98% were paying the full-payload tax for nothing. - The meter is first-class.
RunMetercomputes cost from actualusagefields per call, logs it per run, and feeds a dashboard and an alert (p95 cost/run). Cost regressions now page us before finance does.
Every cost-explosion case — and which control catches it
Agent bills blow up in six distinguishable ways. Diagnose by symptom; each has its own fix:
| # | Case | Symptom in telemetry | Control that catches it |
|---|---|---|---|
| 1 | Runaway loop on a failing tool | Iteration count spikes; same tool signature repeats | Loop detector + iteration budget |
| 2 | Context snowball | Input tokens grow superlinearly across iterations | Tool-result compaction + caching |
| 3 | Over-modeled simple steps | High cost on runs with trivial questions | Router tiering (cheap model classifies complexity) |
| 4 | Verbose tool results | Single iterations with huge input deltas | Compaction with reference escape hatch |
| 5 | Retry amplification | Whole-run retries after timeouts; duplicate run_ids | Idempotent runs + budget carried across retries |
| 6 | Cache-miss bleed | cache_read_input_tokens near zero on repeat calls | Byte-stable system/tool prefix; volatile data after the breakpoint |
Case 6 deserves a confession: our first caching attempt saved nothing. The system prompt included a freshly formatted timestamp — a single changing byte at the top of the prefix, so every request was a cache miss. If your cache_read_input_tokens is ~0 across iterations, hunt for the volatile byte; it's almost always a timestamp, a UUID, or unsorted JSON.
What it cost to fix — and the quality guardrail
Cost optimization that quietly degrades answers is just a slower incident. Every change above ran through our eval gate — the same golden-set discipline from Scenario #1, scored on investigation accuracy and completeness, with a hard floor of 0.90 — before it shipped:
- Tiering (worker on the mid-tier model): eval score moved from 0.93 to 0.92 — inside noise, passed the gate. Routing on the small model was indistinguishable; only unforced escalation to the premium model on "complex"-classified runs (about 9% of traffic) held the score there.
- Compaction: no measurable eval change — the digests carried the signal. The 2% expansion rate confirmed the reference escape hatch was the right pressure valve.
- Budgets: 3% of runs now end with a budgeted partial answer. We count these as successes with caveats in the product metric, and each one files a gap ticket.
Side benefit we didn't optimize for: smaller contexts are faster. p95 latency improved noticeably from compaction alone — but the full latency war is its own incident, and it's the next post.
Results
| Metric | Before | After |
|---|---|---|
| Cost per run (mean) | $0.90 | $0.12 |
| Input tokens per run (p50) | ~140k | ~24k |
| Iterations (p95) | 18 | 6 |
| Runs exceeding 10 iterations | 12% | 0.4% |
| Eval score (gate: 0.90 floor) | 0.93 | 0.92 |
| Projected cost at full rollout | ~$216k/yr | ~$29k/yr |
87% cost reduction, quality statistically unchanged, and — the part I underline in every retro — the meter is permanent. The $0.12 isn't a trophy; it's a monitored SLO with an alert on it.
In the interview
The 60-second STAR version: "Our agentic analytics feature cost $0.90 per run in pilot — dead unit economics at rollout scale (Situation). I owned cutting cost without degrading answer quality, which we measured with a golden-set eval gated at 0.90 (Task). Agent cost is price times tokens times iterations, so I attacked all three: model-per-role tiering with escalation instead of a default premium model; context control via deterministic tool-result compaction and prompt caching; and explicit run budgets with a graceful wrap-up instruction plus a deterministic repeated-call detector (Action). Cost fell 87% to $0.12/run with the eval score inside noise, p95 iterations fell from 18 to 6, and cost-per-run became a monitored SLO with alerting so it can't silently regress (Result)."
The five follow-ups you will get — and senior answers:
- "Why not just use the cheapest model everywhere?" — Because the eval gate failed when we tried: complex causal investigations dropped below 0.90. Tiering is an empirical boundary, not a vibe — the router sends ~9% of runs to the premium model because the data said that slice needs it.
- "How do you know cost per run, exactly?" — From
usagefields on every response, priced through a config table, aggregated per run_id. If your cost number comes from the invoice divided by run count, you can't attribute regressions; per-call accounting is the senior answer. - "Budgets could cut off a run mid-investigation — how do users experience that?" — Two-stage: a wrap-up instruction at 80% so the agent concludes with caveats, hard stop at 100% with human escalation. 3% of runs end budgeted; they're labeled honestly in the product, not disguised as full answers.
- "What stops this regressing next quarter?" — The meter is in CI and production both: evals run with cost assertions (a prompt change that doubles tokens fails the build), and production alerts on p95 cost/run. Regressions page an engineer, not finance.
- "What's the remaining waste?" — The honest answer: multi-turn conversations re-investigate context the previous run already gathered. Cross-run memory of findings is the next lever — with its own staleness risks, which is why it isn't shipped yet.
Senior signals in this story: you framed cost as a product of three managed factors, you refused to trade quality silently (eval gate with a number), your controls are mostly deterministic (loop detector, compaction, budgets) rather than prompt wishes, and you institutionalized the win as an alerted SLO.
Pitfalls
- Optimizing output tokens first. It's the visible number and usually the small one. In agent loops, resent input dwarfs output; measure before cutting.
- "The model will stop when it's done." It will stop when the context makes stopping look right. A failing tool makes trying again look right, forever. Budgets and loop detection are not optional hardening; they're part of the loop's definition.
- Summarizing tool results with another LLM call by default. You can spend more summarizing than you save. Deterministic field selection first; LLM compression only for genuinely unstructured payloads.
- Caching without verifying.
cache_controlin the request proves nothing.cache_read_input_tokens > 0in the response is the only receipt. - Letting client retries restart runs with a fresh budget. A timeout that retries the whole run doubles spend invisibly. Budgets must be keyed to the run_id, not the process.
Continue the series
This is Scenario #2 of AI in Production: War Stories:
- Scenario #1: Our AI Support Bot Invented a Refund Policy — RAG Hallucinations From 18% to 3%
- Next, Scenario #3: p95 was 4.2 seconds and users were abandoning the copilot — the latency incident.
The deep-dive question banks this series pairs with:
- Generative AI Interview Questions for Senior Engineers — 55 Deep Answers
- AI Agents Interview Questions — 50 Deep Answers on Agentic Workflows, Multi-Agent & MCP
- Build Reliable AI Agents: Loop, Planning, Tools, Memory, Guardrails
Further reading
- Anthropic's prompt-caching documentation — the prefix-stability rules behind case #6
- "Building effective agents" (Anthropic engineering) — the argument for simple, budgeted loops over maximal autonomy
- Your own provider's usage API — per-call token accounting is the foundation every control here stands on
Fighting an agent bill of your own? Email me the shape of your loop at randhir.jassal@gmail.com — I read everything.
Get the next issue
A short, curated email with the newest posts and questions.