# Recursion Limit: The Safety Net — LangGraph Agents & Multi-Agent Systems

Source: https://www.geekswithgeeks.com/en/langgraph-agents/f-recursion

> Stop runaway graphs automatically.

## A built-in step budget

LangGraph counts the **super-steps** a run takes and raises **`GraphRecursionError`** when it passes the `recursion_limit` in the run config (the default is a modest number such as 25). It is a safety net, not a design tool: do not rely on it to end normal runs. Set a limit appropriate to your graph, catch the error, log the state, and return a clear failure. Combine it with your own attempt counters, time limits and token budgets, because an agent stuck in a loop costs money on every cycle.

## A buggy infinite loop, stopped, run

I ran this offline with langgraph 1.2.12 and langchain-core 1.6.6 in a Python virtual environment. No API key or model is needed because plain Python functions stand in for the model, so the output is repeatable. The node has an edge back to itself with no end. With `recursion_limit` of 5, LangGraph raises `GraphRecursionError`, which the code catches and reports.

```python
from typing import TypedDict
from langgraph.graph import StateGraph, START
from langgraph.errors import GraphRecursionError

class State(TypedDict):
    n: int

def inc(state): return {"n": state["n"] + 1}

g = StateGraph(State)
g.add_node("inc", inc)
g.add_edge(START, "inc")
g.add_edge("inc", "inc")            # a bug: never ends
app = g.compile()
try:
    app.invoke({"n": 0}, {"recursion_limit": 5})
except GraphRecursionError:
    print("stopped by the recursion limit instead of looping forever")

```

Output:

```
stopped by the recursion limit instead of looping forever
```

## Log the state when the limit hits

The state at the moment of GraphRecursionError usually shows which loop was stuck and why.

**Quiz:** What is the recursion limit for?

- [x] Stopping runaway graphs as a safety net
- [ ] Making the model smarter
- [ ] Compressing state
- [ ] Choosing the language

*Answer:* Stopping runaway graphs as a safety net. It bounds the number of steps in a single run.
