Node caching, loop guards and a fault-tolerant workflow
Overview
A production agent must do more than produce correct answers under ideal conditions. It must operate efficiently when requests repeat, terminate when reasoning stops making progress, and recover when dependencies fail.
Consider a customer-support agent that retrieves product documentation, checks inventory availability, validates its findings, and publishes a response.
Several operational problems can arise:
- Repeated questions trigger identical and expensive retrieval operations.
- An external API becomes temporarily unavailable.
- A dependency stops responding.
- The agent repeatedly validates an answer without improving it.
- A service outage prevents the workflow from completing normally.
- An application failure occurs after an external operation has already succeeded.
Each problem requires a different protection mechanism.
In the preceding lessons, we explored retries, exponential backoff, timeouts, recovery handlers, durable execution, and idempotent operations.
This lesson introduces two additional capabilities: node caching and loop guards. We then integrate the entire chapter into a fault-tolerant workflow.
The objective is not to make every execution succeed. It is to ensure that failures have predictable, bounded, and observable consequences.
Environment setup
Use Python 3.11 or newer:
pip install -U "langgraph>=1.2,<2"LangGraph 1.2 or newer is required for the native error-handler and timeout APIs used in the project.
All examples simulate external dependencies, so no language model, API key, or external database is required.
The implementation follows the current LangGraph node configuration, control flow, and fault tolerance documentation. The examples have been reviewed against these APIs but have not been execution-tested in the authoring environment.
Node caching
Caching stores the result of an operation so subsequent equivalent requests can reuse it rather than repeating the work.
Suppose a document-retrieval node takes two seconds to retrieve information about a product. If hundreds of users request the same product information, repeatedly executing that operation wastes computation and increases dependency traffic.
A cache allows the first execution to retrieve the information while subsequent executions reuse its result.
LangGraph supports this behavior directly at the node level.
How node caching works internally
When a cache-enabled node is scheduled, LangGraph derives a cache key from its input and looks for an existing entry.
If a usable entry exists, the node function is skipped. The previously recorded output is applied through normal graph execution.
Otherwise, the node executes, and its successful result becomes available for future cache lookups.
The following diagram illustrates the cache lookup lifecycle.
Caching does not skip the entire graph. Downstream nodes still execute unless another mechanism allows their work to be reused.
Configuring CachePolicy
Two components are required:
- A
CachePolicyattached to the relevant node. - A cache backend supplied when compiling the graph.
The CachePolicy class supports two main parameters.
| Parameter | Purpose | Default |
|---|---|---|
key_func |
Derives a cache key from node input | Pickle-based input hashing |
ttl |
Controls entry lifetime in seconds | No expiration |
TTL stands for time to live. It determines how long an entry remains eligible for reuse.
Your first cached node
This example simulates a slow product lookup. The second execution uses the same compiled graph and identical input.
import time
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.cache.memory import InMemoryCache
from langgraph.types import CachePolicy
class State(TypedDict):
product_id: str
description: str
def lookup_product(state: State) -> dict:
print("Executing external product lookup")
time.sleep(1)
return {
"description": f"Product details for {state['product_id']}"
}
builder = StateGraph(State)
builder.add_node(
"lookup_product",
lookup_product,
cache_policy=CachePolicy(ttl=60),
)
builder.add_edge(START, "lookup_product")
builder.add_edge("lookup_product", END)
graph = builder.compile(cache=InMemoryCache())
inputs = {
"product_id": "P100",
"description": "",
}
for run in range(1, 3):
started = time.perf_counter()
result = graph.invoke(inputs)
elapsed = time.perf_counter() - started
print(f"Run {run}: {elapsed:.3f} seconds")
print(result)Illustrative output:
Executing external product lookup
Run 1: 1.005 seconds
{'product_id': 'P100', 'description': 'Product details for P100'}
Run 2: 0.002 seconds
{'product_id': 'P100', 'description': 'Product details for P100'}Actual timings depend on the execution environment. The important observation is that the lookup function executes only once.
You can also inspect cache hits using the updates streaming mode. A cached update can include __metadata__ containing {"cached": True}.
Designing custom cache keys
The default key is derived from the node’s input. This is convenient, but entire state objects often contain information irrelevant to a particular operation.
Consider a document-retrieval node whose input state contains a query, document-index version, request identifier, validation counter, and conversation history.
If retrieval depends only on the query and index version, unrelated state changes should not invalidate the cache.
Conversely, omitting an input that affects the output can produce incorrect results.
The following example defines a custom key that incorporates the query, tenant identifier, and index version while ignoring the request identifier.
import json
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.cache.memory import InMemoryCache
from langgraph.types import CachePolicy
class State(TypedDict):
query: str
tenant_id: str
index_version: str
request_id: str
result: str
def retrieval_key(state: State) -> str:
return json.dumps(
[
"retrieval-v1",
state["tenant_id"],
state["index_version"],
state["query"],
],
separators=(",", ":"),
)
def retrieve(state: State) -> dict:
print("Executing retrieval")
return {
"result": (
f"Documents for {state['query']} "
f"in tenant {state['tenant_id']}"
)
}
graph = (
StateGraph(State)
.add_node(
"retrieve",
retrieve,
cache_policy=CachePolicy(
key_func=retrieval_key,
ttl=300,
),
)
.add_edge(START, "retrieve")
.add_edge("retrieve", END)
.compile(cache=InMemoryCache())
)
for tenant, request_id, version in [
("tenant-a", "request-1", "v1"),
("tenant-a", "request-2", "v1"),
("tenant-b", "request-3", "v1"),
("tenant-a", "request-4", "v2"),
]:
result = graph.invoke({
"query": "Return policy",
"tenant_id": tenant,
"index_version": version,
"request_id": request_id,
"result": "",
})
print(request_id, result["result"])Expected output:
Executing retrieval
request-1 Documents for Return policy in tenant tenant-a
request-2 Documents for Return policy in tenant tenant-a
Executing retrieval
request-3 Documents for Return policy in tenant tenant-b
Executing retrieval
request-4 Documents for Return policy in tenant tenant-aRequest two reuses the cached result. Request three belongs to another tenant, while request four uses a different document-index version. Both require fresh execution.
In production, tenant identifiers must come from authenticated application context. Where permissions differ within a tenant, authorization scope must also influence cache isolation.
Runtime context is not automatically represented in a node-input cache key. If context changes the result, include the relevant trusted identifier in the cache input or avoid caching that node.
Choosing what to cache
| Operation | Cache? | Consideration |
|---|---|---|
| Static documentation retrieval | Yes | Invalidate when documents change |
| Text normalization | Yes | Usually deterministic |
| Expensive read-only calculations | Yes | Include all calculation inputs |
| LLM classification | Conditionally | Include model and prompt versions |
| Live inventory availability | Conditionally | Freshness may be critical |
| Financial transactions | No | External side effects |
| Sending notifications | No | Every logical operation matters |
| Loop-control decisions | Usually no | Depends on evolving state |
A cached node’s complete output matters, not just its most expensive field.
For example, caching a node that retrieves a document and increments an iteration counter could replay an outdated counter. Separate reusable computation from execution-specific state changes.
Note: A cache is not an idempotency mechanism. It cannot guarantee that an external write occurs exactly once, particularly after cache expiration, concurrent misses, or process failure.
Cache expiration and production considerations
A short TTL improves freshness but reduces the cache hit rate. A long TTL improves reuse but increases the possibility of stale results.
Choose expiration according to business requirements. Product descriptions might tolerate several minutes of staleness; inventory reservations may require immediate accuracy.
InMemoryCache is process-local and volatile. Python also provides SqliteCache for persistent local caching. Distributed deployments require a cache strategy appropriate to their worker topology.
Do not assume that simultaneous requests for an uncached key are automatically consolidated into one dependency call. High-traffic systems may require request coalescing or concurrency controls.
Caching versus checkpointing
Although both mechanisms reuse previously recorded information, they have different responsibilities.
| Characteristic | Node caching | Checkpointing |
|---|---|---|
| Primary objective | Avoid recomputation | Preserve execution progress |
| Lookup identity | Node input and cache key | Thread and checkpoint identity |
| Lifetime | TTL and backend lifetime | Persistence and retention policy |
| Cross-thread reuse | Possible | Not ordinary checkpoint behavior |
| Workflow recovery | Not sufficient | Supported |
| Human-in-the-loop | Not sufficient | Required for persisted interrupts |
A workflow can use both simultaneously:
builder.compile(cache=InMemoryCache(), checkpointer=InMemorySaver())
A cache hit avoids unnecessary work. A checkpoint allows unfinished execution to resume. Neither replaces the other.
Infinite-loop prevention
Agentic workflows frequently contain cycles.
A model generates an answer, a validator evaluates it, and the workflow returns to the model when improvement is necessary.
This is useful when each iteration moves the system toward a meaningful completion condition.
However, an agent may repeatedly produce invalid responses, issue the same tool call, or alternate between two states indefinitely.
Production loops therefore need explicit termination policies.
Application-level iteration budgets
An iteration counter represents a business-level budget, such as the maximum number of document searches, answer revisions, or tool calls.
Unlike an internal execution limit, it allows the application to decide what should happen when that budget is exhausted.
The following example simulates answer refinement with a maximum of three iterations. The target quality is deliberately unreachable within that budget.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command
class State(TypedDict):
quality: int
iterations: int
target_quality: int
status: str
MAX_ITERATIONS = 3
def improve_answer(
state: State,
) -> Command[Literal["improve_answer", "__end__"]]:
quality = state["quality"] + 10
iterations = state["iterations"] + 1
updates = {
"quality": quality,
"iterations": iterations,
}
print(f"Iteration {iterations}: quality={quality}")
if quality >= state["target_quality"]:
return Command(
update={**updates, "status": "success"},
goto=END,
)
if iterations >= MAX_ITERATIONS:
return Command(
update={**updates, "status": "degraded"},
goto=END,
)
return Command(
update=updates,
goto="improve_answer",
)
graph = (
StateGraph(State)
.add_node("improve_answer", improve_answer)
.add_edge(START, "improve_answer")
.compile()
)
result = graph.invoke(
{
"quality": 40,
"iterations": 0,
"target_quality": 90,
"status": "pending",
},
{"recursion_limit": 15},
)
print(result)Expected output:
Iteration 1: quality=50
Iteration 2: quality=60
Iteration 3: quality=70
{'quality': 70, 'iterations': 3, 'target_quality': 90, 'status': 'degraded'}The workflow terminates normally and preserves its best available result.
In a real agent, quality would come from structured validation, deterministic business rules, or an evaluation model rather than an artificial increment.
The graph recursion limit
LangGraph provides an additional emergency safeguard through recursion_limit.
The current default is 10,007 supersteps, which is far too permissive for many production agent workflows.
Set an explicit limit appropriate to your graph.
The recursion limit measures graph supersteps, not Python recursion depth. Parallel nodes can execute in the same superstep, while sequential nodes generally require separate supersteps.
Retries within a node attempt sequence are also distinct from graph-loop iterations.
The following example deliberately constructs a graph that never reaches END, demonstrating how the engine eventually terminates it.
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START
from langgraph.errors import GraphRecursionError
class State(TypedDict):
count: int
def repeat_forever(state: State) -> dict:
count = state["count"] + 1
print("Executing loop:", count)
return {"count": count}
builder = StateGraph(State)
builder.add_node("repeat", repeat_forever)
builder.add_edge(START, "repeat")
builder.add_edge("repeat", "repeat")
graph = builder.compile()
try:
graph.invoke(
{"count": 0},
{"recursion_limit": 5},
)
except GraphRecursionError:
print("Emergency execution limit reached")The workflow eventually raises GraphRecursionError. The caller catches it and reports that the safety limit was reached.
Unlike the earlier application-level guard, this represents abnormal termination rather than successful graceful completion.
Proactive termination with RemainingSteps
Instead of waiting for the recursion exception, nodes can inspect the remaining graph execution budget.
LangGraph exposes this through the managed state value RemainingSteps.
The next example uses the remaining budget to route to a finalization node before the engine terminates execution.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.managed.is_last_step import RemainingSteps
from langgraph.types import Command
class State(TypedDict):
iterations: int
status: str
remaining_steps: RemainingSteps
def reason(
state: State,
) -> Command[Literal["reason", "finalize"]]:
iterations = state["iterations"] + 1
print(
"Iteration:", iterations,
"Remaining steps:", state["remaining_steps"],
)
if state["remaining_steps"] <= 3:
return Command(
update={"iterations": iterations},
goto="finalize",
)
return Command(
update={"iterations": iterations},
goto="reason",
)
def finalize(state: State) -> dict:
return {"status": "budget_exhausted"}
graph = (
StateGraph(State)
.add_node("reason", reason)
.add_node("finalize", finalize)
.add_edge(START, "reason")
.add_edge("finalize", END)
.compile()
)
result = graph.invoke(
{"iterations": 0, "status": "pending"},
{"recursion_limit": 10},
)
print(result["status"])Expected final output:
budget_exhaustedremaining_steps is supplied by LangGraph. Do not initialize or manually decrement it.
Reserve enough steps for finalization, compensation, or escalation rather than consuming the entire budget on reasoning.
Detecting lack of progress
Iteration limits prevent unlimited execution but do not necessarily prevent wasted work.
For example, if an agent issues the same invalid SQL query five times, allowing another five attempts is unlikely to help.
Useful progress guards include tracking repeated tool arguments, comparing validation scores, detecting repeated state signatures, and monitoring whether new evidence has been discovered.
Distinguish meaningful progress from superficial changes. A rewritten answer is not necessarily a better answer.
Combine stagnation detection with iteration limits, elapsed-time budgets, token budgets, and the graph recursion limit.
Tip: Treat
GraphRecursionErroras an emergency safeguard, not the normal completion mechanism for an agent.
The layered model
Fault tolerance works best when several independent protections cooperate.
Each layer addresses a different category of failure.
| Layer | Mechanism | Responsibility |
|---|---|---|
| 1 | Node caching | Avoid repeated computation |
| 2 | Timeout policy | Bound individual execution attempts |
| 3 | Retry policy | Recover from temporary failures |
| 4 | Error handler | Recover when retries cannot succeed |
| 5 | Loop guard | Prevent unbounded application cycles |
| 6 | Recursion limit | Enforce an engine-level execution budget |
| 7 | Checkpointing | Preserve resumable execution progress |
| 8 | Idempotency | Protect external operations from duplication |
When a cached result is unavailable, the node executes under its timeout policy. A failure is classified by the retry policy. If another attempt is inappropriate, the error handler can choose an alternative route.
Loop guards constrain repeated graph transitions. Checkpointing protects progress, while idempotency protects external effects that graph state alone cannot control.
These are cooperating responsibilities rather than eight strictly sequential processing stages.
Project: a fault-tolerant workflow
We will build an inventory-reporting workflow that combines the chapter’s resilience mechanisms.
The workflow retrieves product metadata, obtains live inventory information, validates the report, and publishes a confirmation.
It must handle temporary connection failures, timeouts, persistent outages, excessive validation iterations, and an acknowledgement lost after publication.
Workflow architecture
The following diagram shows the normal execution path and its recovery branches.
The product catalog is cacheable because its simulated contents are stable. Live inventory is deliberately not cached because availability may change.
Publication is an external side effect and therefore requires deduplication instead of caching.
Complete implementation
Save the following program as fault_tolerant_workflow.py.
import asyncio
import json
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.types import (
CachePolicy,
RetryPolicy,
TimeoutPolicy,
Command,
)
from langgraph.errors import NodeError, NodeTimeoutError
from langgraph.cache.memory import InMemoryCache
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict):
request_id: str
sku: str
scenario: str
product_name: str
quantity: int | None
validations: int
required_validations: int
status: str
reason: str
receipt: str
catalog = {
"SKU-100": "Wireless keyboard",
}
catalog_calls = 0
publication_ledger: dict[str, str] = {}
def catalog_key(state: State) -> str:
return json.dumps(["catalog-v1", state["sku"]])
def fetch_catalog(state: State) -> dict:
global catalog_calls
catalog_calls += 1
print("CATALOG: external lookup")
return {
"product_name": catalog[state["sku"]]
}
async def fetch_inventory(
state: State,
runtime: Runtime,
) -> Command[Literal["validate_report"]]:
attempt = runtime.execution_info.node_attempt
scenario = state["scenario"]
print(f"INVENTORY: attempt {attempt}")
if scenario == "outage":
raise ConnectionError("Inventory API unavailable")
if scenario == "temporary":
if attempt == 1:
raise ConnectionError("Connection interrupted")
if attempt == 2:
await asyncio.sleep(2)
if scenario == "invalid":
raise ValueError("Invalid inventory request")
await asyncio.sleep(0.05)
return Command(
update={"quantity": 24},
goto="validate_report",
)
def recover_inventory(
state: State,
error: NodeError,
) -> Command[Literal["degraded_report"]]:
if not isinstance(
error.error,
(ConnectionError, NodeTimeoutError),
):
raise error.error
print(f"RECOVERY: {error.node}")
return Command(
update={
"quantity": None,
"reason": "Inventory availability unknown",
},
goto="degraded_report",
)
def validate_report(
state: State,
) -> Command[
Literal[
"validate_report",
"publish_report",
"degraded_report",
]
]:
validations = state["validations"] + 1
print(f"VALIDATION: round {validations}")
if validations >= state["required_validations"]:
return Command(
update={"validations": validations},
goto="publish_report",
)
if validations >= 3:
return Command(
update={
"validations": validations,
"reason": "Validation budget exhausted",
},
goto="degraded_report",
)
return Command(
update={"validations": validations},
goto="validate_report",
)
def degraded_report(state: State) -> dict:
print("DEGRADED:", state["reason"])
return {
"status": "degraded",
"receipt": "",
}
def publish_report(state: State) -> dict:
key = f"inventory-report:{state['request_id']}"
if key not in publication_ledger:
receipt = f"REPORT-{len(publication_ledger) + 1}"
publication_ledger[key] = receipt
print("PUBLISH: created", receipt)
if state["scenario"] == "resume":
raise ConnectionError("Acknowledgement lost")
else:
print("PUBLISH: reusing existing receipt")
return {
"receipt": publication_ledger[key],
"status": "success",
}
builder = StateGraph(State)
builder.add_node(
"fetch_catalog",
fetch_catalog,
cache_policy=CachePolicy(
key_func=catalog_key,
ttl=300,
),
)
builder.add_node(
"fetch_inventory",
fetch_inventory,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
backoff_factor=2.0,
max_interval=1.0,
jitter=False,
retry_on=(ConnectionError, NodeTimeoutError),
),
timeout=TimeoutPolicy(run_timeout=0.5),
error_handler=recover_inventory,
)
builder.add_node("validate_report", validate_report)
builder.add_node("degraded_report", degraded_report)
builder.add_node("publish_report", publish_report)
builder.add_edge(START, "fetch_catalog")
builder.add_edge("fetch_catalog", "fetch_inventory")
builder.add_edge("degraded_report", END)
builder.add_edge("publish_report", END)
graph = builder.compile(
cache=InMemoryCache(),
checkpointer=InMemorySaver(),
)
def make_input(
request_id: str,
scenario: str,
required_validations: int = 2,
) -> State:
return {
"request_id": request_id,
"sku": "SKU-100",
"scenario": scenario,
"product_name": "",
"quantity": None,
"validations": 0,
"required_validations": required_validations,
"status": "pending",
"reason": "",
"receipt": "",
}
def make_config(thread_id: str) -> dict:
return {
"configurable": {"thread_id": thread_id},
"recursion_limit": 20,
}
async def main():
print("\nTEST 1: Temporary API failures")
first = await graph.ainvoke(
make_input("REQ-1", "temporary"),
make_config("thread-1"),
durability="sync",
)
assert first["status"] == "success"
assert first["quantity"] == 24
assert first["validations"] == 2
print("\nTEST 2: Persistent outage")
second = await graph.ainvoke(
make_input("REQ-2", "outage"),
make_config("thread-2"),
durability="sync",
)
assert second["status"] == "degraded"
assert second["quantity"] is None
assert second["receipt"] == ""
print("\nTEST 3: Validation loop guard")
third = await graph.ainvoke(
make_input("REQ-3", "normal", 10),
make_config("thread-3"),
durability="sync",
)
assert third["status"] == "degraded"
assert third["validations"] == 3
print("\nTEST 4: Checkpoint-based recovery")
config = make_config("thread-4")
try:
await graph.ainvoke(
make_input("REQ-4", "resume"),
config,
durability="sync",
)
except ConnectionError:
print("Execution failed after publication")
else:
raise AssertionError("Expected publication failure")
snapshot = await graph.aget_state(config)
print("Pending nodes:", snapshot.next)
resumed = await graph.ainvoke(
None,
config,
durability="sync",
)
assert resumed["status"] == "success"
assert resumed["receipt"] == publication_ledger[
"inventory-report:REQ-4"
]
print("\nTEST 5: Non-retryable failure")
try:
await graph.ainvoke(
make_input("REQ-5", "invalid"),
make_config("thread-5"),
durability="sync",
)
except ValueError:
print("Invalid request rejected")
else:
raise AssertionError("Expected ValueError")
assert catalog_calls == 1
assert len(publication_ledger) == 2
print("\nCatalog API calls:", catalog_calls)
print("Unique publications:", len(publication_ledger))
print("All fault-tolerance tests passed")
if __name__ == "__main__":
asyncio.run(main())Execute the program:
python fault_tolerant_workflow.pyExpected output:
TEST 1: Temporary API failures
CATALOG: external lookup
INVENTORY: attempt 1
INVENTORY: attempt 2
INVENTORY: attempt 3
VALIDATION: round 1
VALIDATION: round 2
PUBLISH: created REPORT-1
TEST 2: Persistent outage
INVENTORY: attempt 1
INVENTORY: attempt 2
INVENTORY: attempt 3
RECOVERY: fetch_inventory
DEGRADED: Inventory availability unknown
TEST 3: Validation loop guard
INVENTORY: attempt 1
VALIDATION: round 1
VALIDATION: round 2
VALIDATION: round 3
DEGRADED: Validation budget exhausted
TEST 4: Checkpoint-based recovery
INVENTORY: attempt 1
VALIDATION: round 1
VALIDATION: round 2
PUBLISH: created REPORT-2
Execution failed after publication
Pending nodes: ('publish_report',)
PUBLISH: reusing existing receipt
TEST 5: Non-retryable failure
INVENTORY: attempt 1
Invalid request rejected
Catalog API calls: 1
Unique publications: 2
All fault-tolerance tests passedUnderstanding the recovery scenarios
Temporary failure: The first inventory attempt raises a connection exception. The second exceeds its timeout. The third succeeds. Neither failed attempt produces a successful inventory state update.
Persistent outage: All three attempts fail. The recovery handler receives a NodeError and redirects execution to the degraded-report node. Unknown inventory remains None; it is never incorrectly represented as zero.
Runaway validation: The simulated validator requires ten iterations, but the business budget permits only three. The graph returns a degraded result without publishing an unvalidated report.
Lost acknowledgement: Publication succeeds externally before the node raises an exception. Publication intentionally has no automatic retry policy here, allowing us to demonstrate checkpoint recovery explicitly. Calling ainvoke(None, config) resumes unfinished work on the same thread. The stable operation key prevents a second publication.
Permanent failure: Invalid input raises ValueError. The retry policy excludes it, and the recovery handler re-raises it instead of concealing the failure behind a degraded result.
Throughout these executions, the product catalog is retrieved only once. Each request uses a separate thread while sharing the same eligible cached catalog result.
Important implementation decisions
The project uses simulated validation rounds instead of an LLM evaluator to make failure scenarios reproducible.
Its in-memory checkpointer demonstrates resumption within a running process, not recovery after process termination.
Similarly, the dictionary-based publication ledger illustrates deduplication but does not provide persistent or concurrency-safe guarantees.
For production deployment, replace these educational components with durable infrastructure.
Moving the workflow toward production
Install PostgreSQL checkpoint support when persistent recovery is required:
pip install -U "langgraph-checkpoint-postgres" "psycopg[binary,pool]"For asynchronous graphs, use AsyncPostgresSaver from langgraph.checkpoint.postgres.aio, initialize its database structures with await checkpointer.setup(), and manage its connection lifecycle appropriately.
Use a persistent external operation ledger or provider-supported idempotency mechanism for publication. Stable operation identifiers must represent immutable logical requests; reject attempts to reuse an identifier with conflicting business data.
The graph should also enforce authenticated tenant isolation, dependency-level request timeouts, realistic overall execution deadlines, and bounded concurrency.
Replace simulated checks with meaningful validation rules. Return degraded results only when incomplete information is acceptable to the business operation.
Common production mistakes
| Mistake | Consequence | Correction |
|---|---|---|
| Caching every node | Stale decisions and skipped operations | Cache selectively |
| Incomplete cache keys | Incorrect or unauthorized reuse | Include relevant scope and versions |
| Retrying every exception | Repeated defects and wasted requests | Classify transient failures |
| Unlimited validation loops | Excessive latency and cost | Enforce business budgets |
| Relying only on recursion limits | Abrupt termination | Add graceful exit paths |
| Returning zero for unavailable data | Misleading business results | Represent unknown values explicitly |
| Using volatile checkpoint storage | Progress lost after restart | Use persistent checkpointers |
| Assuming checkpoints prevent duplicate writes | Repeated external effects | Enforce idempotency externally |
Fault tolerance must be tested rather than assumed. Introduce failures deliberately and verify final state, dependency call counts, recovery routes, and external effects.
Preparing for the next chapter
A resilient workflow still needs operational visibility.
When an agent retries three times, serves a cached result, approaches its loop budget, or returns a degraded report, developers need to understand why.
Production monitoring should capture metrics such as:
- Cache hit and miss rates.
- Retry counts and exception categories.
- Node execution durations and timeout frequency.
- Recovery-handler activation rates.
- Validation iteration counts.
- Successful, degraded, and failed executions.
- Checkpoint recovery events.
- Duplicate operations prevented.
In the next lesson, Tracing and monitoring with LangSmith, you will learn how to inspect graph executions, investigate failures, analyze node-level latency, and observe agent behavior across production requests.
The fault-tolerant workflow constructed here provides a practical foundation for understanding those traces and converting operational failures into measurable engineering improvements.
Build a resilient document retrieval workflow
Build a workflow that retrieves a document from a simulated API, caches successful retrieval results for 60 seconds, and performs bounded validation. Configure the retrieval node to retry temporary connection failures and recover from a simulated first-attempt failure. Limit validation to three iterations and return an explicit degraded status when validation cannot succeed within that budget. Verify that repeated requests reuse the cached document without repeating the API call.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.cache.memory import InMemoryCache
from langgraph.runtime import Runtime
from langgraph.types import CachePolicy, RetryPolicy, Command
class State(TypedDict):
document_id: str
document: str
checks: int
required_checks: int
status: str
api_calls = 0
def retrieve_document(state: State, runtime: Runtime) -> dict:
global api_calls
api_calls += 1
if runtime.execution_info.node_attempt == 1:
raise ConnectionError("Temporary document API failure")
return {
"document": f"Content of {state['document_id']}"
}
def validate_document(
state: State,
) -> Command[Literal["validate_document", "__end__"]]:
# TODO: Increment the validation counter.
# TODO: Finish successfully when validation passes.
# TODO: Return degraded status after three checks.
# TODO: Otherwise route back to this node.
raise NotImplementedError
# TODO: Configure a retry policy with three maximum attempts.
# TODO: Cache retrieval results using the document ID as the key.
# TODO: Compile the graph with InMemoryCache.
# TODO: Set an explicit recursion limit.
# TODO: Test successful validation and degraded validation.
# TODO: Verify that the second request does not call the API.from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.cache.memory import InMemoryCache
from langgraph.runtime import Runtime
from langgraph.types import CachePolicy, RetryPolicy, Command
class State(TypedDict):
document_id: str
document: str
checks: int
required_checks: int
status: str
api_calls = 0
def retrieve_document(state: State, runtime: Runtime) -> dict:
global api_calls
api_calls += 1
if runtime.execution_info.node_attempt == 1:
raise ConnectionError("Temporary document API failure")
return {
"document": f"Content of {state['document_id']}"
}
def validate_document(
state: State,
) -> Command[Literal["validate_document", "__end__"]]:
checks = state["checks"] + 1
if checks >= state["required_checks"]:
return Command(
update={"checks": checks, "status": "success"},
goto=END,
)
if checks >= 3:
return Command(
update={"checks": checks, "status": "degraded"},
goto=END,
)
return Command(
update={"checks": checks},
goto="validate_document",
)
builder = StateGraph(State)
builder.add_node(
"retrieve_document",
retrieve_document,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
jitter=False,
retry_on=ConnectionError,
),
cache_policy=CachePolicy(
key_func=lambda state: state["document_id"],
ttl=60,
),
)
builder.add_node("validate_document", validate_document)
builder.add_edge(START, "retrieve_document")
builder.add_edge("retrieve_document", "validate_document")
graph = builder.compile(cache=InMemoryCache())
def make_input(required_checks: int) -> State:
return {
"document_id": "DOC-100",
"document": "",
"checks": 0,
"required_checks": required_checks,
"status": "pending",
}
config = {"recursion_limit": 10}
first = graph.invoke(make_input(2), config)
print("First execution:", first)
assert first["status"] == "success"
assert first["checks"] == 2
assert api_calls == 2
second = graph.invoke(make_input(5), config)
print("Second execution:", second)
assert second["status"] == "degraded"
assert second["checks"] == 3
assert api_calls == 2
print("Total API calls:", api_calls)
print("All assertions passed")Summary
- Node caching reuses previously computed node outputs when the relevant inputs match an unexpired cache entry.
- Cache keys must include every input that materially influences a node's output and authorization boundary.
- Checkpointing preserves execution progress while caching avoids unnecessary recomputation across executions.
- Explicit iteration budgets and progress checks provide graceful termination for potentially unbounded agent loops.
- The recursion limit acts as a graph-level emergency guard measured in supersteps rather than Python function calls.
- Reliable workflows combine selective retries, timeouts, recovery handlers, checkpointing, caching, and idempotent external operations.
- Fault-injection tests verify that workflows recover predictably from temporary failures, persistent outages, stalled operations, and interrupted execution.