Retry policies, backoff and timeouts
Overview
A production agent operates in an unreliable environment. Language model providers become temporarily unavailable, databases experience connection failures, external APIs enforce rate limits, and network requests occasionally stop responding.
A workflow that succeeds only when every dependency behaves perfectly is not production-ready.
Consider an e-commerce support agent that retrieves customer information, checks inventory, generates recommendations, and creates a support ticket. If the inventory API temporarily returns HTTP 503, restarting the entire workflow wastes computation and potentially repeats completed operations. Retrying only the failed operation is considerably more efficient.
Fault tolerance is the ability of a system to withstand failures while preserving correctness and, whenever possible, completing its intended work.
LangGraph provides three complementary mechanisms:
- Retry policies: Repeat operations that encounter recoverable failures.
- Timeout policies: Prevent individual operations from waiting indefinitely.
- Error handlers: Perform recovery when an operation cannot succeed within its execution budget.
This lesson concentrates on the first two mechanisms and the exception-handling principles that connect them.
In the previous lesson, you learned how the Functional API organizes execution using @entrypoint and @task. The same principle of isolating work into independently managed execution units applies here.
Environment setup
Install LangGraph and HTTPX:
pip install -U "langgraph>=1.2,<2.0" "httpx>=0.28,<1.0"Use Python 3.11 or newer for the examples. LangGraph 1.2 introduces the node timeout and graph-wide policy APIs used throughout this lesson.
The examples simulate failures locally, without API keys or paid model calls. They are written against the documented late-2026 APIs, including LangGraph 1.2.25; they have not been execution-tested in this environment.
Retry policies
Understanding retries
A retry is another attempt to execute an operation after an unsuccessful execution.
Not every failure indicates that the operation is fundamentally impossible. An inventory service might be temporarily overloaded and become available again several hundred milliseconds later.
LangGraph represents retry configuration through RetryPolicy, imported from langgraph.types.
A policy attaches to a node through StateGraph.add_node(). Once configured, the graph runtime manages repeated attempts rather than requiring developers to implement manual retry loops inside every node.
The following diagram illustrates the lifecycle of a node with retry and timeout protection.
An unsuccessful attempt includes an exception raised by the node or a timeout detected by the runtime. A successful attempt produces updates that proceed through the normal graph execution process.
Retries repeat a node execution, not necessarily the entire graph.
RetryPolicy parameters
The policy exposes six important configuration parameters.
| Parameter | Default | Purpose |
|---|---|---|
max_attempts |
3 |
Maximum total executions |
initial_interval |
0.5 |
Initial retry delay in seconds |
backoff_factor |
2.0 |
Delay growth multiplier |
max_interval |
128.0 |
Cap on the base retry interval |
jitter |
True |
Randomizes retry timing |
retry_on |
Built-in predicate | Determines eligible exceptions |
These defaults apply when a RetryPolicy is configured. Merely registering a node does not automatically enable this retry policy.
With max_attempts=3, the runtime permits one original execution and up to two retries.
Example: Recovering from a temporary API failure
The following workflow simulates an inventory service that fails twice before recovering.
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.types import RetryPolicy
class State(TypedDict, total=False):
product_id: str
quantity: int
attempts: int
class ServiceUnavailable(Exception):
pass
def fetch_inventory(state: State, runtime: Runtime) -> dict:
attempt = runtime.execution_info.node_attempt
print(f"Attempt {attempt}")
if attempt < 3:
raise ServiceUnavailable("Inventory API unavailable")
return {
"quantity": 25,
"attempts": attempt,
}
builder = StateGraph(State)
builder.add_node(
"fetch_inventory",
fetch_inventory,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.2,
backoff_factor=2.0,
jitter=False,
retry_on=ServiceUnavailable,
),
)
builder.add_edge(START, "fetch_inventory")
builder.add_edge("fetch_inventory", END)
graph = builder.compile()
print(graph.invoke({"product_id": "SKU-101"}))Expected application output:
Attempt 1
Attempt 2
Attempt 3
{'product_id': 'SKU-101', 'quantity': 25, 'attempts': 3}The first execution raises ServiceUnavailable. Because the exception matches retry_on, LangGraph schedules another attempt after the configured delay.
The third execution succeeds, allowing the workflow to finish normally.
Inspecting retry attempts
The runtime exposes execution metadata through runtime.execution_info.
Useful attributes include:
node_attempt: Current execution attempt, starting at one.node_first_attempt_time: Timestamp associated with the initial attempt.task_id: Identifier for the current execution task.thread_id: Persistence thread identifier, when applicable.
Attempt metadata is particularly useful for logging, testing and observing dependency failures.
Do not implement attempt counting by incrementing a field in graph state immediately before raising an exception. Failed node updates are not committed through the normal successful execution path.
Also, an attempt number is not a durable business identifier. It can restart when work is scheduled again in another execution context.
Exponential backoff
Immediately repeating failed requests can make an unhealthy service even less available.
Suppose 1,000 agent executions simultaneously encounter a service outage. If each immediately retries several times, the resulting traffic surge may overwhelm the recovering dependency.
Exponential backoff gradually increases the delay between successive retries.
The base delay after failure number n is calculated as:
delay(n) = min(
max_interval,
initial_interval * backoff_factor ** (n - 1)
)Consider an initial interval of one second, a multiplier of two, and a maximum interval of eight seconds.
| Failed attempt | Next attempt | Base waiting time |
|---|---|---|
| 1 | 2 | 1 second |
| 2 | 3 | 2 seconds |
| 3 | 4 | 4 seconds |
| 4 | 5 | 8 seconds |
| 5 | 6 | 8 seconds |
| 6 | 7 | 8 seconds |
With seven permitted attempts, the cumulative base waiting time is 31 seconds if all six retries are required.
Actual execution time also includes the duration of each attempt, scheduling overhead, and any jitter.
Comparing retry strategies
| Strategy | Behavior | Appropriate use |
|---|---|---|
| Immediate retry | Repeats without meaningful delay | Rare, inexpensive temporary failures |
| Fixed delay | Waits the same duration each time | Predictable recovery intervals |
| Exponential backoff | Progressively increases delays | Remote services and temporary overload |
| Backoff with jitter | Adds randomized timing | Concurrent production workloads |
| No retry | Propagates the first failure | Permanent errors or unsafe operations |
Why jitter matters
Backoff alone does not guarantee that concurrent clients retry at different times.
If hundreds of agents fail simultaneously and all use identical retry intervals, their next attempts may still arrive simultaneously. This creates a synchronized retry storm, sometimes called the thundering herd problem.
Jitter introduces randomness into retry timing.
LangGraph enables jitter by default. In the current retry implementation, randomized delay is added after calculating the capped base interval, so max_interval should not be interpreted as an exact upper bound on observed waiting time.
Disable jitter in demonstrations and deterministic tests. Keep it enabled for typical production workloads.
Tip: Choose retry intervals according to dependency recovery characteristics and the application’s latency budget, rather than applying identical values to every service.
Which errors are retried?
The central question is not whether an operation failed, but whether repeating it is likely to help.
Transient versus permanent failures
A transient failure may disappear without changing the request. A permanent failure generally requires corrected input, credentials, permissions, or implementation logic.
| Failure | Typical retry decision |
|---|---|
| Temporary service outage | Retry |
| Connection interruption | Retry if repetition is safe |
| HTTP 502, 503 or 504 | Usually retry |
| Temporary HTTP 429 rate limit | Retry with appropriate pacing |
| Invalid input or HTTP 400 | Do not retry unchanged |
| HTTP 401 or 403 | Do not retry blindly |
| Programming error | Do not retry |
| Ambiguous payment timeout | Reconcile or use idempotency protection |
These are engineering decisions, not universal rules. For example, HTTP 429 caused by temporary throttling differs from a permanently exhausted account quota.
Default exception selection
LangGraph’s built-in retry predicate excludes many common programming exceptions, including ValueError, TypeError, LookupError, NameError, RuntimeError, and most OSError subclasses.
Built-in ConnectionError is explicitly eligible. HTTP status exceptions from supported HTTP libraries are generally retried for server-side 5xx responses, but not ordinary 4xx responses.
NodeTimeoutError is also eligible by default. Python’s built-in TimeoutError is a different exception and should not be assumed to receive identical treatment.
A custom retry_on replaces the default selection logic. It accepts an exception class, a sequence of exception classes, or a callable returning a Boolean.
Example: Selective HTTP retries
This example uses httpx.MockTransport to simulate HTTP responses and implements an application-specific retry predicate.
import httpx
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.types import RetryPolicy
class State(TypedDict, total=False):
url: str
status_codes: list[int]
data: dict
def should_retry(error: Exception) -> bool:
if isinstance(error, httpx.HTTPStatusError):
status = error.response.status_code
return status in {408, 429, 500, 502, 503, 504}
return isinstance(
error,
(httpx.TimeoutException, httpx.NetworkError),
)
def call_api(state: State, runtime: Runtime) -> dict:
attempt = runtime.execution_info.node_attempt
statuses = state["status_codes"]
status = statuses[min(attempt - 1, len(statuses) - 1)]
print(f"Attempt {attempt}: HTTP {status}")
def mock_response(request: httpx.Request) -> httpx.Response:
return httpx.Response(
status,
json={"quantity": 42},
)
transport = httpx.MockTransport(mock_response)
with httpx.Client(transport=transport, timeout=5.0) as client:
response = client.get(state["url"])
response.raise_for_status()
return {"data": response.json()}
builder = StateGraph(State)
builder.add_node(
"call_api",
call_api,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
jitter=False,
retry_on=should_retry,
),
)
builder.add_edge(START, "call_api")
builder.add_edge("call_api", END)
graph = builder.compile()
for statuses in ([503, 429, 200], [400]):
try:
result = graph.invoke(
{
"url": "https://inventory.example.com/items/101",
"status_codes": statuses,
}
)
print(result["data"])
except httpx.HTTPStatusError as error:
print(f"Request failed: HTTP {error.response.status_code}")Expected output:
Attempt 1: HTTP 503
Attempt 2: HTTP 429
Attempt 3: HTTP 200
{'quantity': 42}
Attempt 1: HTTP 400
Request failed: HTTP 400The distinction is explicit: temporary infrastructure failures trigger retries, while invalid requests stop immediately.
Calling response.raise_for_status() is essential. An HTTP error returned as ordinary data does not automatically trigger an exception-based retry.
For real rate-limited services, respect provider-specific Retry-After instructions. RetryPolicy does not automatically derive a dynamic retry delay from that response header.
Defaults for every node
Large workflows may contain dozens of nodes. Repeating identical retry configuration everywhere introduces duplication and inconsistent behavior.
LangGraph supports shared configuration through StateGraph.set_node_defaults().
Defaults are applied during compilation. Individual node policies override the corresponding graph-wide settings.
Example: Shared defaults with a node override
This workflow gives ordinary operations three attempts but disables retries for a notification operation whose repetition may be unsafe.
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.types import RetryPolicy
class State(TypedDict, total=False):
customer_id: str
customer: str
notification_sent: bool
def fetch_customer(state: State, runtime: Runtime) -> dict:
attempt = runtime.execution_info.node_attempt
print(f"Customer lookup attempt {attempt}")
if attempt == 1:
raise ConnectionError("Temporary connection failure")
return {"customer": "Alex"}
def send_notification(state: State) -> dict:
print(f"Simulated notification sent to {state['customer']}")
return {"notification_sent": True}
builder = StateGraph(State)
builder.set_node_defaults(
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
jitter=False,
retry_on=ConnectionError,
)
)
builder.add_node("fetch_customer", fetch_customer)
builder.add_node(
"send_notification",
send_notification,
retry_policy=RetryPolicy(max_attempts=1),
)
builder.add_edge(START, "fetch_customer")
builder.add_edge("fetch_customer", "send_notification")
builder.add_edge("send_notification", END)
graph = builder.compile()
print(graph.invoke({"customer_id": "C-101"}))Expected output:
Customer lookup attempt 1
Customer lookup attempt 2
Simulated notification sent to Alex
{'customer_id': 'C-101', 'customer': 'Alex', 'notification_sent': True}The customer lookup inherits the default policy. The notification node explicitly permits only one attempt.
Graph defaults do not automatically propagate into independently defined subgraphs. Configure those graphs according to their own dependencies.
Global defaults are useful, but applying a broad retry policy to every operation without reviewing its side effects is dangerous.
Exception handling
Exceptions must reach the runtime
LangGraph can retry a failure only when the relevant exception escapes the node.
A node that catches an exception and returns an ordinary error dictionary has technically completed successfully from the runtime’s perspective.
The following example translates a low-level dependency exception into an application-specific exception while preserving its original cause.
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.types import RetryPolicy
class State(TypedDict, total=False):
order_id: str
status: str
class OrderServiceUnavailable(Exception):
pass
def query_order_service(order_id: str, attempt: int) -> str:
if attempt == 1:
raise ConnectionError("Connection interrupted")
return "shipped"
def fetch_order(state: State, runtime: Runtime) -> dict:
try:
status = query_order_service(
state["order_id"],
runtime.execution_info.node_attempt,
)
return {"status": status}
except ConnectionError as error:
raise OrderServiceUnavailable(
"Could not retrieve order"
) from error
builder = StateGraph(State)
builder.add_node(
"fetch_order",
fetch_order,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
jitter=False,
retry_on=OrderServiceUnavailable,
),
)
builder.add_edge(START, "fetch_order")
builder.add_edge("fetch_order", END)
graph = builder.compile()
print(graph.invoke({"order_id": "ORD-101"}))Expected output:
{'order_id': 'ORD-101', 'status': 'shipped'}Exception chaining preserves the original ConnectionError for debugging while exposing a meaningful domain-level exception to the workflow.
Use finally blocks or context managers for resource cleanup. Avoid indiscriminately catching every exception, especially control-flow exceptions associated with interrupts and cancellation.
When no retry is permitted, or the attempt budget is exhausted, the failure propagates unless a node-level error handler is configured.
A caller can catch that terminal exception and report the failed execution. Workflow-level recovery through error_handler belongs to the next lesson.
Timeout management
Retries address unsuccessful attempts. Timeouts address attempts that take too long to complete.
Without timeouts, a stalled dependency may consume execution capacity indefinitely.
LangGraph supports per-node execution limits through timeout, which accepts seconds, a timedelta, or a TimeoutPolicy.
Node timeouts require asynchronous nodes.
Run timeout versus idle timeout
| Timeout | Measures | Suitable for |
|---|---|---|
| HTTP client timeout | Network operation deadlines | Individual HTTP requests |
| Node run timeout | Total duration of one attempt | Bounded node execution |
| Node idle timeout | Time without observable progress | Streaming and long-running operations |
| Workflow deadline | Overall invocation duration | End-to-end latency requirements |
A run timeout does not reset when progress occurs. An idle timeout can reset when qualifying progress signals occur.
With automatic refresh, recognized signals include streaming activity, supported callback events, and explicit heartbeats. Set refresh_on="heartbeat" when only application-controlled calls to runtime.heartbeat() should refresh the idle timer.
A numeric timeout such as timeout=60 establishes a 60-second run limit for an individual attempt.
Example: Recovering from a timed-out node
The first attempt in this example takes longer than its configured deadline. The second succeeds quickly.
import asyncio
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.types import RetryPolicy, TimeoutPolicy
from langgraph.errors import NodeTimeoutError
class State(TypedDict, total=False):
query: str
result: str
attempts: int
async def search_service(state: State, runtime: Runtime) -> dict:
attempt = runtime.execution_info.node_attempt
print(f"Search attempt {attempt}")
if attempt == 1:
await asyncio.sleep(2)
else:
await asyncio.sleep(0.1)
return {
"result": f"Search completed for {state['query']}",
"attempts": attempt,
}
builder = StateGraph(State)
builder.add_node(
"search",
search_service,
timeout=TimeoutPolicy(
run_timeout=0.5,
idle_timeout=0.3,
),
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
jitter=False,
retry_on=NodeTimeoutError,
),
)
builder.add_edge(START, "search")
builder.add_edge("search", END)
graph = builder.compile()
async def main():
try:
result = await graph.ainvoke({"query": "LangGraph"})
print(result)
except NodeTimeoutError as error:
print(f"Timed-out node: {error.node}")
print(f"Timeout kind: {error.kind}")
print(f"Elapsed seconds: {error.elapsed}")
if __name__ == "__main__":
asyncio.run(main())Expected application output:
Search attempt 1
Search attempt 2
{'query': 'LangGraph', 'result': 'Search completed for LangGraph', 'attempts': 2}The first attempt exceeds its idle timeout. LangGraph cancels that attempt, discards its uncommitted graph writes, and evaluates the resulting NodeTimeoutError against the retry policy.
The second attempt receives a fresh timeout budget and succeeds.
Managing progress and cancellation
For a long-running asynchronous node that processes multiple batches, calling runtime.heartbeat() after each completed batch can indicate meaningful progress.
Combine idle and run limits to prevent a continuously reporting operation from running forever.
Timeout enforcement depends on cooperative asynchronous cancellation. Using time.sleep() or blocking CPU-intensive work inside an asynchronous node prevents the event loop from responding promptly.
Use asynchronous clients for network operations. Where necessary, isolate blocking I/O with asyncio.to_thread(), recognizing that cancellation of the awaiting coroutine cannot forcibly terminate the underlying worker thread.
Note: A node timeout does not guarantee that a remote server stopped processing the request. Cancellation of local execution and cancellation of remote business operations are separate concerns.
Calculating the total execution budget
Consider a node configured with:
- Three total attempts.
- A five-second run timeout.
- An initial retry interval of one second.
- A backoff factor of two.
- Jitter disabled.
Its nominal execution budget is:
Attempt time: 3 × 5 = 15 seconds
Retry delays: 1 + 2 = 3 seconds
Total: 18 secondsThis excludes surrounding graph work, scheduling overhead and delayed cancellation.
A per-node timeout is not a complete workflow deadline. Applications with strict end-to-end requirements should additionally bound the overall asynchronous invocation, for example using Python’s asyncio.timeout().
Retries and side effects
A retry re-executes node logic. This becomes dangerous when the node modifies external systems.
Imagine a payment service successfully charging a customer, but the response disappears because of a network failure. Retrying the request may charge the customer again.
Other vulnerable operations include sending emails, creating tickets, inserting database records and provisioning cloud resources.
Idempotent operations
An operation is idempotent when repeating the same intended request does not create additional unintended effects.
For external write operations, a stable idempotency key identifies the business action across attempts.
The following diagram illustrates a successful external operation whose acknowledgement is lost.
The remote service must enforce deduplication. Merely including an identifier in a request does not make the operation idempotent.
Example: Preventing duplicate ticket creation
This example simulates a ticket service that creates a ticket successfully but loses its first response.
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import RetryPolicy
class State(TypedDict, total=False):
request_id: str
customer_id: str
ticket_id: str
tickets: dict[str, str] = {}
def external_ticket_api(key: str) -> str:
if key in tickets:
print("Existing ticket returned")
return tickets[key]
ticket_id = f"TICKET-{len(tickets) + 1}"
tickets[key] = ticket_id
print(f"Created {ticket_id}")
raise ConnectionError("Response lost after creation")
def create_ticket(state: State) -> dict:
key = (
f"create-ticket:"
f"{state['customer_id']}:"
f"{state['request_id']}"
)
ticket_id = external_ticket_api(key)
return {"ticket_id": ticket_id}
builder = StateGraph(State)
builder.add_node(
"create_ticket",
create_ticket,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
jitter=False,
retry_on=ConnectionError,
),
)
builder.add_edge(START, "create_ticket")
builder.add_edge("create_ticket", END)
graph = builder.compile()
result = graph.invoke(
{
"request_id": "REQ-101",
"customer_id": "C-101",
}
)
print(result)
print("Tickets created:", len(tickets))
assert len(tickets) == 1Expected output:
Created TICKET-1
Existing ticket returned
{'request_id': 'REQ-101', 'customer_id': 'C-101', 'ticket_id': 'TICKET-1'}
Tickets created: 1The same key is generated on both attempts. Consequently, the second request retrieves the previously created ticket instead of creating another one.
The dictionary is only a simulation. Production deduplication requires durable storage, atomic uniqueness enforcement, appropriate request scoping, and protection against conflicting payloads using the same key.
LangGraph retries and checkpoints alone cannot guarantee exactly-once effects in independent external systems.
Production engineering practices
Keep retry boundaries small
Separate unreliable network operations from expensive computation and irreversible business actions.
If one node retrieves customer data, generates an LLM response and sends an email, a failure during email delivery may repeat all three operations.
Smaller nodes create more precise retry boundaries.
Avoid retry amplification
LLM providers, HTTP clients, database drivers and LangGraph may each implement retries.
If an SDK performs three total attempts and LangGraph executes its containing node three times, one logical operation may generate nine underlying requests.
Choose a primary retry layer and explicitly account for retry behavior in every other layer.
Distinguish execution budgets
max_attempts limits retries of a node execution, while recursion_limit limits graph execution steps. Neither replaces network deadlines or an end-to-end workflow deadline.
A workflow containing cycles can revisit a node and receive another retry budget.
Observe and test failures
Record node names, attempt numbers, exception classifications, elapsed durations, timeout categories and terminal outcomes. Avoid logging credentials or sensitive request payloads.
Useful operational metrics include retry frequency, retry recovery rate, timeout frequency, exhausted retry budgets and dependency latency.
Test immediate success, temporary failure, permanent failure, exhausted attempts, timeouts and ambiguous external acknowledgements. A successful final response is insufficient evidence of correctness if duplicate side effects occurred during execution.
Official API references
Consult the following references when upgrading dependencies or reviewing production configuration:
- LangGraph fault tolerance
- RetryPolicy API reference
- TimeoutPolicy API reference
- Graph-wide node defaults
- NodeTimeoutError API reference
- LangGraph retry implementation
Connection to durable execution
Automatic retries protect an active workflow against temporary dependency failures. Durable execution addresses an additional problem: preserving workflow progress when an execution process itself fails or restarts.
Checkpointers preserve graph execution state, allowing supported recovery paths to continue from persisted progress rather than blindly restarting completed work. However, a node that must execute again can still repeat external operations.
Reliable agent engineering therefore requires both execution recovery and business-level correctness.
In the next lesson, Error handlers, recovery and graceful degradation, you will learn what happens when retry budgets are exhausted. You will attach recovery handlers to nodes, inspect structured failure information, redirect execution with Command, and design alternative paths that allow workflows to produce useful outcomes even when their primary dependencies remain unavailable.
Build a resilient inventory workflow
Build an asynchronous inventory workflow that automatically recovers from simulated API failures and slow responses. Configure graph-wide retry defaults, a per-node timeout, and selective exception handling. Verify that temporary failures recover, permanent failures stop immediately, and repeated timeouts cannot trigger unlimited attempts.
import asyncio
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.types import RetryPolicy, TimeoutPolicy
from langgraph.errors import NodeTimeoutError
class InventoryState(TypedDict, total=False):
product_id: str
scenario: str
quantity: int
attempts: int
available: bool
class InventoryUnavailable(Exception):
pass
async def fetch_inventory(
state: InventoryState,
runtime: Runtime,
) -> dict:
attempt = runtime.execution_info.node_attempt
print(f"Inventory API attempt {attempt}")
scenario = state["scenario"]
if scenario == "invalid":
raise ValueError("Invalid product identifier")
if scenario == "transient" and attempt < 3:
raise InventoryUnavailable("Service unavailable")
if scenario == "slow" and attempt == 1:
await asyncio.sleep(2)
if scenario == "always_slow":
await asyncio.sleep(2)
return {"quantity": 15, "attempts": attempt}
async def check_availability(state: InventoryState) -> dict:
return {"available": state["quantity"] > 0}
# TODO: Create a selective RetryPolicy.
# Allow at most three attempts.
# Retry InventoryUnavailable and NodeTimeoutError.
# Disable jitter for predictable testing.
# TODO: Create a StateGraph with graph-wide retry defaults.
# TODO: Register fetch_inventory with a 0.5-second timeout.
# TODO: Register check_availability and connect the graph.
# TODO: Compile the graph and test all four scenarios.import asyncio
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.types import RetryPolicy, TimeoutPolicy
from langgraph.errors import NodeTimeoutError
class InventoryState(TypedDict, total=False):
product_id: str
scenario: str
quantity: int
attempts: int
available: bool
class InventoryUnavailable(Exception):
pass
async def fetch_inventory(
state: InventoryState,
runtime: Runtime,
) -> dict:
attempt = runtime.execution_info.node_attempt
print(f"Inventory API attempt {attempt}")
scenario = state["scenario"]
if scenario == "invalid":
raise ValueError("Invalid product identifier")
if scenario == "transient" and attempt < 3:
raise InventoryUnavailable("Service unavailable")
if scenario == "slow" and attempt == 1:
await asyncio.sleep(2)
if scenario == "always_slow":
await asyncio.sleep(2)
return {"quantity": 15, "attempts": attempt}
async def check_availability(state: InventoryState) -> dict:
return {"available": state["quantity"] > 0}
policy = RetryPolicy(
max_attempts=3,
initial_interval=0.1,
backoff_factor=2.0,
max_interval=1.0,
jitter=False,
retry_on=(InventoryUnavailable, NodeTimeoutError),
)
builder = StateGraph(InventoryState)
builder.set_node_defaults(retry_policy=policy)
builder.add_node(
"fetch_inventory",
fetch_inventory,
timeout=TimeoutPolicy(run_timeout=0.5),
)
builder.add_node("check_availability", check_availability)
builder.add_edge(START, "fetch_inventory")
builder.add_edge("fetch_inventory", "check_availability")
builder.add_edge("check_availability", END)
graph = builder.compile()
async def main():
for scenario in (
"transient",
"slow",
"invalid",
"always_slow",
):
print(f"\nScenario: {scenario}")
try:
result = await graph.ainvoke(
{
"product_id": "SKU-101",
"scenario": scenario,
},
config={"recursion_limit": 20},
)
print(result)
assert result["available"] is True
assert result["quantity"] == 15
if scenario == "transient":
assert result["attempts"] == 3
elif scenario == "slow":
assert result["attempts"] == 2
else:
raise AssertionError("Expected failure")
except ValueError:
assert scenario == "invalid"
print("Permanent validation failure")
except NodeTimeoutError:
assert scenario == "always_slow"
print("Timeout retry budget exhausted")
if __name__ == "__main__":
asyncio.run(main())Summary
- RetryPolicy automatically repeats failed node executions when their exceptions satisfy a configured retry condition.
- The maximum attempt count includes the original execution rather than counting only subsequent retries.
- Exponential backoff and jitter reduce contention and prevent synchronized retry storms during service outages.
- Selective exception handling prevents unnecessary retries of permanent failures and programming errors.
- Graph-wide defaults standardize fault tolerance while allowing individual nodes to override their policies.
- TimeoutPolicy limits individual asynchronous node attempts using wall-clock and inactivity deadlines.
- Retried operations must protect external side effects using stable idempotency keys or equivalent deduplication mechanisms.