AI Hints
Home›LangGraph Tutorial›Safe Loops and Practice
LangGraph · Lesson 17 of 120

Recursion Limit

A safety net.

⏱ 2 min read▶ Video at 17:32🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

Even with care, a bug can create a loop that never ends. LangGraph has a safety net. The recursion limit caps how many steps a single run may take. When it's reached, the run stops with an error.

Recursion Limit
From the video: Recursion Limit
  • Bugs make endless loops
  • A safety net
  • Cap the steps

Hitting the limit

This loop has a bug. It counts up, but the exit checks for a number it can never reach. We set the recursion limit to ten, in the config. Run it. After ten steps, LangGraph stops the run, and raises a graph recursion error, which we catch.

recursion.pypython
from typing import TypedDict
from langgraph.errors import GraphRecursionError
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    count: int

def count_up(s):
    return {"count": s["count"] + 2}

def route(s):
    return END if s["count"] == 7 else "count_up"   # bug: never equals 7

b = StateGraph(State)
b.add_node(count_up); b.add_edge(START, "count_up"); b.add_conditional_edges("count_up", route)
try:
    b.compile().invoke({"count": 0}, {"recursion_limit": 10})
except GraphRecursionError:
    print("Stopped: recursion limit of 10 reached")
Output
Stopped: recursion limit of 10 reached

About the limit

The default limit is generous, so normal graphs never hit it. Set it lower while you develop, to catch bugs fast. Raise it for long running agents that really need many steps. And always catch the error, so users see a friendly message.

keyvalue
Defaultgenerous
Developset it low
Long agentsraise it
CatchGraphRecursionError

Summary

The recursion limit stops runaway loops after a set number of steps. Set it in the config, and catch the error. Next, practise with an order router.

Key takeaways
  • recursion_limit
  • GraphRecursionError
  • A safety net
Next up: Practice: Order Router — branches