entry
No. 17
date

updated
filed under
debugging, agents
checked against
8 sources

LangGraph GraphRecursionError: Fix the Recursion Limit Error

LangGraph raises GraphRecursionError when a graph runs out of super-steps before it reaches END. The full message in langgraph 1.2.24 is: "Recursion limit of 25 reached without hitting a stop condition. You can increase the limit by setting the recursion_limit config key." followed by a link to the GRAPH_RECURSION_LIMIT troubleshooting page. The number is whatever limit was in force. Most of the time the cause is a loop with no working exit, so raising the limit only makes the failure slower and more expensive. Find the edge that should end the run, fix it, and then set a limit that fits your graph on purpose.

This post explains what the limit counts, what the defaults are in current versions (they are not 25 any more), and four fixes, from a graceful wrap-up inside the graph to call limits on create_agent. Every snippet was run on Python 3.13 with langgraph 1.2.24 and langchain 1.5.2, using fake models, so none of it needs an API key.

What recursion_limit counts

The LangGraph docs define it plainly: "The limit is the number of super-steps allowed before LangGraph raises an error." A super-step is one round of the graph's execution. Every node scheduled for that round runs in it, so three nodes that fan out in parallel cost one step, not three.

Two details matter when you size the limit.

The input step counts. In our runs, the first node of a graph ran at langgraph_step 1, because step 0 is the __start__ task that writes your input into the state. A straight chain of N nodes finished with recursion_limit=N+1 and raised GraphRecursionError with recursion_limit=N. A fan-out of three parallel nodes and a join node, two rounds of work, needed a limit of 3.

Subgraphs get the same limit and count their own steps. We built a parent graph with one node that is a compiled subgraph, and the subgraph loops eight times before it ends. The parent uses only two steps, yet the run failed at recursion_limit=5 and passed at 9. The limit you pass is read again inside every subgraph, so a deep inner loop can trip it even when the outer graph is short.

GraphRecursionError subclasses Python's built-in RecursionError, which is why some generic error handlers report it as a recursion problem. It has nothing to do with Python's call stack.

The defaults have changed

Many tutorials and Stack Overflow answers say the default limit is 25. That number still exists: langchain-core declares DEFAULT_RECURSION_LIMIT = 25. But langgraph no longer uses it. In langgraph 1.2.24, a graph run without a recursion_limit gets 10007, read from the LANGGRAPH_DEFAULT_RECURSION_LIMIT environment variable when it is set.

create_agent in langchain 1.5.2 sets its own value. Its source compiles the agent graph and calls .with_config({"recursion_limit": 9_999}), with a comment pointing to langgraph issue 7313, which discusses replacing the large magic number with a sentinel. You can see it on any agent you build:

agent = create_agent(model, tools=[search_orders])
print(agent.config["recursion_limit"])  # 9999

So if you see "Recursion limit of 25 reached", something in your code or an older dependency set 25 explicitly. And if you never see the error at all, a runaway agent may simply be running for thousands of steps. In the create_agent loop, one model call plus one round of tool calls takes two super-steps, so 9,999 steps is close to 5,000 model calls. With recursion_limit=10, our looping fake model was called five times before the error.

Find the loop before you raise the limit

The troubleshooting page gives two cases: an infinite loop in your graph, or a graph that is legitimately complex and needs a higher limit. Start by assuming the first. These are the usual shapes.

  • An edge with no exit. a goes to b and b goes back to a, with no conditional edge that ever returns END. The docs use exactly this graph to show the error.
  • A router whose exit condition never becomes true. A conditional edge checks state["approved"], but no node ever writes approved, or a node writes it under a different key.
  • A critic that never approves. Writer and reviewer loops are common in LangGraph. If the reviewer's bar is unreachable, the loop runs until the limit. Cap the number of revisions in state.
  • An agent that keeps calling a failing tool. The model sees an error it cannot act on and tries again. Better error text helps here, as covered in agent tool retries and why your agent calls the wrong tool.

Stream the run to see the pattern. With stream_mode="updates", each chunk names the node that just ran, so a loop shows up as the same two or three node names repeating:

from langgraph.errors import GraphRecursionError

seen = []
try:
    for chunk in graph.stream(inputs, {"recursion_limit": 6}, stream_mode="updates"):
        seen.append(list(chunk))
except GraphRecursionError:
    print(seen)  # [['a'], ['b'], ['a'], ['b'], ['a'], ['b']]

If you trace runs, the same sequence appears as repeated spans. Agent observability tracing covers what to record on each step.

Fix 1: Wrap up gracefully with RemainingSteps

When a loop can legitimately run long, don't let it crash. LangGraph's docs describe RemainingSteps as "a Python-only managed value for how many steps remain before the recursion limit." Add it to your state and route to a final node before the budget runs out. You never set it yourself; LangGraph fills it in.

Here the reviewer never approves, but the run still ends with an answer:

import operator
from typing import Annotated, Literal, TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.managed import RemainingSteps


class State(TypedDict):
    draft: str
    revisions: int
    log: Annotated[list, operator.add]
    remaining_steps: RemainingSteps


def write(state: State) -> dict:
    n = state["revisions"] + 1
    return {"draft": f"draft v{n}", "revisions": n,
            "log": [f"write v{n} (remaining {state['remaining_steps']})"]}


def review(state: State) -> dict:
    return {"log": ["review: needs work"]}  # this critic never approves


def wrap_up(state: State) -> dict:
    return {"log": [f"wrap_up: returning {state['draft']}"]}


def route(state: State) -> Literal["write", "wrap_up"]:
    if state["remaining_steps"] <= 2:
        return "wrap_up"
    return "write"


builder = StateGraph(State)
builder.add_node("write", write)
builder.add_node("review", review)
builder.add_node("wrap_up", wrap_up)
builder.add_edge(START, "write")
builder.add_edge("write", "review")
builder.add_conditional_edges("review", route)
builder.add_edge("wrap_up", END)
graph = builder.compile()

out = graph.invoke({"draft": "", "revisions": 0, "log": []}, {"recursion_limit": 8})
print("\n".join(out["log"]))

Output:

write v1 (remaining 7)
review: needs work
write v2 (remaining 5)
review: needs work
write v3 (remaining 3)
review: needs work
wrap_up: returning draft v3

The docs call this the proactive approach: the graph notices the limit coming and finishes on its own path. Catching GraphRecursionError outside the graph is the reactive one, where execution has already stopped. For a revision loop like this, a plain revisions cap in the router is clearer still, and RemainingSteps becomes the backstop.

Fix 2: Set the limit for your graph on purpose

Pass recursion_limit in the config of each call, or bake it into the compiled graph with with_config, the same method create_agent uses:

graph = builder.compile().with_config(recursion_limit=50)
result = graph.invoke(inputs)                          # uses 50
result = graph.invoke(inputs, {"recursion_limit": 8})  # a per-call value wins

For create_agent, a per-call limit replaces the 9,999 default. Size it from what you measured: count the super-steps of a normal run, add room for a few retries, and treat anything beyond that as a bug to catch. The docs also note that a node can read the current step from config["metadata"]["langgraph_step"] if it needs to log or react to it.

Fix 3: Limit model and tool calls in create_agent

For agents, super-steps are an indirect measure. LangChain's built-in middleware counts what you actually pay for. ModelCallLimitMiddleware exists to "limit the number of model calls to prevent infinite loops or excessive costs." Its run_limit counts calls in one invocation, thread_limit counts across a thread (which needs a checkpointer), and the default exit_behavior="end" stops the agent with a message instead of an exception.

from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware, ToolCallLimitMiddleware

agent = create_agent(
    model,
    tools=[search_orders],
    middleware=[
        ToolCallLimitMiddleware(tool_name="search_orders", run_limit=2),
        ModelCallLimitMiddleware(run_limit=5),
    ],
)
result = agent.invoke({"messages": [{"role": "user", "content": "Why was I charged twice?"}]})

With a fake model that asks for search_orders on every turn, the first two calls ran. The next three got a tool message instead, "Tool call limit exceeded. Do not call 'search_orders' again.", which is the default exit_behavior="continue" for the tool limiter. On the fifth model call the run ended with an AI message, "Model call limits exceeded: run limit (5/5)", and no exception. Set exit_behavior="error" on the model limiter to raise ModelCallLimitExceededError instead.

The tool limiter's blocking message gives the model a chance to change course, much like the nudge in the loop guard from debugging agents that never stop. The model limiter is the hard stop behind it.

Fix 4: Resume a run that hit the limit

If the graph has a checkpointer, hitting the limit doesn't lose the work. The state is saved after each super-step, and invoking with None as the input continues from the last checkpoint with a fresh step budget:

from langgraph.checkpoint.memory import InMemorySaver

graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "run-1"}, "recursion_limit": 4}

try:
    graph.invoke(inputs, config)
except GraphRecursionError:
    snapshot = graph.get_state(config)
    print(snapshot.values["revisions"], snapshot.next)  # 2 ('write',)
    graph.invoke(None, config)  # picks up at 'write'

In our run on the endless writer and reviewer loop, the first call stopped after two revisions with write as the next node, and the resumed call carried on to revision 5 before hitting its own limit of 4 steps. That makes the limit a safe checkpoint for long jobs: stop, inspect, then resume if the run is healthy. It does not fix a loop that has no exit. The same resume works after a crash, as long as the checkpointer is persistent; LangGraph durable execution covers what replays and what can run twice.

Checklist

  • Read the number in the error. 25 means something set it explicitly.
  • Stream with stream_mode="updates" and look for repeating node names.
  • Check that every cycle has a conditional edge that can reach END, and that the key it reads is written.
  • Cap revisions or retries in state, and add RemainingSteps routing as a backstop.
  • Size recursion_limit from a normal run, counting the input step and any subgraph loops.
  • On create_agent, add ModelCallLimitMiddleware with a run_limit.
  • Use a checkpointer so a run that hits the limit can be inspected and resumed.
  • Turn every limit hit into an eval case, as in the agent evals starter guide.

FAQ

What is the default recursion limit in LangGraph?

In langgraph 1.2.24 it is 10007 when you pass none, or the value of the LANGGRAPH_DEFAULT_RECURSION_LIMIT environment variable. Agents built with create_agent in langchain 1.5.2 set 9999. The value 25 is what langchain-core declares and what older tutorials quote.

Does recursion_limit count nodes or steps?

Super-steps. Nodes that run in parallel in the same round share one step. The step that writes your input at START counts too, so a chain of N nodes needs a limit of N+1.

How do I set recursion_limit on a LangGraph agent?

Pass it in the config of the call, as in agent.invoke(inputs, {"recursion_limit": 30}), or set it once with graph.with_config(recursion_limit=30). A per-call value overrides the compiled one.

How do I stop a LangGraph agent gracefully instead of raising GraphRecursionError?

Add a RemainingSteps key to the state and route to a final node when it gets low, or on create_agent use ModelCallLimitMiddleware, whose default exit_behavior="end" returns a message instead of raising.

Can I continue a run after GraphRecursionError?

Yes, if the graph was compiled with a checkpointer. Call invoke(None, config) with the same thread_id and it resumes from the last saved step with a new step budget.

Sources

Stuck on a different message? The error index lists every agent error covered here, by tool.

Next in the notebook

  1. No. 2AI Agent Calling the Wrong Tool? 7 Causes and How to Fix Them

    A debugging checklist for tool-calling agents: overlapping tools, vague descriptions, ambiguous parameters, noisy output and bad errors, with a fix for each.

  2. No. 7Agent Infinite Loop: How to Debug Agents That Never Stop

    Why AI agents get stuck in infinite loops, and how to stop them: turn caps, token budgets, repeated-call detection, better tool errors and clear stop rules.

  3. No. 11Agent Observability Tracing: What to Log on Every Step

    Trace an AI agent with OpenTelemetry: one span per run, model call and tool call, which gen_ai attributes to record, and how to keep prompts out of traces.