AI in Production: War Stories, Scenario #2. One real production incident: the alert, the triage (dead ends included), the root cause, the fix with runnable code, the measured result — and how to tell it in a senior interview. Scenario #1 was the hallucination incident. This one is about money.
Full original (canonical) on PrepStack: https://prepstack.co.in/blog/ai-production-scenario-2-agent-cost-explosion
The incident
Our agentic analytics feature plans an investigation, calls governed analytics APIs through an 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 pilot cohort ran ~400 agent runs a day. Average cost per run: $0.90. That's $360/day — a ~$11,000/month run-rate for a feature we planned to roll out to 20x the pilot's users. Dead unit economics: it would cost more to serve than the plan tier it shipped in.
Nobody had done anything wrong. "Use the strong model, it's smarter." "Let the agent keep working until it's done." "Pass the full tool output back so it has context." Every decision was locally reasonable. Together they compounded into a money fire. This is the most common agent incident there is.
Where the money leaked — 5 cost multipliers, all live at once
- [C1] Premium model, every step. Premium prices applied to routing, glue, and summary steps a cheap model handles fine.
- [C2] Unbounded loop. The agent decides when it's done, no budget pressure. Worst run: 41 iterations.
- [C3] Context snowball. Full history resent every iteration → input tokens grow roughly quadratically.
- [C4] Raw tool output. 10-50 KB of JSON per result, re-billed on every later iteration via [C3].
- [C5] Failure loops. A tool erroring at iteration 3 gets retried by the model at 4, 5, 6 — each retry re-bills the whole snowball.
Triage — including the dead ends
- "The provider is expensive — switch." Dead end. Price-per-token was ~20% of the story. Same architecture on a cheaper provider still cost ~$0.55/run. The architecture, not the rate card, was the bill.
-
"Cap max_tokens hard." Dead end + a user-facing bug. Someone set
max_tokens=800globally. Findings truncated mid-sentence, runs retried, cost went up. Output tokens were <8% of spend. - Token telemetry — first real signal. Iteration 1 cost 4k input tokens; iteration 8 cost 38k. Re-billed history dominated everything.
- Iteration histogram — second real signal. p50 = 5, p95 = 18. One run hit 41 iterations overnight: $7+ for one unanswered question hammering a failing tool.
Root cause: agent cost is price x tokens x iterations, and we were managing none of the three. The strong model multiplied price, the snowballing context multiplied tokens, the unbounded loop multiplied iterations. Multiplication is why agent bills surprise teams used to linear per-request LLM costs.
The fix: manage all three multipliers
# Multiplier 1: PRICE - model-per-role tiering (escalation, never default)
MODEL_ROUTER = "claude-haiku-5-5" # classify complexity
MODEL_WORKER = "claude-sonnet-5-5" # the default workhorse
MODEL_ESCALATION = "claude-opus-5-5" # earned by 'complex' runs only
# Multiplier 3: ITERATIONS - explicit budgets
MAX_ITERATIONS = 10
MAX_COST_USD = 0.25
WRAP_UP_AT = 0.8 # at 80% of any budget, tell the agent to conclude
# The meter: cost from ACTUAL usage fields - finance's number must be
# computable from our own logs, not reverse-engineered from the invoice.
class RunMeter:
def add(self, model, usage):
inp, out = PRICES[model]
cached = getattr(usage, "cache_read_input_tokens", 0) or 0
self.cost_usd += (usage.input_tokens * inp + cached * inp * 0.1
+ usage.output_tokens * out) / 1_000_000
def over(self): return self.iterations >= MAX_ITERATIONS or self.cost_usd >= MAX_COST_USD
def near(self): return self.cost_usd >= MAX_COST_USD * WRAP_UP_AT
# Multiplier 2: TOKENS - compact tool results, keep a reference escape hatch
def compact_tool_result(raw, run_id, tool_use_id):
data = json.loads(raw); rows = data.get("rows", [])
return json.dumps({
"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; model can ask to expand
})
# [C5] killer: same tool + same args a third time is a retry loop, not progress
def detect_loop(meter, name, args):
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
# The loop, with caching on a byte-stable prefix and graceful budget exits
while True:
meter.iterations += 1
response = client.messages.create(
model=model, max_tokens=4096,
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": return text, meter
if meter.over():
return ("I hit the investigation budget. Partial findings above; "
"a human analyst has been notified to complete this."), meter
# ... execute tools through detect_loop() + compact_tool_result() ...
if meter.near() and not wrap_up_sent:
messages.append({"role": "system", "content": WRAP_UP}) # "conclude with what you have"
What matters more than the code:
- Budgets end runs gracefully. At 80% the agent concludes with caveats; hard-stop at 100% is the fallback, with human escalation owning the rest. A wrapped-up partial beats a dead cursor.
- The loop detector is deterministic. Same tool + same args, third time: blocked. The 41-iteration run would have died at iteration 5, having spent cents.
- Compaction keeps a reference, not just a summary. The model can fetch the full payload — it asked in <2% of runs. The other 98% were paying the full-payload tax for nothing.
-
The meter is first-class. Cost from
usageper call, logged per run, on a dashboard with a p95 cost/run alert. Regressions page us before finance does.
The 6 ways agent bills blow up — and the control for each
| # | Case | Control |
|---|---|---|
| 1 | Runaway loop on a failing tool | Loop detector + iteration budget |
| 2 | Context snowball | Tool-result compaction + caching |
| 3 | Over-modeled simple steps | Router tiering |
| 4 | Verbose tool results | Compaction + reference escape hatch |
| 5 | Retry amplification | Idempotent runs + budget carried across retries |
| 6 | Cache-miss bleed | Byte-stable prefix; volatile data after the breakpoint |
Case 6 confession: our first caching attempt saved nothing. The system prompt had a freshly formatted timestamp — one changing byte at the top of the prefix, so every request was a cache miss. If cache_read_input_tokens is ~0, hunt for the volatile byte: almost always a timestamp, a UUID, or unsorted JSON.
The quality guardrail
Cost optimization that quietly degrades answers is just a slower incident. Everything ran through an eval gate (investigation accuracy + completeness, hard floor 0.90) before shipping. Tiering moved the score 0.93 → 0.92 (inside noise); compaction, no measurable change; budgets end 3% of runs with a budgeted partial answer, counted as successes-with-caveats that each file a gap ticket.
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) | 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
STAR, 60 seconds: "Our agentic feature cost $0.90/run in pilot — dead unit economics at rollout scale. 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 compaction and prompt caching; explicit run budgets with a graceful wrap-up plus a deterministic repeated-call detector. Cost fell 87% to $0.12 with the eval score inside noise, p95 iterations 18→6, and cost-per-run became a monitored SLO with alerting."
Follow-ups you'll get: why not the cheapest model everywhere? (eval gate failed; complex causal runs dropped below 0.90 — tiering is an empirical boundary). How do you know cost exactly? (usage fields priced through a config table, per run_id — not invoice / run count). Budget UX? (wrap-up at 80%, hard stop + escalation at 100%, 3% end budgeted, labeled honestly). What stops regression? (evals with cost assertions in CI + production p95 alert). Remaining waste? (cross-run re-investigation; cross-run memory is the next lever, with its own staleness risks).
Originally published on PrepStack.
Top comments (1)
The context snowball is the multiplier that prompt caching hits most directly. On Anthropic's API cache reads are billed at roughly 10 percent of the base input price, but a cache hit needs the prefix (tools, system prompt, earlier turns) to be exactly identical. So append new tool results at the end rather than rewriting or reordering earlier messages, or every iteration pays full price again. Trimming or clearing old tool results is still worth doing, since cached tokens still occupy the context window.