Durable Execution, Errors, Testing and Cost
Production LangGraph means runs that survive crashes, flaky APIs and runaway loops, and that you can test and evaluate cheaply. Know when checkpoints are written (durability modes), what re-runs on resume or retry, how RetryPolicy, timeouts, error handlers and node caching behave in 1.2, how the recursion limit works, and how to test graphs with fakes, partial execution and evaluations.
Key points
- 1
Durable execution: checkpoints are saved at super-step boundaries, never mid-function. On resume (or a retry) the affected node runs again from its first line, so side effects inside nodes must be idempotent: idempotency keys, upserts, read-before-write.
- 2
Durability modes are passed per run (
invoke(..., durability=...)):"exit"saves only when the run exits (success, error or interrupt), which is fastest but loses progress if the process dies;"async"(default) saves each step in the background;"sync"saves each step before the next starts.checkpoint_during=True/Falseis deprecated and maps toasync/exit. - 3
Functional API and
@task: on resume the entrypoint replays from the top and completed task results are restored from the checkpoint. A task that raised or never finished runs again, so task bodies with side effects still need idempotency. Put non-deterministic values (time, random) inside tasks. - 4
RetryPolicydefaults:max_attempts=3(including the first try),initial_interval=0.5,backoff_factor=2.0,max_interval=128,jitter=True(adds a random amount up to 1 s),retry_on=default_retry_on.retry_policycan also be a list of policies; the first one whoseretry_onmatches is used. - 5
default_retry_onretries any exception exceptValueError,TypeError,ArithmeticError,ImportError,LookupError,NameError,SyntaxError,RuntimeError,ReferenceError,StopIteration,StopAsyncIteration,OSErrorand their subclasses. Built-inConnectionErroris explicitly retried.httpx/requestsHTTP errors are retried only for 5xx, so 429 needs a customretry_on. - 6
Timeouts (1.2+):
add_node(..., timeout=60 | timedelta | TimeoutPolicy(run_timeout, idle_timeout, refresh_on))works for async nodes only; sync nodes with a timeout are rejected at compile time.NodeTimeoutErroris retryable by default, the clock resets per attempt, and a timed-out attempt's writes are discarded. Withrefresh_on="heartbeat"onlyruntime.heartbeat()resets the idle clock. - 7
Error handlers (1.2+):
add_node(..., error_handler=fn)runs after retries are exhausted (or immediately if none apply), receiveserror: NodeError(node,error), and returns an update or aCommand(goto=...). A plain update ends the run there; route onward withCommand.interrupt()bypasses retries and handlers.set_node_defaults(...)sets graph-wide defaults; per-node values win, and subgraphs do not inherit them. - 8
Node caching:
cache_policy=CachePolicy(key_func=..., ttl=...)on the node pluscache=InMemoryCache()(orSqliteCache) oncompile(). The default key hashes the whole node input, andttl=Nonenever expires. Hits show'__metadata__': {'cached': True}inupdatesmode. The cache is shared across threads;graph.clear_cache()empties it. - 9
recursion_limitis a top-level config key that caps super-steps per run. Exceeding it raisesGraphRecursionError(aRecursionError). With a checkpointer, the progress up to the limit is saved and can be resumed withinvoke(None, config)and a higher limit.RemainingSteps(andIsLastStep) managed values let routers wind down before the limit;config["metadata"]["langgraph_step"]gives the current step. - 10
Graceful shutdown (1.2+): pass
control=RunControl()toinvoke/stream, callrequest_drain(reason)(for example on SIGTERM); the run stops at the next super-step boundary, raisesGraphDrained, and resumes withinvoke(None, config). Nodes can checkruntime.drain_requested.runtime.execution_info.node_attempt(1-indexed) lets a node switch to a fallback on retries. - 11
Testing: build and compile the graph per test with a fresh
InMemorySaver; test one node withcompiled.nodes["name"].invoke(state)(bypasses the checkpointer); test a section withupdate_state(cfg, values, as_node=<previous node>)theninvoke(None, cfg, interrupt_after=<last node>); script models withGenericFakeChatModel; useAsyncMockfor awaited dependencies; keep live-LLM tests behind a pytest marker and assert on structure. - 12
Evaluation and cost: a compiled graph is a runnable you can pass to LangSmith
evaluate/aevaluate; evaluate trajectories or intermediate steps from the output state, single nodes viaapp.nodes[...], and usenum_repetitionsfor noisy agents. Cut latency by fanning out independent work withSend, using smaller models for routing, caching repeated deterministic nodes, and never blocking the event loop inside async nodes.
Common traps
Assuming resume continues from the failing line: the whole node re-runs, so a charge, email or insert before the failure can happen twice.
Expecting
durability="sync"to prevent duplicate side effects: it only controls when checkpoints are written between steps.Setting
cache_policywithout passingcache=tocompile(): nothing is ever cached.Assuming
RetryPolicy()retries everything:ValueError,KeyError, built-inTimeoutError,requestsconnection errors (they areOSErrors) and HTTP 429 are not retried by default.Returning a plain dict from an
error_handlerand expecting the node's normal edges to run next: the run ends unless the handler returnsCommand(goto=...).A custom cache
key_functhat leaves out the tenant or another input the output depends on: the cache is shared across threads, so results leak between users.Running two
invokecalls on the samethread_idat once: both start from the same checkpoint and one update is lost. Serialise runs per thread.Calling blocking I/O (
time.sleep,requests) inside async nodes: parallel branches run one after another and node timeouts cannot cancel the work.
Read the source
Further reading
Suggest a resourceNo extra reading for Durable Execution, Errors, Testing and Cost yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Durable Execution, Errors, Testing and Cost
Ten questions, with the answer and explanation after each one.