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.
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:
A tool that keeps failing. The model retries with small variations
because it has no better idea.
Empty or unhelpful results. A search returns nothing, so the model
searches again, differently, forever.
Ambiguous goals. The model cannot tell whether it is done.
Oscillation. Two steps undo each other, such as editing a value and
then "correcting" it back.
Context decay. In a long run, early instructions or earlier attempts
fall out of effective attention and the agent repeats itself.
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.
Limit
What it bounds
What it misses
Max steps
Number of model/tool iterations
Cost per step, slow tools
Token or spend budget
Total cost of the run
A cheap loop that wastes time
Wall-clock timeout
Time the user or worker waits
Fast, expensive loops
Repeated-call detection
Same action over and over
Loops that vary slightly each time
Per-tool call caps
One tool being hammered
Loops spread across tools
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.
Plot the distribution of steps for successful runs per task type.
Set the limit above the high end of that distribution, with headroom.
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:
Identical call detection. Hash the tool name plus normalised arguments.
If the same hash appears two or three times in a run with no state change in
between, stop or inject a correction.
No-progress detection. Track a simple progress signal: new documents
retrieved, a field filled in, a task list item completed. N steps without
movement means stop.
Error streaks. The same tool failing repeatedly should trip a circuit
breaker for that tool rather than let the model keep retrying. This pairs
with the retry rules in
AI agent retries and idempotency.
Oscillation detection. Keep the last few states; if the agent returns to
a state it already visited, that is a cycle.
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:
Stop before the next paid call, not after it.
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.
Return an explicit status such as budget_exceeded, never a partial
answer dressed up as complete.
Escalate where the stakes warrant it. Customer-facing runs should hand
off to a person; see human-in-the-loop approval.
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.
Per-run cancel. Every run has an ID and a cancelled flag the loop checks
before each step. This also lets users stop a run they started.
Per-agent or per-tenant disable. A feature flag that makes new runs fail
fast or fall back to a non-agent path.
Global spend ceiling. A hard daily or monthly cap that pauses new runs
and pages someone. Provider-side spend limits are a useful second layer, but
do not rely on them as your only control; enforce your own as well. For
per-customer caps see
AI usage limits per customer.
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:
Log steps, tokens and cost per run, and look at the top 1% most expensive.
Add a per-agent step limit and a wall-clock timeout based on real
successful runs.
Add identical-call detection, which is a few lines of code.
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
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.
Durable execution lets a long-running AI agent resume after a crash, deploy or timeout instead of starting over. How checkpointing and workflow engines differ, and when you need either.
Single agent vs multi-agent AI systems: when extra agents help, when they only add cost and coordination bugs, and a decision checklist to use before you build.
AI agent memory cost is the budget line most teams discover only after their context window balloons. What naive context injection actually costs, what tiered retrieval saves, and real 2026 pricing to plan against.