How runaway agent loops burn budget, and how to detect them
30 November 2026 · 8 min read
In November 2025, four LangChain agents looped for 11 days (264 hours) and ran up a $47,000 bill. The post-mortem did not find an exotic bug. It found that nothing limited what each agent could spend, and nothing could stop the next API call once the loop started (write-up).
Agents loop because they are built to retry: a tool fails, the model tries again; a sub-agent returns something unexpected, the planner asks again. Most of the time that is the feature. This post is about telling the feature from the failure, automatically, while it is still cheap.
Three shapes of loop
1. The exact repeat
The agent sends the same request again and again. Typical causes: a tool returns an error the model cannot act on, a framework retries without changing anything, or a planner and a worker hand the same task back and forth with no new information. Each call costs about the same, so spend grows linearly with time, for as long as nobody looks.
2. The growing-context loop
The agent calls a tool, appends the result to its conversation, and calls again. No two requests are identical, because the history grows every turn. This one is more expensive than it looks. If each turn adds k tokens to the context, turn n sends about n·k input tokens, and the total after N turns is about k·N²/2. Twice as many turns costs four times as much.
3. The slow leak
Nothing is stuck. An agent just runs more often, or with more context, than anyone planned: a cron that fires every minute instead of every hour, a retrieval step that now returns fifty documents instead of five. Each run looks normal. The monthly total does not.
Each shape needs a different signal. One check will not catch all three.
Signal 1: request fingerprints for exact repeats
Hash the request body, minus fields that do not change what is asked (like the streaming flag), and count how often the same hash appears for the same agent in a short window. Legitimate agents rarely send a byte-identical request many times in two minutes. A stuck one does little else.
import hashlib, json, time
from collections import defaultdict, deque
class LoopDetected(RuntimeError):
pass
class LoopGuard:
def __init__(self, max_repeats=8, window_sec=120):
self.max_repeats, self.window = max_repeats, window_sec
self.seen = defaultdict(deque) # (agent, fingerprint) -> timestamps
self.tripped = set()
@staticmethod
def fingerprint(body: dict) -> str:
body = {k: v for k, v in body.items() if k not in ("stream", "stream_options")}
return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()[:32]
def check(self, agent: str, body: dict):
if agent in self.tripped:
raise LoopDetected(f"{agent} is tripped; resume it by hand")
now, q = time.time(), self.seen[(agent, self.fingerprint(body))]
while q and q[0] < now - self.window:
q.popleft()
if len(q) >= self.max_repeats:
self.tripped.add(agent)
raise LoopDetected(f"identical request repeated {len(q)}x within {self.window}s")
q.append(now)
guard = LoopGuard()
# before every call: guard.check("research-agent", request_body)
Two details matter. First, the guard stays tripped. If it only rejected the ninth call, the agent would retry, wait out the window and continue. Second, the threshold is per agent: a batch job that legitimately embeds the same string repeatedly should get its own, looser setting.
Signal 2: per-run budgets for growing loops
A growing-context loop changes every request, so fingerprints do not see it. What it cannot hide is cost per task. Give every run an ID, sum spend per ID, and refuse the next call when the run's total plus the estimated cost of the call would cross a limit.
class RunBudget:
def __init__(self, limit_usd):
self.limit, self.spent = limit_usd, defaultdict(float)
def before(self, run_id, estimate_usd):
if self.spent[run_id] + estimate_usd > self.limit:
raise RuntimeError(f"run {run_id} would exceed ${self.limit}")
def after(self, run_id, actual_usd):
self.spent[run_id] += actual_usd
Set the limit from data: a few times the cost of your most expensive normal run. The quadratic growth above works in your favour here. A looping run crosses a sensible per-run limit quickly, long before it would show up on a monthly total. A turn counter (stop after 50 tool calls) is a useful second check, but a cost limit is the one that maps to what you care about.
Signal 3: burn-rate projection for slow leaks
For the slow leak, look at pace rather than totals. Take spend over the last hour, multiply by the hours left in the month, add what has been spent so far, and compare with the monthly budget:
def burn_rate_alert(month_spend, last_hour_spend, monthly_budget, hours_left, factor=1.5):
projected = month_spend + last_hour_spend * hours_left
return last_hour_spend > 0 and projected > monthly_budget * factor
This one should alert, not block. A projection is a guess, and a busy hour is not a bug. But an alert that says "at this pace you will spend 1.5x the budget" on day 3 is much more useful than a threshold email on day 25.
Stop first, then tell someone
The common thread in the $47,000 incident is that information existed and nothing acted on it. A detector that only logs is a dashboard. For loops, the action should be:
- Refuse the call with a clear error the agent framework will surface, not a timeout it will retry.
- Keep the agent blocked until a person resumes it.
- Send the reason, the agent, and a resume link to wherever your team looks: Slack, email, a webhook.
Doing this at a proxy
The snippets above work inside one process. The same limits as in the spending-cap post apply: state is lost on restart, workers do not share it, and any client created elsewhere skips it. AgentFuse implements all three signals at a proxy in front of the OpenAI and Anthropic APIs, per agent key:
curl -s https://<your AgentFuse URL>/api/keys -H 'authorization: Bearer af_org_...' -H 'content-type: application/json' \
-d '{"name":"planner","policy":{
"loop_max_repeats":8, "loop_window_sec":120,
"per_run_budget_usd":2, "monthly_budget_usd":100, "burn_rate_alert_pct":80}}'
Runs are identified by an X-AgentFuse-Run header on each request. The loop check fingerprints the request body (minus the streaming fields) the same way as the guard above. This is what an agent sees when it sends the same request a ninth time within two minutes:
1..8 200 OK
9 402 {"error":{"code":"loop_detected","message":"AgentFuse blocked this request: loop_detected
(identical request repeated 8x within 120s). Resume at https://<your AgentFuse URL>/keys/key_c274532666fcf149"}}
10 402 {"error":{"code":"circuit_open","message":"AgentFuse blocked this request: circuit_open (loop_detected). ..."}}
The tenth call is refused too, with circuit_open: the key is tripped, a tripped event is recorded, and the webhook and email alerts fire if configured. A different request from the same key is also refused until someone clicks Resume in the dashboard or calls POST /api/keys/:id/resume. Burn-rate alerts use the projection above with a 1.5x factor, and a separate alert fires at 80% of the monthly budget.
One limit to be honest about: no detector knows what your agent is supposed to do. A loop that changes its request every turn and stays under the per-run budget will not be caught by any of these signals. Per-run limits that match real task costs are what keep that case small.
Catch the next loop at call nine, not day eleven
The AgentFuse Free plan includes 3 agent keys. Change a base URL and an API key; no SDK changes.
Launching soon About AgentFuse