New Tool Radar

AI Agents & Automation

How to Set a LangGraph Recursion Limit So an Agent Loop Cannot Run Forever

Set a recursion limit on a LangGraph graph invocation so an agent that keeps calling tools stops instead of looping without end.

Schematic diagram with three steps: Count normal steps, Set the limit, then Test a looping prompt.

An agent is a cycle, and a cycle with no limit can run forever when the model keeps calling tools. A recursion limit caps how many steps one invocation may take, so a confused agent stops with an error instead of burning calls without end.

Before you start

You need a working LangGraph StateGraph with a model and tool loop. Count how many steps a normal task takes first, by reading the state history of three ordinary runs.

Pick a limit from your own runs and set it

Take the highest step count from your three ordinary runs and add a small margin, for example a limit of 10 when ordinary tasks take 4 to 6 steps. Pass the limit in the config when you invoke the graph. A limit is per invocation, so a new thread starts with a fresh count.

Test the limit with a prompt that loops

Send a prompt that makes the agent call tools without progress, for example a question the tools cannot answer. Check the run stops at the limit and returns an error instead of running on. Then check an ordinary task still finishes under the limit.

Worked example: Step counts for a fictional support agent

Northwind Support is a fictional help desk. Its graph checks orders with one tool. The table shows step counts for four runs.

Run Steps used Limit of 10 stops it?
Check order 1042 status 4 No
List the last 3 orders 6 No
Find a delivery date 5 No
Ask a question no tool can answer 10, then stopped Yes

Expected result (UNTESTED): the three ordinary runs finish in 4 to 6 steps, and the unanswerable question stops at 10 steps. We checked the LangGraph checkpointers documentation, which describes step-based state and resuming, but we did not run the limit test on this machine.

Limits

A recursion limit counts steps, not cost, and a limit that is too low cuts off legitimate long tasks. It does not stop a single slow tool call. Set the limit from your own measured runs, not from a guess.

Sources

See all