All posts

AI agent infinite loops: step budgets, loop detection and kill switches

How to stop an AI agent infinite loop from burning your LLM budget: step and token budgets, repeated-call detection, wall-clock limits and a per-run kill switch.

CodeKrypt 6 min read

An agent that never stops is the most expensive bug in an AI product, because every extra iteration is a paid model call. An AI agent infinite loop rarely looks like a crash. It looks like a run that keeps going: the same search with slightly different wording, the same failing tool call, the same "let me try another approach". Nothing errors, the bill just grows.

This post covers the controls that bound a run: step budgets, token budgets, repeated-call detection, time limits and a kill switch. It is about the domain, not any particular deployment of ours.

Why do AI agents loop forever?

An agent is a loop: call the model, run any tool it asks for, feed the result back, repeat until the model answers instead of requesting a tool. Nothing in that structure guarantees termination. Anthropic's guide to building effective agents says it is "common to include stopping conditions (such as a maximum number of iterations) to maintain control", and warns that autonomy means "higher costs, and the potential for compounding errors."

Common triggers:

None of these is exotic. They are why a loop needs limits written in code, not a line in the prompt asking the model to be careful.

What limits should every agent loop have?

Use several, because each catches a different failure.

LimitWhat it boundsWhat it misses
Max stepsNumber of model/tool iterationsCost per step, slow tools
Token or spend budgetTotal cost of the runA cheap loop that wastes time
Wall-clock timeoutTime the user or worker waitsFast, expensive loops
Repeated-call detectionSame action over and overLoops that vary slightly each time
Per-tool call capsOne tool being hammeredLoops spread across tools
Agent loop with a budget check before every step: within budget the step runs, over budget the run stops and hands offNext stepBudget checkModel + tool callStop + hand offwithin budgetover budgetCheck before the step runs, not after the bill arrives

Frameworks ship a version of the first one. LangGraph, for example, has a recursion limit that caps how many super-steps one run may execute and raises GraphRecursionError when it is exceeded. Its default is in the thousands of steps in current versions, which is a backstop against a true infinite loop, not a cost control. Set your own, much lower, per-agent limit.

How do you pick a step limit?

Do not guess. Log the step count of every run, then look at completed, successful runs only.

  1. Plot the distribution of steps for successful runs per task type.
  2. Set the limit above the high end of that distribution, with headroom.
  3. Review the runs that hit the limit. Some will be legitimate hard tasks (raise the limit for that task type); most will be real loops.

A single global number is usually wrong: a lookup agent might finish in a handful of steps while a research agent legitimately needs many more. Set limits per agent or per task type. If you have no history yet, start low and raise it on evidence, because a too-low limit fails visibly and a too-high one fails on your invoice.

Remember that steps are not equal. Each iteration usually resends the growing conversation, so later steps cost more than early ones. That is why a step limit alone does not bound spend, and why we cover tiered context and agent memory cost separately.

How do you detect a loop before the limit?

Waiting for the maximum wastes money. Cheap detectors catch most loops early:

When a detector fires you have options: return a structured "this call is repeating" message to the model so it can change approach, force a tool-free final answer, or abort. Try the nudge once; if the pattern continues, abort.

What should happen when a limit is hit?

The worst outcome is a silent one. Define the exit path up front:

  1. Stop before the next paid call, not after it.
  2. Persist the run state: steps, tool calls and results, so a person or a later run can pick up from there. Long-running workflows are easier to resume with durable execution.
  3. Return an explicit status such as budget_exceeded, never a partial answer dressed up as complete.
  4. Escalate where the stakes warrant it. Customer-facing runs should hand off to a person; see human-in-the-loop approval.
  5. Alert on limit hits. A rising rate of budget_exceeded is an early signal that a tool, prompt or model change broke something.

What is a kill switch and where does it live?

Limits are automatic. A kill switch is manual, for the case where something is wrong right now and you do not want to wait for a deploy.

Test the kill switch. A control nobody has exercised is a hope, not a control.

What to do next

If you already run an agent in production, do these four things this week:

  1. Log steps, tokens and cost per run, and look at the top 1% most expensive.
  2. Add a per-agent step limit and a wall-clock timeout based on real successful runs.
  3. Add identical-call detection, which is a few lines of code.
  4. Add a per-run cancel flag and a global spend ceiling, then test both.

If you are still designing the agent, build these limits in from the first version; retrofitting them after a surprise invoice is the expensive way. We build agent workflows with these controls as standard engineering practice. Read more on our AI automation page, or see why AI agents fail in production for the wider set of failure modes.

CodeKrypt avatar

CodeKrypt

Drafted by CodeKrypt's AI writing pipeline, built and maintained by our engineers, under fixed rules on sources and claims. How we write

Frequently asked questions

Why do AI agents get stuck in infinite loops?
An agent loop keeps calling the model and tools until the model decides it is done. If a tool keeps returning an error, an empty result or the same data, the model can keep trying variations of the same call and never reach a stopping state. Nothing in the model forces termination; your code has to.
What is a good max-iterations value for an AI agent?
There is no universal number. Measure the step count of your successful runs, then set the limit above the high end of that distribution with some headroom. A limit far above any legitimate run is a cost ceiling, not a safety net.
Is a step limit enough to control agent cost?
No. A step limit does not bound tokens per step, and long contexts make later steps more expensive. Pair it with a token or spend budget and a wall-clock timeout.
What should happen when an agent hits its limit?
Stop cleanly, save the run state, and either hand off to a person or return a defined failure to the caller. Do not silently return a half-finished answer as if it were complete.

Related reading

Chat on WhatsApp