LangGraph: persistence, human approval and failure
- Advanced
- 40 min
- Lesson 4 of 7 in LangChain ecosystem
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:LangGraph: state, nodes, edges and control flow
- Completed:Context engineering and memoryContext, memory and multi-agent systems
You will be able to
- Distinguish the checkpointer from the store by scope, key and purpose, and say what a thread id selects.
- Implement a pause for human approval with interrupt and a resume command, and state what re-executes when the run resumes.
- Explain why a step can run twice after a failure or resume, and design side effects, durability settings and approvals to be safe.
- Use history, replay and fork correctly, and say what replay re-runs and what a fork leaves untouched.
The server restarts halfway through the morning’s job, and everything in memory is gone.
Kavya restores the saved state exactly as it stood at the last checkpoint. “But two refunds went out before the restart,” she says, “and the job starts again from its last saved step.”
What happens to those refunds when it runs again?
Concept
The graph from lesson 3 lives in memory. Kill the process and it is gone. Persistence is what lets LangGraph pick up where it stopped, and it is also what makes the harder questions appear: what exactly was saved, what runs again, and what happens to a side effect that already happened.
Two separate stores do the saving. A checkpointer keeps one conversation’s state. A store keeps memories that outlive any one conversation. On top of the checkpointer sit interrupts, which pause a run for a person, and time travel, which lets you look back, replay and branch. The same mechanism that makes all this possible makes one rule unavoidable: steps can run more than once.
Why It Matters
Agent work that matters is slow and interrupted. A refund waits two days for a manager. A deploy script is killed mid-run. A user closes the tab and returns tomorrow. If the only state is in memory, each of those is a restart from nothing. If the state is saved but side effects are careless, each is a duplicate charge. Interviewers for agent roles ask about exactly this seam, and “I used a checkpointer” is the start of the answer, not the end.
Mental Model
In the story, Kavya keeps two stores. One holds a copy of the state after every round, labelled with the job’s number: that is the checkpointer, and the job number is the thread id. The other holds notes about people that any job may read: that is the store.
When the server comes back, Kavya loads the latest copy of the state and the job restarts at the step where it stopped. She can restore the state exactly. She cannot take back a refund that was already sent, because the refund happened outside the saved state. Whatever a step did in the world is that step’s problem.
Two kinds of saved state
| Checkpointer | Store | |
|---|---|---|
| Scope | One thread | Across threads and users |
| Holds | The graph’s state, as checkpoints | Application-defined memories: preferences, facts |
| Used for | Conversation continuity, approvals, time travel, recovery | Long-term memory |
| Keyed by | A thread id | A namespace and a key |
| Implementations named in the docs | An in-memory saver (lost on restart), a SQLite saver, a Postgres saver | An in-memory store for development; a database-backed store for production |
You attach them when you compile, and select a thread through the run config:
# Illustrative, after the persistence and memory pages.
with PostgresSaver.from_conn_string(DB_URI) as checkpointer:
checkpointer.setup() # creates the tables
graph = builder.compile(checkpointer=checkpointer, store=store)
graph.invoke(inputs, {"configurable": {"thread_id": "cust-42"}})Reuse a thread id and you continue that state. Use a new id and you start fresh. Treat the id as part of your access control: if one user can guess or supply another’s id, they can load that conversation. Postgres-backed ids must stay under 255 characters, and the docs warn that checkpoints accumulate over long conversations, so plan pruning or a retention policy.
The store groups items under a namespace tuple, typically by user, with a key and a dict as the value. A node reaches it through the runtime object. If you give the store an embedding index, a search matches by meaning instead of exact key.
# Illustrative, after the add-memory page.
store.put(("user_123", "memories"), "pref-lang", {"text": "prefers short replies"})
hits = store.search(("user_123", "memories"), query="how should I answer?", limit=1)The write policy questions from lesson 2 apply here. Namespace by user or tenant so access and deletion are clean. Decide whether the agent writes a memory in the middle of a conversation (immediate, but slower and noisier) or a separate job extracts memories afterwards (better latency, delayed). The docs show the inline pattern; the background pattern is a design choice you would justify with your own latency and quality data.
Pausing for a person
An approval has to survive a delay of hours or days, so it cannot be a function that blocks on input. LangGraph’s answer is interrupt. A node calls it with a payload for the reviewer. The runtime saves the state through the checkpointer, returns control to the caller with the payload, and waits indefinitely. Calling the graph again with a resume command, on the same thread, continues the run, and the call to interrupt returns whatever value you resumed with.
# Illustrative, after the interrupts page.
from langgraph.types import interrupt, Command
def approve_refund(state):
decision = interrupt({"action": "refund", "amount": state["amount"], "order": state["order_id"]})
if decision["approved"]:
return {"status": issue_refund(state["order_id"], key=state["request_id"])}
return {"status": "rejected"}
graph = builder.compile(checkpointer=checkpointer)
config = {"configurable": {"thread_id": "refund-9"}}
out = graph.invoke({"order_id": "8841", "amount": 120, "request_id": "r-9"}, config)
out["__interrupt__"] # the payload for the reviewer's screen
graph.invoke(Command(resume={"approved": True}), config) # later, same threadRequirements, from the docs: a checkpointer, a thread id, and a payload that can be serialised as JSON.
| Phase | Code before interrupt | The interrupt call | Code after interrupt |
|---|---|---|---|
| First run | Runs | Saves state and pauses | Does not run yet |
| After resume | Runs again | Returns the resume value | Runs |
What actually happens on resume. The node does not continue from the interrupt line. It starts again from its beginning, and this time interrupt returns the resume value instead of pausing. That single fact produces the rules the docs list:
- Anything before
interruptruns again. Put non-repeatable work after it, or in another node, or make it idempotent. - Do not wrap
interruptin a baretry/except. The pause is implemented as an exception, and you would catch it. Catch specific exception types. - Keep the order of interrupts in a node stable. Resume values match by position, so do not skip one conditionally or loop over data that changes between runs.
- Pass simple data, not functions or class instances.
- Avoid a
while Trueloop aroundinterrupt. Call it once per node run and use a conditional edge to ask again. - When parallel branches interrupt together, resume them in one call with a map of interrupt ids to values.
Static breakpoints. The graph can also be told to stop before or after named nodes. The docs say these are for debugging and are not recommended for human-approval flows. Use interrupt for the product.
Designing the review. Common shapes are approve or reject, edit then approve (the person changes the arguments), a question back to the user, and review of a draft. In LangChain the human-in-the-loop middleware from lesson 2 wraps this for tool calls. Around it, the operational pieces matter: a timeout or escalation for an unanswered review, an audit record of who approved what, an idempotent action after approval, and a clear policy on what always needs a person (money leaving, deletion, external email).
Steps run more than once
Put the story and the docs together. The checkpointer saves state at step boundaries. If a failure happens between steps, the run resumes from the last saved state. If a failure happens inside a node, that node runs again from its start. An interrupt resume also re-runs its node. So for anything the node does outside the graph, the guarantee is at least once, not exactly once.
The checkpointers page says a task that started but did not finish is re-run on resume. The interrupts page says side effects before an interrupt must be idempotent, for example by using an upsert or checking whether a record already exists. Idempotency keys, as payment APIs use them, are this course’s extension of that advice.
| Where the failure happens | What reruns on resume |
|---|---|
| Between steps | Nothing: the run continues from the last saved state |
| Inside a node | That node, from its start, so outside effects can repeat |
| After an interrupt | The interrupted node, from its start |
For anything a node does outside the graph, the guarantee is at least once, not exactly once.
What to do about it:
- Idempotency keysIdempotency keyA unique value sent with a side-effecting request so the receiver can recognise a repeat and not act twice. It protects against retries and loops.Open the glossary entry. Derive a stable key from the request (the refund request id in the example) and send it with the call, so the receiver ignores a repeat.
- Record “done” in state before the next step, or check for an existing result before acting.
- Order the work. Do the non-repeatable action after the interrupt, never before it.
- Retry deliberately. A per-node retry policy handles transient errors. For input that fails every time, cap the attempts and route to a person or a queue instead of looping.
- Timeouts on model calls, tool calls and the whole run.
- Reject duplicate resumes. Two reviewers clicking approve should not issue two refunds. The action’s idempotency key handles it.
Durability settings. The checkpointers page describes three durability modes you choose per run: save only when the run exits, save in the background while the next step runs, or save before each next step. The names are exit, async and sync, ordered from least to most durable. The first is fastest and cannot recover from a crash mid-run; the last is safest and slowest; the middle risks losing the latest checkpoint if the process dies. Pick by what a lost step costs.
| Mode | When state is saved | Speed | Risk |
|---|---|---|---|
exit | Only when the run exits | Fastest | Cannot recover from a crash mid-run |
async | In the background while the next step runs | Middle | May lose the latest checkpoint if the process dies |
sync | Before each next step | Slowest | Safest |
Other rehearsals. If the database is down, fail closed: do not carry on and lose an approval. Treat a corrupted state as repairable (the update-state call below). When the state’s shape changes while runs are in flight, version it and handle missing keys. If one parallel branch fails, completed siblings can keep their saved writes so they are not redone on retry, which matters when branches are expensive. The Checkpointers page describes this as pending writes from nodes that succeeded in a failed step.
Time travel: history, replay and fork
Because every step has a checkpoint, you can look back.
- History. Listing a thread’s checkpoints returns them newest first, each with an id.
- Replay. Invoke with an earlier checkpoint’s config to run again from there. Nodes before it are not re-run, because their results are saved. Nodes after it do run again. The docs are blunt that replay re-executes nodes and does not just read from a cache: model calls and API requests happen again and may differ, and their side effects fire again. Replaying from the final checkpoint does nothing.
- Fork. Update the state at an earlier checkpoint, then invoke. This creates a new checkpoint that branches from that point. The original history is untouched. A setting names which node the update should count as coming from, so execution resumes at that node’s successors.
Uses: finding where a trajectory went wrong, trying a prompt change from the same midpoint, correcting an agent’s wrong assumption without redoing early steps, and building an undo.
A worked case. An agent made a wrong assumption at step 4 of 9. To fix it without redoing steps 1 to 3: fork from the checkpoint before step 4 with the corrected state and run on. Steps 1 to 3 are not repeated. Steps 4 to 9 run again, and any side effects in them fire again, so check what those steps touch before you do it on a live thread.
Subgraphs and handoffs
A compiled graph can be a node inside another graph, or be called from inside a node. This gives you reusable parts, separate state shapes and isolated message history for a specialist. Two cautions from the docs: a subgraph’s state changes may not show in the parent straight away (design the shared keys on purpose, or use a shared store), and a Command that targets the parent graph needs a reducer on any key it shares. Keep the tree shallow; each level is another place to debug.
A handoff between agents is a tool that returns a Command naming the next agent, pointed at the parent graph. Pass the next agent a task summary, not the whole transcript: a full history on every hop costs tokens and mixes instructions. Supervisor and swarm helper packages exist; they are thin wrappers over these primitives, and being able to write the primitive yourself is what an interview checks.
Real-World Application
A refund agent. The graph classifies the request, looks up the order, and reaches approve_refund. Amount above a threshold: interrupt with the order, the amount and the reason, and stop. The thread id is the case number. Two days later a manager approves from a review screen. The run resumes from the saved checkpoint; the node starts from its top, interrupt returns the decision, and issue_refund is called with the request id as an idempotency key. If the manager’s browser sends the approval twice, the second call finds the key already used and does nothing. Everything before the interrupt is read-only. The audit record stores who approved, when, and the payload they saw. The memory of “this customer prefers email” lives in the store under the customer’s namespace, not in the thread.
Interview Perspective
Expect: “Checkpointer or store?”, “A reviewer approves a refund two days after the agent paused. What is stored, what re-executes, how do you prevent a double refund?”, “An agent made a wrong assumption at step 4 of 9; how do you fix it without redoing 1 to 3?”, “What does interrupt actually do?”, “Can I put an email send before interrupt?”
Strong answers say: state is saved at the interrupt in a durable checkpointer under the thread id; resume re-runs the node from the top; the refund call carries an idempotency key; the approval is recorded; a duplicate resume is harmless. For time travel: fork before step 4; later steps run again, so side effects can fire again.
Common mistakes: a checkpointer without a thread id; the in-memory saver in production; a side effect before interrupt; treating the store as chat history, or state as long-term memory; surprise that replay fires tool effects again; passing the full transcript at each handoff; never pruning checkpoints; not authorising access to thread ids.
Provenance: Common industry pattern. These are the questions this topic tends to draw for agent roles; none is verified for a named company.
Practice Questions
- Basic: Compare the checkpointer and the store by scope, key and an example use.
- Intermediate: Implement refund approval where the reviewer can change the amount. How do you make a resume that arrives twice safe?
- Advanced: An agent made a wrong assumption at step 4 of 9. How do you correct it without redoing steps 1 to 3, and what runs again?
- Product-Company: Design long-term memory for a personal assistant: write policy, namespaces, retrieval, deletion and evaluation.
Activity
Take the refund flow above and mark every line of the approval node as “safe to repeat” or “must happen once”. Move each “must happen once” line after the interrupt call, and say what key you would give it.
Homework
Write a one-page runbook for a pausing graph. Cover the saver you would use and why, how thread ids are issued and authorised, the review timeout and escalation, the idempotency key for each outside action, which durability setting you would choose and what a lost checkpoint would cost, and a retention rule for old checkpoints.
Quick Revision
- Checkpointer: one thread’s state, keyed by thread id. Store: memories across threads, keyed by namespace and key.
interruptsaves state and pauses; resume with the same thread and a resume command; the node restarts from its top.- Side effects before
interruptrun twice. Do not catch it with a bare except. Keep interrupt order stable. - Outside effects are at least once. Use idempotency keys and check for existing results.
- Durability: exit, async or sync, from fastest to safest.
- Replay re-executes later nodes (side effects again). Fork branches without changing history.
- Pass summaries across handoffs, not transcripts.
Check yourself
- Walk-through: A reviewer approves a refund two days after the agent paused. Say what is stored, what runs again and how a double refund is prevented.
- Variation: Add a second approval from a manager above a higher amount. Sequential or parallel, and how do the interrupt ids behave?
- Common misconception: “
interruptcontinues from the exact line, so earlier code does not run again.” It restarts the node.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Memory overview (LangGraph documentation) (opens in a new tab)
The overview of short-term and long-term memory in LangGraph, which frames when to use the checkpointer and when to use the store.
Hands-on
langchain-ai/langgraph (GitHub repository) (opens in a new tab)
The source code and examples for the library, useful for reading how checkpointing is implemented and for running the course's crash tests yourself.
More for this module: LangChain ecosystem resources
Practice
Test what you just read. Quizzes and cards are grouped by module: LangChain ecosystem.
Check yourself12 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.