A temporary API failure can stop a graph even when the next request would succeed. In Python LangGraph, a node retry policy gives transient failures another chance while limiting how many times the node runs.
The retry policy belongs to the node registration, so different nodes can use different exception filters and delays. The attempt limit includes the first call, and an error that does not match the filter escapes immediately unless a separate error handler handles it.
Retries restart the whole node function, including any external writes it already performed. Payments, emails, and other side effects need a stable idempotency key honored by the receiving service, or a separate design that prevents duplication. A simulated connection failure lets you test the retry boundary without credentials or real API requests.
Steps to configure node retries in LangGraph:
- Create a file named retry_demo.py in your Python project using your text editor.
The project needs an activated environment with LangGraph installed. The code was tested with Python 3.12 and LangGraph 1.2.20, and needs LangGraph 1.1.3 or later because 1.1.2 raises an AttributeError at runtime.execution_info.
- Enter the imports and graph state definition in retry_demo.py.
from typing import TypedDict from langgraph.graph import END, START, StateGraph from langgraph.runtime import Runtime from langgraph.types import RetryPolicy class State(TypedDict): failures_before_success: int result: str
The input determines how many attempts fail before the node can return a result.
- Append a node that raises a simulated connection error until its configured failure count is reached.
def call_api(state: State, runtime: Runtime) -> dict[str, str]: attempt = runtime.execution_info.node_attempt print(f"attempt {attempt}") if attempt <= state["failures_before_success"]: raise ConnectionError("simulated failure") return {"result": "response received"}
LangGraph supplies the attempt number, starting at 1 for each node execution. The raised exception reaches the retry policy; returning an error string instead would count as a successful node return.
- Append a retry policy that allows three total attempts for ConnectionError.
retry_policy = RetryPolicy( max_attempts=3, retry_on=ConnectionError, initial_interval=0.1, jitter=False, )
The first retry waits 0.1 seconds, shorter than the default 0.5 seconds to keep the demonstration quick, and the wait doubles by default, so the second retry waits 0.2 seconds. Disabling jitter makes the demonstration predictable; random jitter is enabled by default and helps spread retries across clients. An explicit exception filter leaves unrelated failures outside this policy.
- Register call_api with the retry policy before compiling the graph.
builder = StateGraph(State) builder.add_node( "call_api", call_api, retry_policy=retry_policy, ) builder.add_edge(START, "call_api") builder.add_edge("call_api", END) graph = builder.compile()
In an existing graph, add the retry policy to that node's registration. Other nodes keep their own retry behavior.
When the node makes a real API call, retry_on must name the exception that client raises. The built-in ConnectionError matches only the simulated failure here, because requests and httpx raise their own connection errors, so this policy would run such a node once and fail with no retry. An HTTP status error such as 503, raised by raise_for_status(), needs its own entry, which also retries 4xx responses such as 404. These filters replace the retry_on line for each client.
# httpx, connection failures retry_on=httpx.TransportError, # httpx, connection failures and HTTP status errors retry_on=(httpx.TransportError, httpx.HTTPStatusError), # requests, connection failures retry_on=requests.exceptions.ConnectionError,
- Append two invocations to exercise recovery and exhausted retries.
for failures in (2, 3): print(f"failures_before_success={failures}") try: result = graph.invoke( {"failures_before_success": failures, "result": ""} ) print(f"result: {result['result']}") except ConnectionError as exc: print(f"stopped: {type(exc).__name__}") print()
The first invocation can succeed on attempt 3. The second would need attempt 4, which exceeds the policy limit. The outer exception handler displays the exhausted error without concealing it inside the node.
- Save retry_demo.py.
- Run retry_demo.py to confirm recovery on attempt 3 and termination at the same limit for a persistent failure.
$ python retry_demo.py failures_before_success=2 attempt 1 attempt 2 attempt 3 result: response received failures_before_success=3 attempt 1 attempt 2 attempt 3 stopped: ConnectionError
The result: line is the value in the state returned by the recovered invocation. The second invocation raises the last connection error after three attempts and returns no completed state. An attempt 4 or a missing result: line means the retry behavior differs from the configured policy.