flowchart TD
START(["START"]) --> risky["risky"]
risky -.->|"error set"| fallback["fallback"]
risky -.->|"no error"| normal["normal"]
normal --> END(["END"])
fallback --> END(["END"])
21 Error Handling

Every graph in this book so far has the same exposure: a node raises, the exception unwinds through invoke, and the run aborts. With a checkpointer the finished steps are already saved and you can resume from the last one saved (see Chapter 8) — but the current request still fails, and without a checkpointer everything it had done goes with it. On your laptop that costs a rerun. In a service it costs the user’s request, and the server in front of you cannot tell a model that hiccupped from a tool that is gone for the day.
A node will fail. The job of a production graph is not to prevent that — you can’t — but to stay up when it happens: retry what is worth retrying, route around what isn’t, and degrade to a decent answer instead of a stack trace.
The instinct from ordinary Python is to wrap the call in try/except and move on. That is half right. In a graph, a recovery is a piece of wiring, and the wiring differs with the kind of failure — which is why the chapter is three patterns, not one.
21.1 Three failures, three shapes
Here is a failure that showed up in this book’s own code, in an early draft of the evaluation harness of Chapter 32. Its chat calls were wrapped in a retry, because LM Studio on a shared machine drops and reloads models. The call that embeds the question for retrieval sat one step earlier and was not wrapped; the server swapped models under it, the embedding call raised, and the whole batch came down with a stack trace. The retry, attached to the wrong node, never got a chance. (The shipped harness wraps both.)
Sort that outage and its cousins by what a second attempt would do, and three responses fall out:
| Failure kind | Response | The shape |
|---|---|---|
| Transient — a blip, a one-off 5xx | Retry the node | RetryPolicy on the node |
| Permanent — this call always fails | Route to a fallback | catch, write to State, conditional edge |
| Non-critical — a nice-to-have tool dies | Skip it, answer anyway | catch, mark degraded, keep flowing |
There is a fourth response — a node crashes hard and you recover from a checkpoint — but that was Chapter 8 (Chapter 8): a checkpoint restores state, not the call stack. This chapter covers the other three.
Everything below is deterministic. The failures are simulated — a counter that trips twice, a raise that always fires — so the runnable file prints the same thing every run, with no LLM in the loop. Error handling is the code you cannot test by waiting for the network to misbehave.
21.2 Pattern 1: retry a transient fault with RetryPolicy
A dropped connection or a transient 500 is not a bug in your code — it is weather. The fix is to try again, and usually the second or third try sails through. You do not hand-roll a for loop with time.sleep: LangGraph has retry-with-backoff built in, and it attaches to a node as one keyword argument.
First the node. We simulate a flaky service with a module-level counter so the behavior is reproducible — it fails twice, then succeeds on the third call:
from typing import NotRequired, TypedDict
from langgraph.graph import START, END, StateGraph
from langgraph.types import RetryPolicy
_attempt = {"n": 0} # simulated flaky service: fails twice, succeeds on the third call
class S1(TypedDict):
result: NotRequired[str] # written by the node; absent in the initial input
def flaky_api_node(state: S1) -> dict:
_attempt["n"] += 1
if _attempt["n"] < 3:
print(f" attempt {_attempt['n']} -> raising ConnectionError (simulated network blip)")
raise ConnectionError("network blip")
print(f" attempt {_attempt['n']} -> success")
return {"result": "call succeeded"}The node does nothing special: it raises when it fails, as a real HTTP client would, and has no idea it will be retried. The retry lives on the wiring, where add_node takes a retry_policy:
def demo_retry() -> None:
print("\n########## Pattern 1: RetryPolicy auto-retries transient faults ##########")
b = StateGraph(S1)
b.add_node(
"api",
flaky_api_node,
retry_policy=RetryPolicy(
1 max_attempts=3,
initial_interval=0.1,
backoff_factor=2.0,
2 retry_on=(ConnectionError,),
),
)
b.add_edge(START, "api")
b.add_edge("api", END)
graph = b.compile()
_attempt["n"] = 0
result = graph.invoke({})
print(f" final: {result['result']} (the first two failures were retried away)")- 1
-
The numbers are less important than they look:
RetryPolicy()with no arguments is already three attempts (not five), starting at half a second and doubling. - 2
-
The decision that matters. Retrying a transient fault usually pays off — the attempts cost a little time, and a little money on a paid API, but the fault often clears; retrying a permanent one just spends the backoff delay three times for the same wall. The policy names which exceptions are weather (
ConnectionError) and, by omission, which are bugs (ValueError,TypeError).
Run it and the node visibly fails, fails, then succeeds — and invoke returns the success as if nothing went wrong. The two failures never reach the caller:
########## Pattern 1: RetryPolicy auto-retries transient faults ##########
attempt 1 -> raising ConnectionError (simulated network blip)
attempt 2 -> raising ConnectionError (simulated network blip)
attempt 3 -> success
final: call succeeded (the first two failures were retried away)
We passed retry_on=(ConnectionError,) to be explicit, but the parameter is optional — and its default is already the sane choice. Leave it off and LangGraph uses a built-in predicate, default_retry_on (internal: it lives in langgraph._internal._retry on 1.2.19, and nothing public exports it), that encodes the same instinct you would apply by hand:
It runs three checks in order, and the order is load-bearing:
- Retry
ConnectionErroroutright, and anyhttpx/requestserror whose status is a5xx(a server-side wobble the client can’t fix but a retry might). - Otherwise never retry a curated deny-list of “this is your bug” exceptions —
ValueError,TypeError,ArithmeticError,ImportError,LookupError,NameError,SyntaxError,RuntimeError,OSError, and their kin. Trying aValueErroragain just reproduces it. Note thatConnectionErroris anOSError; step 1 is what rescues it, which is why the order matters. - Retry anything else, on the optimistic assumption it might be transient.
retry_on accepts a single exception type, a tuple of types (what we used), or a callable predicate (exc) -> bool if you want to inspect the error — say, retry a 429 only when it carries a Retry-After header. RetryPolicy also carries max_interval (a ceiling on the backoff, default 128s) and jitter (default True, which spreads retries so a fleet of workers doesn’t stampede the recovering service in lockstep). For most nodes, RetryPolicy() with no arguments is a defensible starting point. The mistake that opened this chapter was not tuning but coverage: a policy protects only the node it is attached to, so every node that talks to the network needs its own.
In the output above, flaky_api_node ran three times. If the node’s body did anything to the outside world before it failed — charged a card, sent an email, inserted a row — a retry does that thing again. Three attempts, three charges.
A RetryPolicy is one more way a node runs more than once, and the same fixes apply as Chapter 15’s Gotcha: an upsert, an idempotency key, or the risky write isolated in its own node.
21.3 Pattern 2: catch and route to a fallback
Some failures no retry will fix — the input is malformed, the downstream is permanently down, the API key was revoked. Retrying is pointless; crashing is worse. The graceful move is to catch the error, write it into State, and let a conditional edge steer to a fallback node that gives the user a degraded-but-real reply instead of a 500.
This is the conditional-edge routing from Chapter 5, driven by an error field:
The risky node catches its own exception and records it, rather than letting it propagate and tear down the run:
class S2(TypedDict):
question: str # input, set by the caller
answer: NotRequired[str] # written by normal_answer or fallback
error: NotRequired[str] # written by risky_node when it fails
def risky_node(state: S2) -> dict:
try:
raise ValueError("downstream service permanently unavailable") # always fails
1 except ValueError as e:
print(f" risky_node failed and caught: {e}")
2 return {"error": str(e)}
def normal_answer_node(state: S2) -> dict:
return {"answer": "this is the normal, successful answer"}
def fallback_node(state: S2) -> dict:
# In production the user gets a generic message; the raw reason stays in the
# logs. This demo echoes it only so you can see the error travel through State.
return {"answer": f"Sorry, we cannot handle this right now (reason: {state['error']}). Please try again later."}- 1
-
Catch the specific fault you expect to be permanent —
ValueErrorhere, not a blanketexcept Exception. A broad catch would also swallow the programming bugs and the transient errors you would rather let aRetryPolicysee, and route every one of them to the same apology. - 2
-
The line that does the work. The error stops being control flow that unwinds the stack and becomes data in
Statethat the router can read. If it propagated instead, the whole graph would crash and no fallback would ever run.
The router is an ordinary function: no side effects, it reads State and returns a string naming the branch:
def route_on_error(state: S2) -> str:
return "fallback" if state.get("error") else "ok"Wiring it up, the conditional edge maps each string to a node. "ok" goes to the normal answer; "fallback" goes to the apology:
def demo_catch_and_route() -> None:
print("\n########## Pattern 2: catch the error + conditional edge to a fallback ##########")
b = StateGraph(S2)
b.add_node("risky", risky_node)
b.add_node("normal", normal_answer_node)
b.add_node("fallback", fallback_node)
b.add_edge(START, "risky")
b.add_conditional_edges("risky", route_on_error, {"ok": "normal", "fallback": "fallback"})
b.add_edge("normal", END)
b.add_edge("fallback", END)
graph = b.compile()
result = graph.invoke({"question": "ask me anything"})
print(f" user receives: {result['answer']}")
print(" -> the graph did not crash; it returned a graceful, degraded reply")The failure happens, is caught, and the user gets a courteous answer — the run completes cleanly:
########## Pattern 2: catch the error + conditional edge to a fallback ##########
risky_node failed and caught: downstream service permanently unavailable
user receives: Sorry, we cannot handle this right now (reason: downstream service permanently unavailable). Please try again later.
-> the graph did not crash; it returned a graceful, degraded reply
Keep the except narrow, in both senses. Catch a specific exception type, so an unexpected error still propagates instead of being quietly rerouted. And do not let the node swallow the error and return a plausible-looking answer: nothing downstream could then tell a fallback from a success, and the retry you add later would have nothing to trigger on. Against Pattern 1 the split is simple: RetryPolicy for a fault you expect to pass on a second look, catch-and-route for one you expect to persist.
error_handler=, timeout=, set_node_defaults
LangGraph 1.2 gave Pattern 2 a name. Instead of catching inside the node and routing on a State field, you can hand the fallback to add_node and let the runtime do the catching. The handler is an ordinary node; declare a parameter typed NodeError and the runtime injects the failure into it (.node is the name, .error the exception). It may return a state update, or — if it wants to steer — a Command from Section 10.6:
from langgraph.errors import NodeError
def raising_node(state: S2) -> dict:
raise ValueError("downstream service permanently unavailable") # no try/except
def fallback_handler(state: S2, error: NodeError) -> dict:
print(f" [handler] {error.node} raised {type(error.error).__name__}")
return {"answer": f"Sorry, we cannot handle this right now (reason: {error.error})."}
b = StateGraph(S2)
b.add_node("risky", raising_node, error_handler=fallback_handler) # the runtime catchesRun it and the user receives the same apology as above — without route_on_error, without the error field, without the conditional edge. Two neighbours arrived with it: add_node(..., timeout=) puts a wall-clock ceiling on each attempt — async nodes only, so none of this chapter’s def nodes qualifies, and the async chapter later on is where it runs — and builder.set_node_defaults(...) applies retry, cache, error-handler and timeout settings to every node at once, with a per-node argument still winning.
The chapter keeps the hand-rolled route as its mechanism because it is what error_handler= does for you; having built it, you can read the declarative form and its edge cases instead of trusting it.
21.4 Pattern 3: graceful degradation when a non-critical tool dies
The third pattern is the subtlest, because nothing here “fails” from the user’s point of view. The doc-bot answers from two sources: local docs (essential) and a web search (nice-to-have). If the web search dies, the answer must not die with it. So the node swallows its own failure, marks the run degraded, and the pipeline flows straight on to generate with whatever it has:
class S3(TypedDict):
question: str # input, set by the caller
docs: NotRequired[list] # written by local_search
web_results: NotRequired[list] # written by web_search (empty when it degrades)
degraded: NotRequired[bool] # written by web_search on failure
answer: NotRequired[str] # written by generate
def local_search_node(state: S3) -> dict:
return {"docs": ["local doc: Kafka configuration guide"]}
def web_search_node(state: S3) -> dict:
try:
raise TimeoutError("web search API timed out")
except Exception as e:
print(f" web_search failed, degrading gracefully: {e}")
# Do NOT re-raise: mark the run degraded and return empty results.
return {"web_results": [], "degraded": True}
def generate_node(state: S3) -> dict:
sources = state.get("docs", []) + state.get("web_results", [])
note = "(note: web retrieval is unavailable; answering from local docs only) " if state.get("degraded") else ""
return {"answer": f"{note}answer based on {len(sources)} source(s)"}The wiring is a plain linear pipeline (Chapter 4) with no branch. web always leads to generate; the only question is how much web managed to bring:
def demo_graceful() -> None:
print("\n########## Pattern 3: graceful degradation (a non-critical tool dies, keep going) ##########")
b = StateGraph(S3)
b.add_node("local", local_search_node)
b.add_node("web", web_search_node)
b.add_node("generate", generate_node)
b.add_edge(START, "local")
b.add_edge("local", "web")
b.add_edge("web", "generate")
b.add_edge("generate", END)
graph = b.compile()
result = graph.invoke({"question": "How do I configure Kafka?"})
print(f" answer: {result['answer']}")
print(" -> web died, but the local docs still produced an answer (degraded, not failed)")The web tool falls over and the user still gets a Kafka answer, built from one source instead of two, with a note saying so:
########## Pattern 3: graceful degradation (a non-critical tool dies, keep going) ##########
web_search failed, degrading gracefully: web search API timed out
answer: (note: web retrieval is unavailable; answering from local docs only) answer based on 1 source(s)
-> web died, but the local docs still produced an answer (degraded, not failed)
The difference from Pattern 2 is the intent. Pattern 2 catches an error on a critical path and routes to an apology because there is no real answer to give. Pattern 3 catches an error on a non-critical path and keeps going because there still is one, a slightly worse one. The degraded flag does not change whether you answer, only how you frame the answer and, in a real system, what you log and alert on. An undeclared degradation is how a half-broken system looks healthy on the dashboard until someone notices the answers got worse.
Right now web_search_node always raises. Give it a success path instead — replace the raise with return {"web_results": ["web: latest Kafka release notes"]} — and re-run. degraded never gets set, the apologetic note disappears, and the count climbs to answer based on 2 source(s). The wiring did not change, which is the property you want: a tool’s bad day should not require a different graph.
21.5 Caching a node so it doesn’t pay twice
Retries and degradation are about surviving failure. There is a quieter production concern next door: surviving success that costs too much. If a node makes an expensive call — a slow API, a paid LLM request — and the same input comes through twice, re-running it is money and latency spent to recompute an answer you already had. LangGraph can memoize a node by its input with a CachePolicy, in the same attach-to-the-node style as RetryPolicy. The chapter’s runnable file does not exercise this (it has no expensive nodes to cache), so treat the following as a sketch of the API rather than a line from ch19_error_handling.py.
CachePolicy
Caching has two moving parts: a cache backend you hand to compile, and a CachePolicy you attach to the node you want memoized.
from langgraph.types import CachePolicy
from langgraph.cache.memory import InMemoryCache
builder.add_node(
"expensive_search",
expensive_search_node,
cache_policy=CachePolicy(
key_func=lambda s: s["question"].lower().strip(), # what counts as one input
ttl=600, # how long a result lasts
),
)
graph = builder.compile(cache=InMemoryCache()) # the store the policy writes toCachePolicy has just two knobs, both keyword-only:
key_func— how a node’s input becomes a cache key. The default,default_cache_key,pickle-serializes the node’s input state and uses those bytes as the key: identical input, identical key, cache hit. That is a sensible default and a subtle constraint: the input must be picklable, and two inputs the model would treat as identical can still serialize to different bytes and miss: an extra space in the question ("kafka?"vs"kafka ?"), or a differently ordered dict nested inside a field. (Reordering the top-level state keys does not miss; theStateGraphschema normalizes those before the node sees them, so the node’s input serializes the same either way; it is structure inside a value that bites.) Supply your ownkey_funcwhen you want a coarser or normalized key: say, key a retrieval node on the lowercased, trimmed question and nothing else, so trivial variations still hit.ttl— how many seconds a cached result stays valid, orNone(the default) to keep it until the process or backend evicts it. Attlis how you say “cache this, but not forever” — right for anything whose upstream answer drifts, like a price lookup or a search over docs that change.
The mental model: RetryPolicy protects against a node running too few times (it failed, try again); CachePolicy protects against a node running too many times (same input, don’t recompute). Both attach to the node without touching its body.
The sharp edge is the mirror of the retry Gotcha: a cache hit means the node body does not run, so any side effect inside it does not fire the second time. Caching a pure computation is a clean win; caching a node that also writes to the outside world skips that write on a hit, with no error to tell you so. Cache functions of their input, not actions on the world.
21.6 Running it
The runnable file, code/ch19_error_handling.py, defines the three little graphs above and runs the three demos in order against the same simulated failures:
if __name__ == "__main__":
demo_retry() # transient fault: RetryPolicy
demo_catch_and_route() # permanent fault: catch + conditional edge
demo_graceful() # non-critical fault: degrade and continueBecause every failure is simulated with a counter and a raise, the output is identical every run.
21.7 The same shape elsewhere

Retry the transient thing, fall back when the retry is pointless, cache what you already paid for. The resilience libraries ship these as decorators, each with its own inventory: Resilience4j in Java has retry, fallback and cache as composable modules; Polly in .NET has retry and fallback policies, and carried a cache policy through v7; Netflix’s Hystrix is the circuit-breaker, isolation and fallback library of an earlier generation, with request caching but retries left to the caller. This chapter is those decorators one layer down, applied to a node instead of a method call.
One difference is worth the trade. In a resilience library the policies compose as a stack of wrappers around a single call, and reading the recovery path means reading the decorator order. Here the retry is a property of a node and the fallback is an edge — so the recovery path is part of the topology, in the same picture as the happy path. A reviewer can see that a failure routes to degrade without opening a single function.
21.8 The operational rule
Go back to the crash that opened the chapter. A model reload is weather, so the embedding call gets a RetryPolicy of its own, not just the chat call next to it; a model that is gone for good is permanent, so the chat node needs a fallback route rather than a third attempt; and in the doc-bot the web search is non-critical, so it degrades rather than routes. Three nodes, three different pieces of wiring, one question per node: does trying again help, and is this path essential?
Two of the details will bite in practice. retry_on is the decision that matters in a RetryPolicy; left off, default_retry_on already refuses ValueError and TypeError, and the default is three attempts. And both policies on a node re-run or skip its body: a retry can fire a write twice, a cache hit can skip it entirely, so keep external effects idempotent (Chapter 9) and cache only functions of input.

If you use create_agent from Chapter 13, the same moves ship as ModelRetryMiddleware, ToolRetryMiddleware, and ModelFallbackMiddleware (langchain.agents.middleware) — hooks on the seams you opened by hand in Chapter 19. RetryPolicy and the fallback route built here are the mechanism underneath those names.
The graph can now take a punch and stay standing. The next chapter leaves the failure modes alone and asks a different production question: nothing can reach this agent but your shell. Chapter 22, Serving over HTTP, puts the graph behind an endpoint.
New pieces in this chapter
| Piece | Usage |
|---|---|
| Type | |
RetryPolicy |
Retry-with-backoff for a transient fault, attached to the node it protects. add_node("api", fn, retry_policy=RetryPolicy(max_attempts=3, retry_on=…)); a retry re-runs side effects too |
CachePolicy |
Memoizes a node by its input, attached to the node like RetryPolicy. add_node("expensive_search", fn, cache_policy=CachePolicy(ttl=600)); a cache hit skips the node body — and its writes |
InMemoryCache |
An in-process cache backend the node policies write to. graph = builder.compile(cache=InMemoryCache()) |
Code in this chapter
| File | What it runs |
|---|---|
code/ch19_error_handling.py |
The three shapes of surviving failure: retry the node, degrade to a fallback path, and fail the run cleanly. |
Challenge
🥉 Bronze — prove the deny-list
Change flaky_api_node so that on its first attempt it raises ValueError("bad input") instead of ConnectionError, leaving the RetryPolicy as written (retry_on=(ConnectionError,)).
Predict first: how many times does the node run, and does invoke return or raise? Run it and confirm. Then widen retry_on to (ConnectionError, ValueError) and watch the behavior flip. Getting retry_on wrong costs you in either direction: wasted backoff, or a crash you could have caught.
Worked solution with tests: code/answers/ch19_prove_the_deny_list.py.
🥈 Silver — make the retried node idempotent
The retry Gotcha warned that a node body runs once per attempt, side effects and all. Make it bite, then fix it.
Give flaky_api_node a fake side effect — append to a module-level charges = [] list before the point where it might raise — and print len(charges) after the run. Observe that a “successful” call charged three times. Now make it idempotent: guard the append with an idempotency key (e.g. only append if a given request id is not already in a seen set) so that no matter how many times the node retries, the effect happens once. This is the Chapter 9 lesson (a replayed node must be safe to replay) meeting the retry loop.
The in-process seen set is the shape of the fix, not a production store: it dies with the process, is not shared across replicas, and the guard-then-charge is not atomic. In production the key rides to a service that dedupes it — or the effect and its record commit in one transaction. The exercise is the guard; the durable store behind it is Chapter 26’s problem.
Worked solution with tests: code/answers/ch19_idempotent_retry.py.
🥇 Gold — combine all three in one graph
The chapter kept the patterns in separate demos for clarity. Build one graph that uses all three: a fetch node with a RetryPolicy for transient blips, followed by a web node that degrades gracefully when it times out, followed by a critical parse node that catches a permanent error and routes to a fallback.
Feed it an input that trips the transient retry and the graceful degradation but not the fatal parse, and show the run completing with a degraded answer. Then flip one input so parse fails and show the same graph taking the fallback branch instead.
Then a third input, the one neither of those covers: an outage the retry cannot fix. Make fetch fail on every attempt and watch what leaves the graph — the third attempt’s ConnectionError, out of invoke, with no fallback answer behind it. That is the right outcome, and it is worth seeing once: the fallback edge handles a fault parse caught, and an exhausted retry is one nobody caught. Turning it into a status is the job of whatever owns the call (Chapter 22’s handler does exactly that), not of a node that swallows the exception and, with it, cancels the retry.
The fetch → web → parse order is chosen so one run touches all three mechanisms — not because it is the right production shape. It pays for the web enrichment before the fatal parse check, so a doomed request still spends on the web call; a real graph would validate first (fetch → parse → web) and fall back before enriching.
A production graph wears all three at once, one per node, each matched to the kind of failure that node can have.
Worked solution with tests: code/answers/ch19_combined_recovery.py.

