Durable execution, idempotency and duplicate side effects
Overview
Imagine an agentic order-processing workflow that performs the following operations:
- Validates a customer’s order.
- Calculates the final purchase amount.
- Charges the customer’s payment method.
- Creates an invoice.
- Sends an order confirmation.
- Updates the order status.
The payment provider successfully charges the customer. However, before the workflow records the payment receipt, the Python process crashes.
When the application restarts, should it charge the customer again?
Clearly not. But how can the workflow know whether the previous payment succeeded if its most recent saved state does not contain the payment receipt?
This is one of the fundamental challenges of reliable distributed systems and production agentic AI engineering.
Durable execution allows a workflow to preserve its progress and recover from failures without unnecessarily repeating completed work.
Idempotency ensures that when an operation must be attempted again, repeating it does not create an unintended additional business effect.
These mechanisms complement each other:
- Durable execution reduces unnecessary re-execution.
- Idempotency makes necessary re-execution safe.
- Reconciliation resolves uncertainty about operations that may already have succeeded.
In the previous lesson, you learned how error handlers, recovery branches, and graceful degradation keep workflows operational when individual components fail. Here, we address a different failure category: situations where the entire execution process stops or an external operation succeeds without returning an acknowledgment.
A production workflow must handle both.
Environment setup
Install LangGraph 1.x and the SQLite checkpoint integration:
pip install -U "langgraph>=1.0,<2.0" langgraph-checkpoint-sqliteThe examples intentionally use simulated external services instead of real payment systems or language models. This makes failure injection deterministic, avoids API costs, and allows you to focus on reliability guarantees.
The APIs follow the current LangGraph 1.x documentation. The examples have not been runtime-tested in the authoring environment because the required packages were unavailable; the outputs below describe the expected behavior.
How durable execution works
A normal Python function stores intermediate execution information in memory. Local variables, function frames, and unfinished operations disappear when the process terminates.
LangGraph introduces a different execution model.
When a graph is compiled with a checkpointer, the runtime records recoverable execution information at graph boundaries. A checkpoint contains sufficient information to reconstruct the graph’s logical progress.
Conceptually, this includes:
- Current graph state.
- State channel values and versions.
- Execution scheduling information.
- Checkpoint identity and metadata.
- Information about unfinished work.
Each checkpoint belongs to a thread, identified through thread_id.
A thread represents an execution history that can survive multiple invocations.
Understanding super-steps
LangGraph uses a super-step execution model derived from Pregel.
During a super-step, eligible nodes execute using the state available at that boundary. Their updates are collected and applied according to the state’s reducer rules.
A sequential graph generally advances through successive node boundaries. Parallel branches can execute several nodes within the same super-step.
The following diagram illustrates how execution progress becomes recoverable.
Checkpointing is not equivalent to saving the Python interpreter’s instruction pointer. Recovery reconstructs graph execution from saved information rather than restoring arbitrary local variables.
Example: Recovering an unfinished node
This example demonstrates that a successful preparation node is not repeated when a downstream node fails.
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict):
order_id: str
validated: NotRequired[bool]
status: NotRequired[str]
attempts = {"process": 0}
def validate(state: State):
print("Validating order")
return {"validated": True}
def process(state: State):
attempts["process"] += 1
print("Processing attempt:", attempts["process"])
if attempts["process"] == 1:
raise RuntimeError("Simulated API failure")
return {"status": "completed"}
builder = StateGraph(State)
builder.add_node("validate", validate)
builder.add_node("process", process)
builder.add_edge(START, "validate")
builder.add_edge("validate", "process")
builder.add_edge("process", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {
"configurable": {"thread_id": "order-101"}
}
try:
graph.invoke(
{"order_id": "ORD-101"},
config,
durability="sync",
)
except RuntimeError as exc:
print("Execution failed:", exc)
snapshot = graph.get_state(config)
print("Saved state:", snapshot.values)
print("Pending nodes:", snapshot.next)
result = graph.invoke(
None,
config,
durability="sync",
)
print("Final result:", result)Expected output:
Validating order
Processing attempt: 1
Execution failed: Simulated API failure
Saved state: {'order_id': 'ORD-101', 'validated': True}
Pending nodes: ('process',)
Processing attempt: 2
Final result: {'order_id': 'ORD-101', 'validated': True, 'status': 'completed'}Notice that validate executes only once.
The validation result was recorded before the processing node failed. Resuming the thread allows LangGraph to recover the unfinished execution instead of submitting a completely new workflow input.
Note:
InMemorySaverdemonstrates checkpoint semantics but cannot survive process termination because its checkpoints exist only in RAM. Use a persistent backend for restart recovery.
Pending writes and parallel execution
Consider a super-step containing three independent nodes:
- Fetch customer information.
- Fetch inventory information.
- Fetch shipping information.
If the first two finish successfully but the third fails, their successful writes can be preserved as pending writes associated with that super-step.
During recovery, LangGraph can reuse those saved results and execute the unfinished shipping operation rather than repeating the entire parallel batch.
This optimization depends on the relevant writes having reached the checkpointer.
It reduces duplicated computation but does not eliminate the requirement for idempotent external operations.
For more information about checkpoint internals, see the LangGraph checkpointer documentation.
Durability modes
Durability involves a trade-off between checkpoint consistency, execution latency, and storage overhead.
LangGraph supports three durability modes, selected when invoking or streaming a workflow.
| Mode | Persistence timing | Performance | Crash recovery |
|---|---|---|---|
exit |
When execution exits | Highest | Limited during execution |
async |
Concurrently with subsequent execution | High | Recent progress may be lost |
sync |
Before advancing to the next step | Lower | Strongest checkpoint consistency |
Exit durability
With durability="exit", intermediate progress is not continuously persisted to the backend.
Persistence occurs when execution exits normally, through a handled execution failure, or through an interrupt, assuming the runtime successfully completes its persistence work.
This mode is useful for short, inexpensive, repeatable computations.
However, if a worker is abruptly terminated during execution, recent progress may be unavailable. A new thread might not have any persisted checkpoint at all.
Asynchronous durability
With durability="async", checkpoint persistence can overlap with subsequent graph execution.
This is the default durability mode and provides a practical balance for many workflows.
For example, while the database persists a completed document-retrieval step, the next node may begin generating a response.
The trade-off is that an abrupt process failure can occur before an outstanding checkpoint write finishes.
Synchronous durability
With durability="sync", the runtime waits for checkpoint persistence before advancing to subsequent graph steps.
This makes it particularly useful for:
- Billing workflows.
- Order fulfillment.
- Long-running business processes.
- Expensive document-processing pipelines.
- Workflows involving irreversible external changes.
For a new thread, synchronous durability also ensures that the initial execution checkpoints are persisted before the first user node runs.
A failure before the initial checkpoint exists still requires recovery from an independently persisted request or job record.
Most importantly, synchronous durability protects graph progress, not arbitrary external transactions. A payment provider and a checkpoint database usually commit independently.
The re-execution model
A crucial engineering distinction is that recovery does not continue from the exact Python statement where execution stopped.
Suppose a node performs these operations:
Read order information
Charge customer
Create invoice
Return state updateIf the process fails after charging the customer but before returning its state update, the node may run again from its beginning.
Without additional safeguards, the customer could be charged twice.
This behavior also matters when using automatic retries or human-in-the-loop interruptions.
Different ways to continue a thread
| Invocation | Purpose |
|---|---|
graph.invoke(inputs, config) |
Submit new input |
graph.invoke(None, config) |
Recover unfinished execution |
graph.invoke(Command(resume=value), config) |
Answer a dynamic interrupt |
graph.invoke(None, snapshot.config) |
Replay from a historical checkpoint |
For ordinary failure recovery, use the original thread ID and omit a historical checkpoint_id.
Submitting the original input again is not equivalent to resuming unfinished execution. It can initiate new work through the graph’s entry point.
Historical replay is similarly different: it intentionally re-executes work after a selected checkpoint.
Deterministic replay
Deterministic replay requires execution decisions to remain consistent when a workflow reconstructs previous progress.
Potential sources of nondeterminism include:
- Randomly generated identifiers.
- Current timestamps.
- Changing database queries.
- External API responses.
- Language model outputs.
For example, generating a new UUID each time a payment node runs produces a different operation identity during recovery.
Instead, derive the identity from stable business information or generate it in an earlier checkpointed step.
Persist significant decisions such as the approved purchase amount, selected recipient, generated document identifier, or requested action before performing irreversible operations.
Idempotent operations
An operation is idempotent when applying the same logical operation multiple times produces the same intended business effect as applying it once.
For example:
| Operation | Naturally idempotent? |
|---|---|
Set order status to completed |
Generally yes |
| Increment account balance by $100 | No |
| Replace a document with identical content | Generally yes |
| Append a new audit record | No |
| Create an invoice using a unique operation ID | Yes, if enforced |
| Send an email | Usually no |
Idempotency concerns business outcomes rather than the number of function calls.
A payment function may execute three times while producing only one successful charge.
Idempotency keys
An idempotency key identifies one logical business operation.
For example:
payment:ORD-101:v1
invoice:ORD-101:v1
shipment:ORD-101:v1These identifiers distinguish payment creation from invoice creation and shipment creation.
In production, include appropriate tenant or account scope. If the same order can legitimately receive multiple payments, include a stable payment-operation identifier rather than relying exclusively on the order ID.
A repeated request must reuse the original key and the original operation parameters.
Many external APIs support idempotency keys through a request header or request field. The exact contract, retention period, concurrency behavior, and payload matching rules depend on the provider.
Never assume that an arbitrary API supports idempotency simply because you supply a header.
The ambiguous success problem
The most dangerous failure occurs when an external operation succeeds but its acknowledgment never reaches the workflow.
The following diagram illustrates this failure window.
The absence of a payment receipt in graph state does not prove that the payment failed.
It means the result is unknown.
A safe recovery strategy must retrieve the existing result, repeat the request using a provider-enforced idempotency key, or reconcile the operation before taking further action.
Example: Surviving an actual process crash
This example uses two SQLite databases:
checkpoints.dbstores LangGraph execution progress.payments.dbsimulates an independent payment service.
A unique database constraint protects the payment operation. The workflow deliberately terminates after the payment transaction commits but before the node returns.
Save the following as durable_payment.py in a new working directory.
import os
import sys
import sqlite3
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.sqlite import SqliteSaver
class PaymentState(TypedDict):
order_id: str
amount_cents: int
operation_id: NotRequired[str]
payment_id: NotRequired[str]
def payment_provider(operation_id, amount_cents):
db = sqlite3.connect("payments.db")
try:
db.execute("""
CREATE TABLE IF NOT EXISTS payments (
operation_id TEXT PRIMARY KEY,
payment_id TEXT NOT NULL,
amount_cents INTEGER NOT NULL
)
""")
db.execute(
"""
INSERT INTO payments VALUES (?, ?, ?)
ON CONFLICT(operation_id) DO NOTHING
""",
(
operation_id,
f"PAY-{operation_id}",
amount_cents,
),
)
payment_id, saved_amount = db.execute(
"""
SELECT payment_id, amount_cents
FROM payments WHERE operation_id = ?
""",
(operation_id,),
).fetchone()
if saved_amount != amount_cents:
raise ValueError("Operation payload mismatch")
db.commit()
return payment_id
finally:
db.close()
def prepare(state: PaymentState):
return {
"operation_id": f"payment:{state['order_id']}:v1"
}
def build_graph(saver, simulate_crash):
def charge(state: PaymentState):
payment_id = payment_provider(
state["operation_id"],
state["amount_cents"],
)
print("Provider returned:", payment_id, flush=True)
if simulate_crash:
print("Simulating process crash", flush=True)
os._exit(17)
return {"payment_id": payment_id}
builder = StateGraph(PaymentState)
builder.add_node("prepare", prepare)
builder.add_node("charge", charge)
builder.add_edge(START, "prepare")
builder.add_edge("prepare", "charge")
builder.add_edge("charge", END)
return builder.compile(checkpointer=saver)
def main():
if len(sys.argv) != 2 or sys.argv[1] not in {
"start", "resume"
}:
raise SystemExit(
"Usage: python durable_payment.py start|resume"
)
mode = sys.argv[1]
config = {
"configurable": {"thread_id": "payment-workflow-101"}
}
with SqliteSaver.from_conn_string(
"checkpoints.db"
) as saver:
graph = build_graph(
saver,
simulate_crash=(mode == "start"),
)
if mode == "start":
graph.invoke(
{
"order_id": "ORD-101",
"amount_cents": 25000,
},
config,
durability="sync",
)
else:
print("Pending nodes:", graph.get_state(config).next)
result = graph.invoke(
None,
config,
durability="sync",
)
print("Recovered state:", result)
db = sqlite3.connect("payments.db")
try:
count = db.execute(
"SELECT COUNT(*) FROM payments"
).fetchone()[0]
finally:
db.close()
print("Total payment records:", count)
assert count == 1
if __name__ == "__main__":
main()Execute the first process:
python durable_payment.py startExpected output:
Provider returned: PAY-payment:ORD-101:v1
Simulating process crashThe process terminates with exit code 17. The payment record already exists.
Start a separate process to recover the workflow:
python durable_payment.py resumeExpected output:
Pending nodes: ('charge',)
Provider returned: PAY-payment:ORD-101:v1
Recovered state: {'order_id': 'ORD-101', 'amount_cents': 25000, 'operation_id': 'payment:ORD-101:v1', 'payment_id': 'PAY-payment:ORD-101:v1'}
Total payment records: 1The payment node executes again, but the database prevents a second payment record.
Three properties make this design reliable:
- The operation identity is stable.
- The payment service enforces uniqueness atomically.
- Repeated requests recover the original operation result.
The database constraint is more reliable than performing an unprotected SELECT followed by an INSERT. Two concurrent workers could both observe that no record exists and independently create duplicate operations.
This example models a provider-side idempotency guarantee. It does not imply that storing a payment record locally automatically makes a separate real payment API idempotent.
Preventing duplicate side effects: a checklist
Apply the following checklist whenever a graph node performs externally visible work.
1. Identify every side effect
Include database writes, emails, webhook deliveries, payments, file creation, infrastructure changes, and agent tool calls.
Even an apparently read-only LLM request may consume money and return a different result when repeated.
2. Establish a stable operation identity
Generate identifiers from immutable business intent.
Avoid generating a fresh UUID inside an operation that may be replayed unless the identifier itself is safely persisted before the effect occurs.
A thread_id identifies a workflow history; it does not necessarily identify an individual business operation.
3. Persist intent before execution
Record the approved operation, its parameters, and its identity before calling the external system.
For highly consequential workflows, persist incoming requests in a durable job or admission table before starting the graph.
4. Enforce idempotency at the destination
Use provider-supported idempotency keys, database uniqueness constraints, atomic upserts, or transactional conditional writes.
An in-memory flag or ordinary graph-state boolean cannot protect against all crash windows.
5. Preserve the original response
Store provider identifiers, receipts, transaction references, and operation status so that recovery can return the original result instead of creating a replacement operation.
6. Treat timeouts as uncertain outcomes
A timeout does not guarantee that remote execution stopped.
Do not automatically retry an irreversible operation with a new identity. Reconcile uncertain outcomes before issuing new business actions.
7. Protect concurrent execution
Prevent multiple workers from independently resuming the same unfinished workflow using queue ownership, leases, locking, or supported orchestration mechanisms.
Keep destination-side deduplication as an additional safeguard.
8. Test the failure windows
Inject failures:
- Before the external request.
- After the request reaches the provider.
- After the external transaction commits.
- Before the graph checkpoint is saved.
- During checkpoint persistence.
- During concurrent recovery attempts.
Verify business invariants, not merely whether execution eventually completes.
Tasks inside nodes
Graph nodes provide natural execution boundaries. However, some nodes contain several expensive or nondeterministic operations.
Suppose an agent generates a proposal, estimates its cost, and requests human approval within one node.
When the interrupted node resumes, ordinary Python code before the interrupt runs again. This can unnecessarily repeat expensive model calls.
LangGraph’s @task decorator provides finer-grained execution boundaries inside Graph API nodes as well as Functional API workflows.
Completed task results can be restored from saved execution information rather than recomputed during recovery.
Example: Preserving an expensive task across an interrupt
This example demonstrates a proposal-generation task inside a graph node.
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import task
from langgraph.types import interrupt, Command
class State(TypedDict):
customer: str
proposal: NotRequired[str]
approved: NotRequired[bool]
@task
def generate_proposal(customer: str) -> str:
print("Generating expensive proposal")
# Simulates an expensive LLM request.
return f"Annual support proposal for {customer}"
def review_proposal(state: State):
print("Entering review node")
proposal = generate_proposal(
state["customer"]
).result()
approved = interrupt({
"proposal": proposal,
"question": "Approve this proposal?",
})
return {
"proposal": proposal,
"approved": approved,
}
builder = StateGraph(State)
builder.add_node("review", review_proposal)
builder.add_edge(START, "review")
builder.add_edge("review", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {
"configurable": {"thread_id": "proposal-101"}
}
result = graph.invoke(
{"customer": "Acme"},
config,
durability="sync",
)
print("Interrupted:", "__interrupt__" in result)
result = graph.invoke(
Command(resume=True),
config,
durability="sync",
)
print("Approved:", result["approved"])
print("Proposal:", result["proposal"])Expected output:
Entering review node
Generating expensive proposal
Interrupted: True
Entering review node
Approved: True
Proposal: Annual support proposal for AcmeThe review node executes again, but its saved task result is reused.
For synchronous tasks, retrieve results with .result(). In asynchronous nodes, use await with asynchronous tasks.
Keep task arguments and results serializable, and preserve deterministic task invocation order during replay.
Tip: A task is a recoverable unit of execution, not an exactly-once transaction. If a task performs an external operation but fails before its result is persisted, the task may execute again. Its external effects must still be idempotent.
Use separate tasks for independent expensive operations rather than placing numerous unrelated effects inside a single large task.
See the Functional API documentation for additional task execution and replay rules.
Checkpoint-based recovery in production
Choosing a persistent checkpointer
| Checkpointer | Survives process restart | Recommended use |
|---|---|---|
InMemorySaver |
No | Unit tests and experiments |
SqliteSaver |
Yes, with persistent file storage | Local development and smaller applications |
PostgresSaver |
Yes, with persistent database storage | Production synchronous workflows |
AsyncPostgresSaver |
Yes, with persistent database storage | Production asynchronous workflows |
SQLite is convenient for learning, but a local database file must reside on persistent storage to survive container replacement.
For distributed production systems, PostgreSQL is generally a better starting point.
Install the PostgreSQL checkpoint integration:
pip install -U langgraph-checkpoint-postgres "psycopg[binary,pool]"Example: Recovering workflows with PostgreSQL
This example assumes a reachable PostgreSQL database and a DATABASE_URL environment variable containing its connection string.
import os
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.postgres import PostgresSaver
class State(TypedDict):
job_id: str
status: NotRequired[str]
def process_job(state: State):
return {"status": "completed"}
builder = StateGraph(State)
builder.add_node("process", process_job)
builder.add_edge(START, "process")
builder.add_edge("process", END)
config = {
"configurable": {"thread_id": "production-job-101"}
}
with PostgresSaver.from_conn_string(
os.environ["DATABASE_URL"]
) as saver:
saver.setup()
graph = builder.compile(checkpointer=saver)
snapshot = graph.get_state(config)
if snapshot.next:
# Suitable for this graph, which has no dynamic interrupts.
result = graph.invoke(
None,
config,
durability="sync",
)
elif snapshot.values:
result = snapshot.values
else:
result = graph.invoke(
{"job_id": "JOB-101"},
config,
durability="sync",
)
print(result)
for checkpoint in graph.get_state_history(config):
print(
"Step:", checkpoint.metadata.get("step"),
"Next:", checkpoint.next,
)The first invocation creates and completes the job. Subsequent executions recover unfinished work or return the existing completed state.
In production, run saver.setup() as part of controlled database initialization or migration rather than independently in every worker.
The example is deliberately single-worker. Its inspect-then-invoke sequence is not an atomic distributed job-claiming mechanism.
Operational recovery procedure
When a worker fails:
- Retrieve the persisted job and thread identity.
- Acquire exclusive recovery ownership.
- Inspect
graph.get_state(config). - Determine whether the workflow is unfinished, completed, or waiting for human input.
- Reconcile uncertain external operations.
- Resume using the appropriate invocation.
- Verify both graph completion and business outcomes.
Inspect checkpoint history through get_state_history() when investigating failures.
If an operator needs to repair state, update_state(config, values, as_node=...) creates a new checkpoint representing the update. Because as_node can affect subsequent scheduling, use this API only with a clear understanding of the graph topology.
Do not manually mark a payment successful merely to bypass a failed node without verifying the provider’s transaction record.
Transactional outbox and reconciliation
For workflows that update a business database and publish an event, consider the transactional outbox pattern.
Write the business change and an outbox record within the same database transaction. A separate dispatcher delivers the event and records its delivery status.
If the dispatcher crashes after sending but before recording delivery, it may send the event again. Therefore, the receiving service must deduplicate events using their stable event IDs.
For external services without reliable idempotency support, maintain an operation ledger with states such as pending, confirmed, and unknown.
An unknown outcome should trigger provider lookup or reconciliation rather than unconditional repetition.
Compensation, such as refunding a payment, is another distinct business operation and requires its own idempotency protection.
Production considerations
Reliable checkpoint-based recovery also requires:
- Durable database storage, backups, and tested restoration.
- Tenant isolation and authorization for thread access.
- Checkpoint retention policies and compatible graph deployments.
- Secure handling of sensitive persisted state.
- Logging of thread IDs, operation IDs, attempts, and provider references.
- Alerts for repeatedly failing or unresolved operations.
When deploying graph changes, remember that existing threads may resume against the new graph implementation. Renaming unfinished nodes or changing task ordering can disrupt recovery.
Version long-running workflows and test upgrades against representative saved checkpoints.
LangSmith Agent Server manages checkpoint infrastructure automatically when using its managed execution environment, but application-level business idempotency remains your responsibility.
The next lesson extends these reliability foundations through node caching and loop guards. Caching reduces unnecessary computation, while loop guards prevent unbounded execution. Neither replaces durable checkpointing or destination-side idempotency.
Together, these mechanisms will support the chapter’s hands-on project: building a fault-tolerant workflow that recovers from simulated API failures without duplicating consequential business operations.
Build a crash-resilient invoice workflow
Build a LangGraph workflow that creates an invoice using a simulated billing service backed by SQLite. Simulate a lost API response immediately after the invoice has been committed, then reopen the checkpointer and resume the workflow using the original thread ID. Use a stable idempotency key to ensure that exactly one invoice exists and that the recovered workflow returns its original invoice ID.
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.sqlite import SqliteSaver
class InvoiceState(TypedDict):
order_id: str
amount_cents: int
operation_id: NotRequired[str]
invoice_id: NotRequired[str]
def billing_api(db_path, operation_id, amount_cents):
db = sqlite3.connect(db_path)
try:
db.execute("""
CREATE TABLE IF NOT EXISTS invoices (
operation_id TEXT PRIMARY KEY,
invoice_id TEXT NOT NULL,
amount_cents INTEGER NOT NULL
)
""")
cursor = db.execute(
"""
INSERT INTO invoices VALUES (?, ?, ?)
ON CONFLICT(operation_id) DO NOTHING
""",
(operation_id, f"INV-{operation_id}", amount_cents),
)
created = cursor.rowcount == 1
invoice_id, saved_amount = db.execute(
"""
SELECT invoice_id, amount_cents
FROM invoices WHERE operation_id = ?
""",
(operation_id,),
).fetchone()
if saved_amount != amount_cents:
raise ValueError("Idempotency key payload mismatch")
db.commit()
if created:
raise TimeoutError("Invoice committed, response lost")
return invoice_id
finally:
db.close()
def prepare(state: InvoiceState):
# TODO: Generate a stable business operation ID.
raise NotImplementedError
def build_graph(checkpointer, billing_db):
def create_invoice(state: InvoiceState):
# TODO: Call billing_api with the persisted operation ID.
# TODO: Return the invoice ID as a state update.
raise NotImplementedError
builder = StateGraph(InvoiceState)
# TODO: Register the nodes and connect them.
# START -> prepare -> create_invoice -> END
return builder.compile(checkpointer=checkpointer)
with TemporaryDirectory() as directory:
checkpoint_db = str(Path(directory) / "checkpoints.db")
billing_db = str(Path(directory) / "billing.db")
config = {
"configurable": {"thread_id": "invoice-workflow-101"}
}
# TODO: Open SqliteSaver and invoke the workflow.
# Catch the simulated TimeoutError.
# TODO: Reopen SqliteSaver, rebuild the graph,
# and resume the unfinished execution.
# TODO: Verify that exactly one invoice exists.import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.sqlite import SqliteSaver
class InvoiceState(TypedDict):
order_id: str
amount_cents: int
operation_id: NotRequired[str]
invoice_id: NotRequired[str]
def billing_api(db_path, operation_id, amount_cents):
db = sqlite3.connect(db_path)
try:
db.execute("""
CREATE TABLE IF NOT EXISTS invoices (
operation_id TEXT PRIMARY KEY,
invoice_id TEXT NOT NULL,
amount_cents INTEGER NOT NULL
)
""")
cursor = db.execute(
"""
INSERT INTO invoices VALUES (?, ?, ?)
ON CONFLICT(operation_id) DO NOTHING
""",
(operation_id, f"INV-{operation_id}", amount_cents),
)
created = cursor.rowcount == 1
invoice_id, saved_amount = db.execute(
"""
SELECT invoice_id, amount_cents
FROM invoices WHERE operation_id = ?
""",
(operation_id,),
).fetchone()
if saved_amount != amount_cents:
raise ValueError("Idempotency key payload mismatch")
db.commit()
if created:
raise TimeoutError("Invoice committed, response lost")
return invoice_id
finally:
db.close()
def prepare(state: InvoiceState):
return {
"operation_id": f"invoice:{state['order_id']}:v1"
}
def build_graph(checkpointer, billing_db):
def create_invoice(state: InvoiceState):
invoice_id = billing_api(
billing_db,
state["operation_id"],
state["amount_cents"],
)
return {"invoice_id": invoice_id}
builder = StateGraph(InvoiceState)
builder.add_node("prepare", prepare)
builder.add_node("create_invoice", create_invoice)
builder.add_edge(START, "prepare")
builder.add_edge("prepare", "create_invoice")
builder.add_edge("create_invoice", END)
return builder.compile(checkpointer=checkpointer)
with TemporaryDirectory() as directory:
checkpoint_db = str(Path(directory) / "checkpoints.db")
billing_db = str(Path(directory) / "billing.db")
config = {
"configurable": {"thread_id": "invoice-workflow-101"}
}
with SqliteSaver.from_conn_string(checkpoint_db) as saver:
graph = build_graph(saver, billing_db)
try:
graph.invoke(
{"order_id": "ORD-101", "amount_cents": 4999},
config,
durability="sync",
)
except TimeoutError as exc:
print("First invocation failed:", exc)
print("Pending nodes:", graph.get_state(config).next)
with SqliteSaver.from_conn_string(checkpoint_db) as saver:
graph = build_graph(saver, billing_db)
result = graph.invoke(
None,
config,
durability="sync",
)
print("Recovered invoice:", result["invoice_id"])
assert graph.get_state(config).next == ()
db = sqlite3.connect(billing_db)
try:
count = db.execute(
"SELECT COUNT(*) FROM invoices"
).fetchone()[0]
finally:
db.close()
print("Total invoices:", count)
assert count == 1
assert result["invoice_id"] == "INV-invoice:ORD-101:v1"
print("All recovery assertions passed.")Summary
- Durable execution preserves workflow progress through checkpoints rather than preserving the live Python execution stack.
- A persistent checkpointer and a stable thread ID allow unfinished workflows to resume across process restarts.
- Synchronous durability provides stronger checkpoint guarantees but cannot make external API operations exactly-once.
- Failed or interrupted nodes may execute again from their beginning, making replay-safe implementation essential.
- Stable business-level idempotency keys prevent repeated execution attempts from creating duplicate business effects.
- Tasks provide finer-grained recovery boundaries for expensive, nondeterministic, and side-effecting operations.
- Production recovery requires checkpoint inspection, external operation reconciliation, concurrency controls, and deliberate failure testing.