Module 2 · Flow control

Loops, recursion limits and stop conditions

6 min read

Loops are LangGraph's strength — an agent that checks a tool, reads the result, checks another — and also its main risk. A loop without a reliable stop condition consumes tokens indefinitely, ties up resources and ends in an obscure error. This lesson presents the three levels of protection to put in place, then the reliability tools that apply to each node: retries, timeouts and error handlers.

Three levels of stop condition

LevelMechanismWhat it produces when triggered
1. Natural stopThe model answers without requesting a toolThe expected answer
2. Business guardA counter in the state (agent_turns) and a routerA clean exit: escalation, message to the customer
3. Safety netLangGraph's recursion limitA GraphRecursionError exception

Level 1 is normality. Level 2 is the one you design: it turns an abnormal situation into a planned path of the graph. Level 3 is only there to catch bugs: it stops everything abruptly, with no answer for the customer.

The business guard

In Relay, the agent_turns counter is reset on every new message (load_profile), incremented on each pass through agent, and read by the router:

def route_after_agent(state: SupportState) -> Literal["tools", "handoff", "finish"]:
    last = state["messages"][-1]
    if not getattr(last, "tool_calls", None):
        return "finish"
    if state.get("agent_turns", 0) >= config.MAX_AGENT_TURNS:
        return "handoff"
    return "tools"

When the agent goes in circles, the customer gets a clear message ("I'm passing your request to an advisor") and the conversation status becomes escalated, so the team can find it. The threshold is a business setting, in config.py, to calibrate on your real trajectories: look at how many turns successful conversations take, and put the limit well above.

Other business guards are useful depending on the case: a cumulative token budget in the state, a maximum number of revisions in a writer-critic loop, repetition detection (the same tool call with the same arguments twice in a row).

The recursion limit: the safety net

LangGraph counts the steps (super-steps) of each run. Beyond a limit, it raises a GraphRecursionError:

from langgraph.errors import GraphRecursionError

try:
    await graph.ainvoke(inputs, {"configurable": {"thread_id": "t1"}, "recursion_limit": 40})
except GraphRecursionError:
    ...  # bug: the business guard did not work

Beware: in LangGraph 1.x, the default limit is very high (over 10,000 steps). It therefore protects you from nothing until you set it. Set it explicitly in each run's configuration, to a value consistent with your graph's size: for Relay, a normal conversation takes about ten steps, so a limit of 40 to 50 is reasonable.

The limit counts the steps of the whole run, subgraphs included. If a legitimate run exceeds it, it isn't the limit you should raise first: the graph probably needs rethinking.

Retry policies

A node calling an external service can fail for transient reasons: API overload, network drop, provider unavailable. LangGraph can retry a node automatically, with a retry policy:

from langgraph.types import RetryPolicy

builder.add_node(
    "execute",
    execute,
    retry_policy=RetryPolicy(max_attempts=3, initial_interval=0.2, retry_on=data.PaymentGatewayError),
)
ParameterRoleDefault
max_attemptsTotal number of attempts3
initial_intervalWait before the 1st retry (s)0.5
backoff_factorWait multiplier at each attempt2
max_intervalMaximum wait (s)128
jitterAdds randomness to the waitTrue
retry_onExceptions (or function) that trigger a retryConnection errors and HTTP 5xx, and any exception that isn't a common programming error (ValueError, TypeError, KeyError…)

Set retry_on to transient errors only. Retrying a validation error or a bug gives the same failure three times, three times slower. Also note that LLM SDKs already retry transient errors on their calls: a retry policy on a node that only calls the model would multiply attempts.

Crucial point: a retried node runs again from the start. If it has a side effect (a payment, an email), that effect must be idempotent. Relay's execute node uses an idempotency key built from the thread and the order: a retry, or a replay, never refunds twice.

Node timeouts

A service that doesn't answer is worse than one that errors: without a limit, the graph waits forever. LangGraph lets you bound each attempt of a node:

builder.add_node("execute", execute, timeout=15, retry_policy=...)

After 15 seconds, the attempt is cancelled and a NodeTimeoutError is raised; the retry policy then decides whether to retry. For long but active processing, TimeoutPolicy distinguishes an absolute maximum duration (run_timeout) from an idle timeout (idle_timeout) reset by signs of progress.

One important restriction: timeouts only apply to async nodes (async def). A synchronous node cannot be cleanly interrupted mid-execution. One more reason to write your nodes as async as soon as they do I/O.

Error handlers

What to do when all attempts have failed? By default, the exception propagates and the run stops. A node error handler turns it into a planned path of the graph:

from langgraph.errors import NodeError


def execute_failed(state: RefundState, error: NodeError) -> dict:
    return {
        "status": "escalated",
        "messages": [AIMessage(content=(
            "Your refund is approved but our payment provider is unavailable. "
            "An advisor will complete it within 24 hours."
        ))],
        "audit": [f"execute: échec ({type(error.error).__name__}), escalade"],
    }


builder.add_node("execute", execute, retry_policy=..., timeout=15, error_handler=execute_failed)

The handler receives the state and a NodeError object (the node name and the exception). It returns an update — or a Command to route elsewhere. The customer gets an honest answer, the team finds the conversation with status escalated, and the audit log says exactly what happened. The test_payment_retry_then_success and test_payment_down_goes_to_error_handler tests cover both scenarios.

Key takeaways

  • Three stop levels: natural, designed business guard (counter, budget), safety net (recursion_limit).
  • The default recursion limit is very high in LangGraph 1.x: set it yourself.
  • RetryPolicy retries a node on transient errors only; a retried node starts over, so its side effects must be idempotent.
  • timeout= bounds each attempt, for async nodes only.
  • error_handler= turns a node's definitive failure into a planned path of the graph.

Practice

  1. Run Relay with {"recursion_limit": 5} on an agent question: at which step does the error occur?
  2. In a test, call data.fail_next_payments(2) then (3): how many attempts do you see, and when does the error handler take over?
  3. Add a guard that escalates if the agent calls the same tool twice in a row with the same arguments.

Resources