If you build the same LangGraph agent in Python and in JavaScript, a stuck loop behaves very differently in each.
I wrote a two-node graph that never reaches END and ran it with no config on current releases (langgraph 1.2.24 for Python, @langchain/langgraph 1.7.5 for JavaScript):
JavaScript: Recursion limit of 25 reached without hitting a stop condition.
Python: Recursion limit of 10007 reached without hitting a stop condition.
JavaScript still stops a runaway graph after 25 steps. Python now lets it run for 10,007. If every pass through the loop calls a model, that is the difference between a quick, cheap failure and thousands of paid model calls before anything raises.
This post shows the test, explains what a "step" is, and gives three guards you can add today.
The test
Here is the Python version. Node b always routes back to a, so the graph never ends:
from typing import TypedDict
from langgraph.graph import StateGraph, START
from langgraph.errors import GraphRecursionError
class State(TypedDict):
n: int
def step(state: State):
return {"n": state["n"] + 1}
g = StateGraph(State)
g.add_node("a", step)
g.add_node("b", step)
g.add_edge(START, "a")
g.add_edge("a", "b")
g.add_conditional_edges("b", lambda s: "a")
app = g.compile()
try:
app.invoke({"n": 0})
except GraphRecursionError as e:
print(str(e).splitlines()[0])
The JavaScript version is the same graph:
import { StateGraph, START, Annotation, GraphRecursionError } from "@langchain/langgraph";
const State = Annotation.Root({
n: Annotation<number>({ reducer: (_a, b) => b, default: () => 0 }),
});
const step = (s: typeof State.State) => ({ n: s.n + 1 });
const app = new StateGraph(State)
.addNode("a", step)
.addNode("b", step)
.addEdge(START, "a")
.addEdge("a", "b")
.addConditionalEdges("b", () => "a", ["a"])
.compile();
try {
await app.invoke({ n: 0 });
} catch (e) {
if (e instanceof GraphRecursionError) console.log(e.message.split("\n")[0]);
}
In the installed packages, the JavaScript default is a constant DEFAULT_RECURSION_LIMIT = 25. Python reads LANGGRAPH_DEFAULT_RECURSION_LIMIT from the environment and falls back to 10007. If you pass a limit yourself, both runtimes respect it.
What counts as a step
The limit counts supersteps: each round in which LangGraph runs the nodes that are ready. In a classic tool-calling agent, one loop is usually two steps, the model node and then the tool node.
So with the Python default, a model that keeps asking for the same tool can make about 5,000 model calls before the graph raises. Each call usually carries a growing message history, so later calls cost more than earlier ones. The error only arrives at the end, after all of that spend.
The low JavaScript limit has the opposite problem. A legitimate long task, such as a research agent visiting many pages, can hit 25 and fail even though nothing is wrong.
Neither default knows your workload. Pick the limit yourself.
Guard 1: always set recursion_limit
Treat the limit as a budget for the task:
result = app.invoke(inputs, {"recursion_limit": 40})
const result = await app.invoke(inputs, { recursionLimit: 40 });
A reasonable starting point is the highest step count you see on healthy runs, plus some headroom. If healthy runs need 12 steps, a limit of 25 to 40 catches loops early without breaking real work.
Guard 2: end the run cleanly before the limit
When invoke raises GraphRecursionError, you get no return value. Often you would rather stop one step early and return what you have, or hand off to a person.
Python LangGraph has a managed value for this. Add RemainingSteps to your state and route to END when it gets low:
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.managed import RemainingSteps
class State(TypedDict):
n: int
remaining_steps: RemainingSteps
def route(state: State):
if state["remaining_steps"] <= 2:
return END # stop and return partial work
return "a"
g = StateGraph(State)
g.add_node("a", step)
g.add_node("b", step)
g.add_edge(START, "a")
g.add_edge("a", "b")
g.add_conditional_edges("b", route, ["a", END])
app = g.compile()
print(app.invoke({"n": 0}, {"recursion_limit": 12})) # {'n': 10}, no exception
LangGraph fills in remaining_steps for you. You never set it yourself.
Guard 3: watch the path, not just the final error
When a run does hit the limit, the question is which step should have ended the loop. Streaming updates shows the path the graph took:
for chunk in app.stream(inputs, {"recursion_limit": 8}, stream_mode="updates"):
print(list(chunk))
# ['a'], ['b'], ['a'], ['b'], ...
The same node pair repeating is the loop. Then look at the step just before each repeat:
-
A router that never returns
END. The condition checks a field that no node ever sets, or a typo means it never matches. - A tool that fails the same way each time. The model reads the error, calls the tool again with the same arguments, and gets the same error. Catch the error, return a clear message, and count retries in state.
- A model that never says it is done. The prompt asks for a final answer in a format the router does not recognize. Log the last model message and compare it with what the router expects.
- The router reads a different field than the node writes. The node stores its result under one key, the router checks another, so the router keeps seeing the starting value.
A checklist for production graphs
- Set
recursion_limit(recursionLimitin JS) on everyinvokeandstreamcall, sized from healthy runs. - Add a clean exit before the limit (
RemainingStepsin Python) so stuck runs return partial work instead of an exception. - Catch
GraphRecursionErrorat the request boundary so one stuck run does not crash the request. - Record each step of a run with its node name, model call, tool call and token count, so a failed run shows the repeat at a glance.
- Alert on steps per run, not only on errors. A run that uses 300 steps and then succeeds is still a problem worth seeing.
Why I looked into this
I build Uncoil, an open-source tracing tool for AI agents. A run that loops shows up as one long timeline of the same model call and tool call, with the cost adding up step by step. The LangGraph integration page shows the setup. Whatever you use to watch your agents, check which default your runtime ships with, because the two LangGraph runtimes disagree by 10,000 steps.
Top comments (0)