Error handlers, recovery and graceful degradation
Overview
In the previous lesson, you learned how LangGraph uses retry policies, exponential backoff, and timeouts to recover from temporary dependency failures.
However, retries cannot solve every problem.
An external API may remain unavailable for hours. A payment may be rejected permanently. A document retrieval service may stop responding during an important customer interaction. A workflow may successfully reserve inventory but fail to arrange delivery.
What should happen when another attempt is unlikely to help?
A production workflow needs explicit recovery strategies. It must decide whether to reverse completed operations, continue with reduced functionality, pause for human assistance, or terminate with a clearly classified failure.
These decisions belong to the workflow architecture rather than being scattered across unrelated exception-handling blocks.
LangGraph provides several mechanisms for implementing recovery:
- Node-level error handlers for failures that cannot be retried further.
Commandfor updating state and redirecting execution.- Checkpointers for preserving execution progress.
interrupt()for requesting human intervention.- Ordinary Python exception handling for application-specific decisions.
The objective is not to prevent every exception. It is to ensure that failures produce predictable, safe, and understandable outcomes.
Environment setup
Node-level error handlers require LangGraph 1.2 or newer within the 1.x series.
pip install -U "langgraph>=1.2,<2.0"Use Python 3.11 or newer.
All examples simulate external services locally, so no model API keys, database servers, or paid service accounts are required. The API usage has been checked against the current official documentation and reference, but the examples have not been execution-tested in the authoring environment.
Error handlers
What is a node-level error handler?
An error handler is a recovery function associated with a particular graph node.
Register it using the error_handler argument of StateGraph.add_node().
Unlike a try/except block inside a node, a node-level handler runs after the runtime determines that the failure will not receive another retry.
The handler therefore separates execution logic from terminal failure recovery.
This diagram illustrates how retries and error handlers cooperate.
A configured handler may execute after the final permitted attempt, immediately after a non-retryable exception, or after the first failure when no retry policy exists.
Timeout failures also participate in this process through NodeTimeoutError.
Understanding NodeError
Import the failure-context type from langgraph.errors:
from langgraph.errors import NodeErrorLangGraph injects this object when the handler declares a parameter annotated with NodeError.
| Attribute | Meaning |
|---|---|
error.node |
Name of the node that failed |
error.error |
Exception responsible for the failure |
The handler receives the current graph state, including previously committed information.
It can return a state-update dictionary or a Command containing updates and routing instructions.
Do not assume that local variables or attempted state updates from the failed execution are available. Information needed for compensation should be recorded in earlier successful steps or recoverable from external systems.
Example: Recovering from an unavailable pricing API
Consider a product assistant that retrieves live prices. If its pricing service remains unavailable, it should return a clearly identified failure response rather than inventing a price.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, RetryPolicy
from langgraph.errors import NodeError
from langgraph.runtime import Runtime
class State(TypedDict, total=False):
product_id: str
status: str
price: float | None
failed_node: str
error_code: str
response: str
class PricingUnavailable(Exception):
pass
def fetch_price(state: State, runtime: Runtime) -> dict:
print(f"Pricing attempt {runtime.execution_info.node_attempt}")
raise PricingUnavailable("Pricing API unavailable")
def handle_pricing_failure(
state: State,
error: NodeError,
) -> Command[Literal["fallback"]]:
if not isinstance(error.error, PricingUnavailable):
raise error.error
print(f"Handling failure from {error.node}")
return Command(
update={
"status": "degraded",
"price": None,
"failed_node": error.node,
"error_code": "PRICING_UNAVAILABLE",
},
goto="fallback",
)
def fallback(state: State) -> dict:
return {
"response": (
"Product information is available, "
"but live pricing cannot currently be retrieved."
)
}
builder = StateGraph(State)
builder.add_node(
"fetch_price",
fetch_price,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
jitter=False,
retry_on=PricingUnavailable,
),
error_handler=handle_pricing_failure,
)
builder.add_node("fallback", fallback)
builder.add_edge(START, "fetch_price")
builder.add_edge("fallback", END)
graph = builder.compile()
result = graph.invoke({"product_id": "SKU-101"})
print(result["status"])
print(result["response"])Expected application output:
Pricing attempt 1
Pricing attempt 2
Pricing attempt 3
Handling failure from fetch_price
degraded
Product information is available, but live pricing cannot currently be retrieved.The original node fails three times. The handler records structured failure information and schedules the fallback node.
There is no unconditional edge from fetch_price to fallback. The fallback is activated by the handler, not by ordinary successful execution.
Graph-wide default handlers
Use builder.set_node_defaults(error_handler=handler) when multiple nodes share a standard failure policy.
For example, a background document-processing workflow might use a default handler that records a failed job status whenever an unrecoverable processing error occurs.
An individual node can override the default through its own error_handler argument.
Important runtime behavior:
- Graph-wide retry and timeout defaults also apply to error-handler nodes.
- Error-handler nodes do not inherit another error handler or a cache policy.
- An exhausted handler failure propagates instead of recursively invoking another handler.
- Defaults are resolved at compilation and are not inherited automatically by independently configured subgraphs.
A default handler should not indiscriminately suppress unexpected exceptions.
Compensation: The saga pattern
Why database rollback is insufficient
A traditional SQL transaction can often roll back several related changes inside a single database.
Distributed workflows are different.
Consider an order-processing agent that performs three operations:
- Reserves inventory through a warehouse API.
- Authorizes payment through a payment service.
- Books delivery through a logistics provider.
These services have separate databases and transaction boundaries. If delivery booking fails, rolling back a local database transaction cannot undo the completed inventory reservation or payment authorization.
The saga pattern addresses this problem by organizing a distributed business process into independently completed operations and corresponding compensating actions.
| Forward operation | Compensating operation |
|---|---|
| Reserve inventory | Release inventory |
| Authorize payment | Void authorization |
| Capture payment | Issue refund |
| Book shipment | Cancel shipment |
| Provision resource | Deprovision resource |
| Create reservation | Cancel reservation |
Compensation is a new business operation, not a reversal of execution history.
It may incur costs, require permission, or fail independently.
Designing compensation order
Compensation typically executes in reverse dependency order.
If inventory is reserved first and payment authorized second, a subsequent failure can require voiding the payment authorization before releasing inventory.
The following diagram shows an order saga with a delivery failure recovery branch.
The compensation path should depend on what actually completed, not merely on which operation was attempted.
Example: Compensating a failed order workflow
This example simulates warehouse and payment services using Python sets. Delivery always fails before creating a shipment.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, RetryPolicy
from langgraph.errors import NodeError
from langgraph.checkpoint.memory import InMemorySaver
class OrderState(TypedDict, total=False):
order_id: str
inventory_reserved: bool
payment_authorized: bool
status: str
error_code: str
class DeliveryUnavailable(Exception):
pass
reservations: set[str] = set()
authorizations: set[str] = set()
def reserve_inventory(state: OrderState) -> dict:
reservations.add(state["order_id"])
print("Inventory reserved")
return {
"inventory_reserved": True,
"status": "reserved",
}
def authorize_payment(state: OrderState) -> dict:
authorizations.add(state["order_id"])
print("Payment authorized")
return {
"payment_authorized": True,
"status": "authorized",
}
def book_delivery(
state: OrderState,
) -> Command[Literal["__end__"]]:
print("Attempting delivery booking")
raise DeliveryUnavailable("Delivery provider unavailable")
def delivery_error_handler(
state: OrderState,
error: NodeError,
) -> Command[Literal["void_payment"]]:
if not isinstance(error.error, DeliveryUnavailable):
raise error.error
return Command(
update={
"status": "compensating",
"error_code": "DELIVERY_UNAVAILABLE",
},
goto="void_payment",
)
def void_payment(state: OrderState) -> dict:
authorizations.discard(state["order_id"])
print("Payment authorization voided")
return {"payment_authorized": False}
def release_inventory(state: OrderState) -> dict:
reservations.discard(state["order_id"])
print("Inventory released")
return {"inventory_reserved": False}
def cancel_order(state: OrderState) -> dict:
return {"status": "cancelled"}
builder = StateGraph(OrderState)
builder.add_node("reserve_inventory", reserve_inventory)
builder.add_node("authorize_payment", authorize_payment)
builder.add_node(
"book_delivery",
book_delivery,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
jitter=False,
retry_on=DeliveryUnavailable,
),
error_handler=delivery_error_handler,
)
builder.add_node("void_payment", void_payment)
builder.add_node("release_inventory", release_inventory)
builder.add_node("cancel_order", cancel_order)
builder.add_edge(START, "reserve_inventory")
builder.add_edge("reserve_inventory", "authorize_payment")
builder.add_edge("authorize_payment", "book_delivery")
builder.add_edge("void_payment", "release_inventory")
builder.add_edge("release_inventory", "cancel_order")
builder.add_edge("cancel_order", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {
"configurable": {"thread_id": "order-101"},
"recursion_limit": 20,
}
result = graph.invoke(
{"order_id": "ORD-101"},
config,
durability="sync",
)
print(result["status"])
print("Active reservations:", reservations)
print("Active authorizations:", authorizations)
assert result["status"] == "cancelled"
assert not reservations
assert not authorizationsExpected application output:
Inventory reserved
Payment authorized
Attempting delivery booking
Attempting delivery booking
Attempting delivery booking
Payment authorization voided
Inventory released
cancelled
Active reservations: set()
Active authorizations: set()The handler does not attempt to perform the entire compensation sequence itself. Instead, it schedules dedicated compensation nodes.
This creates clearer execution boundaries and allows intermediate recovery progress to be checkpointed.
The demonstration intentionally targets the delivery-failure branch. A complete commercial implementation would also implement successful delivery booking, compensation for payment authorization failure, and recovery from failures inside the compensation operations.
What if compensation fails?
Compensation must be treated as an operation that can itself encounter outages.
For example, a payment service may become unavailable while the workflow attempts to void an authorization.
Do not mark the order as fully cancelled until the required compensating actions have completed or their outcomes have been independently verified.
Useful business statuses include:
compensating: Recovery is underway.compensation_failed: A recovery action remains unsuccessful.manual_review_required: Automated recovery cannot safely proceed.cancelled: Required compensation has completed.
Compensation nodes can have their own retry policies and handlers because they are ordinary graph nodes.
Note: A missing acknowledgement does not prove that an external operation failed. Before compensating or repeating an ambiguous payment or shipment operation, reconcile its actual status with the provider.
Recovery from failures with checkpoints
Understanding checkpoint-based recovery
Retries operate within an active graph execution. Checkpoint-based recovery preserves progress across separate invocations and, with persistent storage, process restarts.
LangGraph saves full state checkpoints at superstep boundaries and records completed task writes within a superstep.
Consequently, a failed branch does not necessarily require recomputing successful sibling branches from the same execution step.
A checkpointer also preserves information needed to continue a recovery path. When a node failure has been recorded and its handler remains unfinished, recovery can resume the handler with the preserved failure context.
Example: Resuming after a dependency outage
This workflow prepares a report successfully but fails when publishing it. After the publishing service becomes available, execution resumes using the original thread.
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import RetryPolicy
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict, total=False):
report_id: str
report: str
published: bool
service = {"available": False}
calls = {
"prepare_report": 0,
"publish_report": 0,
}
def prepare_report(state: State) -> dict:
calls["prepare_report"] += 1
print("Preparing report")
return {"report": "Monthly sales report"}
def publish_report(state: State) -> dict:
calls["publish_report"] += 1
print("Attempting publication")
if not service["available"]:
raise ConnectionError("Publishing service unavailable")
return {"published": True}
builder = StateGraph(State)
builder.add_node("prepare_report", prepare_report)
builder.add_node(
"publish_report",
publish_report,
retry_policy=RetryPolicy(
max_attempts=2,
initial_interval=0.1,
jitter=False,
retry_on=ConnectionError,
),
)
builder.add_edge(START, "prepare_report")
builder.add_edge("prepare_report", "publish_report")
builder.add_edge("publish_report", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {
"configurable": {"thread_id": "report-101"},
"recursion_limit": 20,
}
try:
graph.invoke(
{"report_id": "REP-101"},
config,
durability="sync",
)
except ConnectionError:
print("Publication failed")
snapshot = graph.get_state(config)
print("Saved state:", snapshot.values)
print("Pending nodes:", snapshot.next)
for task in snapshot.tasks:
if task.error:
print("Failed task:", task.name)
service["available"] = True
result = graph.invoke(None, config, durability="sync")
print("Published:", result["published"])
print("Execution counts:", calls)
assert calls["prepare_report"] == 1
assert calls["publish_report"] == 3
assert result["published"] is TrueExpected application output:
Preparing report
Attempting publication
Attempting publication
Publication failed
Saved state: {'report_id': 'REP-101', 'report': 'Monthly sales report'}
Pending nodes: ('publish_report',)
Failed task: publish_report
Attempting publication
Published: True
Execution counts: {'prepare_report': 1, 'publish_report': 3}The report preparation node executes only once. The subsequent invocation resumes unfinished publication work and receives a new execution attempt.
Choosing the correct resume operation
| Operation | Purpose |
|---|---|
graph.invoke(inputs, config) |
Submit new input and start from the graph entry point |
graph.invoke(None, config) |
Continue unfinished execution |
graph.invoke(Command(resume=value), config) |
Supply a response to a pending interrupt |
graph.get_state(config) |
Inspect saved state and pending work |
graph.get_state_history(config) |
Examine historical checkpoints |
graph.update_state(config, values, as_node=...) |
Apply an explicit state update |
Reusing a thread ID with new inputs is not equivalent to resuming a failed execution.
State updates also influence downstream scheduling, particularly when as_node identifies which node should be treated as the update’s source. Operators should not use this mechanism to bypass failed business operations without reconciliation.
Persistence and durability
InMemorySaver is suitable for demonstrations and tests but loses checkpoint data when the process terminates.
Production deployments commonly use PostgresSaver or AsyncPostgresSaver with a durable PostgreSQL database.
Durability modes control checkpoint persistence timing.
| Mode | Behavior |
|---|---|
sync |
Persists progress before subsequent execution steps |
async |
Persists progress concurrently with execution |
exit |
Persists when execution exits |
Synchronous durability is particularly useful when later operations depend on reliably recorded earlier results.
Nevertheless, checkpoints cannot create a distributed transaction with independent external services.
Graceful degradation
Maintaining useful functionality
Graceful degradation means deliberately reducing functionality when the preferred execution path becomes unavailable.
Instead of failing an entire customer interaction because one optional service is offline, an agent may provide whatever information remains reliable.
Typical degradation strategies include:
| Primary capability | Degraded capability |
|---|---|
| Live inventory lookup | Last recorded inventory information |
| Advanced LLM | Smaller model or deterministic response |
| Vector search | Keyword search |
| Personalized recommendations | General recommendations |
| Live order tracking | Previously verified tracking status |
| Automated decision | Human review |
A fallback should preserve essential correctness requirements.
For instance, an unavailable fraud-detection service should not automatically cause a financial transaction to be approved.
This distinction is known as fail-open versus fail-closed behavior. Fail-open allows an operation to proceed despite a dependency failure; fail-closed blocks it until the required verification becomes available.
Select the behavior according to the business risk.
Example: Degrading to a deterministic response
This workflow normally generates a personalized recommendation. During a simulated model outage, it returns a predefined general recommendation.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, RetryPolicy
from langgraph.errors import NodeError
class State(TypedDict, total=False):
category: str
service_available: bool
recommendations: list[str]
mode: str
notice: str
class RecommendationUnavailable(Exception):
pass
def personalize(
state: State,
) -> Command[Literal["__end__"]]:
if not state["service_available"]:
raise RecommendationUnavailable("Model service unavailable")
return Command(
update={
"recommendations": ["Personalized product selection"],
"mode": "normal",
},
goto=END,
)
def handle_failure(
state: State,
error: NodeError,
) -> Command[Literal["general_recommendations"]]:
if not isinstance(error.error, RecommendationUnavailable):
raise error.error
return Command(
update={"mode": "degraded"},
goto="general_recommendations",
)
def general_recommendations(state: State) -> dict:
catalog = {
"electronics": ["USB-C cable", "Laptop stand"],
"books": ["Python fundamentals", "SQL fundamentals"],
}
return {
"recommendations": catalog.get(state["category"], []),
"notice": (
"Personalization is unavailable. "
"Showing general recommendations."
),
}
builder = StateGraph(State)
builder.add_node(
"personalize",
personalize,
retry_policy=RetryPolicy(
max_attempts=2,
initial_interval=0.1,
jitter=False,
retry_on=RecommendationUnavailable,
),
error_handler=handle_failure,
)
builder.add_node(
"general_recommendations",
general_recommendations,
)
builder.add_edge(START, "personalize")
builder.add_edge("general_recommendations", END)
graph = builder.compile()
result = graph.invoke({
"category": "electronics",
"service_available": False,
})
print(result["mode"])
print(result["recommendations"])
print(result["notice"])Expected output:
degraded
['USB-C cable', 'Laptop stand']
Personalization is unavailable. Showing general recommendations.The user receives a useful response without being misled into believing that personalization succeeded.
Keep degraded outcomes explicit in both application state and user-facing responses.
For previously recorded data, retain its verification timestamp and enforce acceptable freshness limits. Stale information should not be used when it could authorize unsafe or incorrect business actions.
Human intervention as a recovery strategy
Some failures require knowledge, permissions, or judgment that automated components do not possess.
LangGraph supports this through interrupt().
The following standalone example pauses after an identity-verification service becomes unavailable and resumes using a human decision.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, RetryPolicy, interrupt
from langgraph.errors import NodeError
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict, total=False):
customer_id: str
status: str
error_code: str
class VerificationUnavailable(Exception):
pass
def verify_customer(state: State) -> dict:
raise VerificationUnavailable("Verification API offline")
def handle_failure(
state: State,
error: NodeError,
) -> Command[Literal["human_review"]]:
if not isinstance(error.error, VerificationUnavailable):
raise error.error
return Command(
update={
"status": "pending_review",
"error_code": "VERIFICATION_UNAVAILABLE",
},
goto="human_review",
)
def human_review(state: State) -> dict:
approved = interrupt({
"customer_id": state["customer_id"],
"reason": state["error_code"],
"request": "Has identity been independently verified?",
})
if not isinstance(approved, bool):
raise ValueError("Expected a boolean review decision")
return {
"status": "verified" if approved else "rejected"
}
builder = StateGraph(State)
builder.add_node(
"verify_customer",
verify_customer,
retry_policy=RetryPolicy(
max_attempts=2,
initial_interval=0.1,
jitter=False,
retry_on=VerificationUnavailable,
),
error_handler=handle_failure,
)
builder.add_node("human_review", human_review)
builder.add_edge(START, "verify_customer")
builder.add_edge("human_review", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {
"configurable": {"thread_id": "verification-101"}
}
paused = graph.invoke(
{"customer_id": "C-101"},
config,
durability="sync",
)
print(paused["status"])
print(paused["__interrupt__"][0].value)
result = graph.invoke(
Command(resume=True),
config,
durability="sync",
)
print(result["status"])Expected application output:
pending_review
{'customer_id': 'C-101', 'reason': 'VERIFICATION_UNAVAILABLE', 'request': 'Has identity been independently verified?'}
verifiedThe interrupt pauses execution rather than raising an ordinary recoverable failure. LangGraph excludes this control-flow mechanism from retry and error-handler processing.
On resume, the interrupted node starts again from its beginning.
In production, the approval must originate from an authenticated, authorized reviewer who has actually completed the required verification. The example simulates that external review.
Where to handle errors
Error handling should occur at the layer that possesses enough information to make the correct recovery decision.
| Handling location | Responsibility |
|---|---|
| API client | Translate transport failures into meaningful exceptions |
| Node implementation | Handle expected application-level conditions |
| Retry policy | Repeat eligible temporary failures |
| Node error handler | Choose a recovery route after terminal node failure |
| Compensation node | Reverse a completed business action |
| Human-review node | Collect an authorized decision |
| Application boundary | Report terminal failure and trigger operational alerts |
Recoverable errors inside agent loops
An LLM may generate invalid tool arguments that can be corrected without repeating the same request.
In a custom agent loop, catch the specific validation failure, provide a sanitized explanation to the model through a corresponding ToolMessage, and route execution back to the model.
Preserve the original tool-call identifier so the response remains associated with the correct tool invocation.
This is different from a retry policy: the model must change its proposed action rather than repeat identical invalid arguments.
Unexpected programming errors
A TypeError, unexpected schema mismatch, or broken invariant may indicate defective application code.
Avoid treating every exception as a dependency outage.
Overly broad recovery can hide defects, produce misleading results, and prevent monitoring systems from detecting serious problems.
Handlers should explicitly recognize recoverable exceptions and propagate failures they cannot safely classify.
Common mistakes and production practices
Mixing normal and recovery routing: Command adds routing instructions rather than universally replacing static edges. Use deliberate routing so a recovery branch does not accidentally coexist with an inappropriate normal branch.
Performing all compensation inside one handler: Separate important recovery actions into individual nodes so their progress can be observed and checkpointed independently.
Confusing workflow completion with business success: A graph can reach END with a cancelled, rejected, or degraded outcome. Inspect the business status.
Retrying unsafe compensation blindly: Compensating operations can also produce duplicate external effects and require appropriate deduplication.
Storing sensitive exceptions in state: Prefer structured error codes and sanitized metadata. Keep protected diagnostic details in appropriately secured logs.
Creating unbounded recovery cycles: A fallback that repeatedly routes back to the failing primary node can create endless execution. Establish explicit recovery budgets.
Tip: Test business invariants as well as returned responses. A compensated order should have no unreleased inventory or unintended payment authorization, not merely a status field containing
cancelled.
Observability and recovery testing
Record the failing node, exception category, recovery destination, compensation progress, degradation mode, thread identifier, and terminal business status.
Inject temporary outages, permanent failures, compensation failures, unexpected exceptions, and interrupted human reviews into automated tests.
Also test repeated recovery attempts. A recovery mechanism that succeeds once but duplicates business actions after a restart is not reliably fault-tolerant.
Official API references
- LangGraph fault tolerance
- NodeError API reference
- Graph-wide node defaults
- LangGraph checkpointers
- LangGraph interrupts
- LangGraph Command and control flow
Connection to durable execution
This lesson adds explicit recovery paths to the retry-protected workflows introduced earlier in the chapter.
However, retries, compensation, checkpoint recovery, and human interrupts share an important characteristic: they can cause application code to execute more than once.
A process can fail after an external operation succeeds but before its result is checkpointed. A compensation operation can complete without returning its acknowledgement. A paused node can execute its earlier instructions again when resumed.
In the next lesson, Durable execution, idempotency and duplicate side effects, you will examine these failure windows in depth and learn how to combine stable operation identifiers, idempotent APIs, durable execution boundaries, and deduplication mechanisms to preserve business correctness across repeated execution.
Build a recoverable order tracking workflow
Build an order tracking agent that retries temporary failures from its primary tracking API before activating a recovery path. When retries are exhausted, use a previously recorded tracking status if one exists or pause for human assistance otherwise. Preserve failure information in state and verify that unexpected programming errors are not silently converted into successful responses.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, RetryPolicy, interrupt
from langgraph.errors import NodeError
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.runtime import Runtime
class TrackingState(TypedDict, total=False):
order_id: str
scenario: str
cached_status: str | None
tracking_status: str
mode: str
failed_node: str
error_code: str
response: str
class TrackingUnavailable(Exception):
pass
def fetch_tracking(
state: TrackingState,
runtime: Runtime,
) -> dict:
print(f"API attempt {runtime.execution_info.node_attempt}")
if state["scenario"] == "outage":
raise TrackingUnavailable("Tracking service unavailable")
if state["scenario"] == "bug":
raise TypeError("Unexpected response structure")
return {
"tracking_status": "Out for delivery",
"mode": "normal",
}
# TODO: Implement a typed error handler.
# Recover only from TrackingUnavailable.
# Route to fallback when cached_status exists.
# Otherwise route to human_review.
# TODO: Implement a fallback node.
# Clearly identify the tracking information as unverified.
# TODO: Implement a human_review node using interrupt().
# Accept a manually verified tracking status.
# TODO: Compile the graph with InMemorySaver.
# Configure three total attempts for fetch_tracking.
# TODO: Test normal execution, cached fallback,
# human intervention, and unexpected programming errors.from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, RetryPolicy, interrupt
from langgraph.errors import NodeError
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.runtime import Runtime
class TrackingState(TypedDict, total=False):
order_id: str
scenario: str
cached_status: str | None
tracking_status: str
mode: str
failed_node: str
error_code: str
response: str
class TrackingUnavailable(Exception):
pass
def fetch_tracking(
state: TrackingState,
runtime: Runtime,
) -> Command[Literal["finalize"]]:
print(f"API attempt {runtime.execution_info.node_attempt}")
if state["scenario"] == "outage":
raise TrackingUnavailable("Tracking service unavailable")
if state["scenario"] == "bug":
raise TypeError("Unexpected response structure")
return Command(
update={
"tracking_status": "Out for delivery",
"mode": "normal",
},
goto="finalize",
)
def tracking_error_handler(
state: TrackingState,
error: NodeError,
) -> Command[Literal["fallback", "human_review"]]:
if not isinstance(error.error, TrackingUnavailable):
raise error.error
destination = (
"fallback"
if state.get("cached_status")
else "human_review"
)
return Command(
update={
"failed_node": error.node,
"error_code": "TRACKING_UNAVAILABLE",
"mode": "recovering",
},
goto=destination,
)
def fallback(state: TrackingState) -> dict:
return {
"tracking_status": state["cached_status"],
"mode": "degraded",
}
def human_review(state: TrackingState) -> dict:
decision = interrupt({
"order_id": state["order_id"],
"reason": state["error_code"],
"request": "Provide a verified tracking status",
})
status = decision["verified_status"]
if not isinstance(status, str) or not status.strip():
raise ValueError("A verified status is required")
return {
"tracking_status": status.strip(),
"mode": "manual",
}
def finalize(state: TrackingState) -> dict:
status = state["tracking_status"]
if state["mode"] == "degraded":
response = (
f"Last recorded status: {status}. "
"Live tracking is currently unavailable."
)
elif state["mode"] == "manual":
response = f"Manually verified status: {status}."
else:
response = f"Current tracking status: {status}."
return {"response": response}
builder = StateGraph(TrackingState)
builder.add_node(
"fetch_tracking",
fetch_tracking,
retry_policy=RetryPolicy(
max_attempts=3,
initial_interval=0.1,
backoff_factor=2.0,
jitter=False,
retry_on=TrackingUnavailable,
),
error_handler=tracking_error_handler,
)
builder.add_node("fallback", fallback)
builder.add_node("human_review", human_review)
builder.add_node("finalize", finalize)
builder.add_edge(START, "fetch_tracking")
builder.add_edge("fallback", "finalize")
builder.add_edge("human_review", "finalize")
builder.add_edge("finalize", END)
graph = builder.compile(checkpointer=InMemorySaver())
def config(thread_id: str) -> dict:
return {
"configurable": {"thread_id": thread_id},
"recursion_limit": 20,
}
normal = graph.invoke(
{
"order_id": "ORD-101",
"scenario": "normal",
"cached_status": None,
},
config("tracking-normal"),
durability="sync",
)
assert normal["mode"] == "normal"
print(normal["response"])
degraded = graph.invoke(
{
"order_id": "ORD-102",
"scenario": "outage",
"cached_status": "In transit",
},
config("tracking-degraded"),
durability="sync",
)
assert degraded["mode"] == "degraded"
assert degraded["failed_node"] == "fetch_tracking"
print(degraded["response"])
manual_config = config("tracking-manual")
paused = graph.invoke(
{
"order_id": "ORD-103",
"scenario": "outage",
"cached_status": None,
},
manual_config,
durability="sync",
)
assert paused["__interrupt__"]
print(paused["__interrupt__"][0].value)
resumed = graph.invoke(
Command(resume={
"verified_status": "Arrived at distribution center"
}),
manual_config,
durability="sync",
)
assert resumed["mode"] == "manual"
print(resumed["response"])
try:
graph.invoke(
{
"order_id": "ORD-104",
"scenario": "bug",
"cached_status": "In transit",
},
config("tracking-bug"),
)
except TypeError:
print("Unexpected programming error propagated")
else:
raise AssertionError("Programming error was swallowed")Summary
- Node-level error handlers execute when a failed node cannot be retried further and can redirect execution into explicit recovery branches.
- NodeError exposes the failing node and its exception so that recovery decisions can distinguish expected failures from unexpected bugs.
- The saga pattern compensates completed business operations when a later operation prevents the workflow from finishing successfully.
- Checkpointers preserve execution progress and allow unfinished work to resume without unnecessarily repeating completed graph steps.
- Graceful degradation provides reduced but trustworthy functionality when primary dependencies remain unavailable.
- Human intervention through interrupt allows a workflow to pause when automated recovery cannot safely resolve a failure.
- Recovery logic should be selective, bounded, observable, and protected against duplicate external side effects.