LangGraph: persistence, human approval and failure

  • Advanced
  • 40 min
  • Lesson 4 of 7 in LangChain ecosystem
  • Last verified

Open slides(29 slides)

Before you start

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

Diagram: A thread is a line of checkpoints, each a copy of the graph’s state after a step, saved by the checkpointer.

read or write long-term memory

One thread

checkpoint 1

checkpoint 2

checkpoint 3

Checkpointer

Store: namespace, key, JSON

node

Diagram summary: A thread is a line of checkpoints, each a copy of the graph’s state after a step, saved by the checkpointer. The store is a separate shelf of memories that any node can read or write, shared across threads.
CheckpointerStore
ScopeOne threadAcross threads and users
HoldsThe graph’s state, as checkpointsApplication-defined memories: preferences, facts
Used forConversation continuity, approvals, time travel, recoveryLong-term memory
Keyed byA thread idA namespace and a key
Implementations named in the docsAn in-memory saver (lost on restart), a SQLite saver, a Postgres saverAn 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:

Python

# 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.

Python

# 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.

Python

# 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 thread

Requirements, from the docs: a checkpointer, a thread id, and a payload that can be serialised as JSON.

Diagram: Calling interrupt saves the state through the checkpointer and returns control with a payload for the reviewer.
ReviewerCheckpointerGraphYour appReviewerCheckpointerGraphYour appminutes, hours or days passinvoke(input, thread refund-9)node calls interrupt(payload)save statereturns with __interrupt__ payloadshow the refund for approvalapprovedinvoke(Command(resume=approved), same thread)load statenode restarts, interrupt returns the valuefinal result
Diagram summary: Calling interrupt saves the state through the checkpointer and returns control with a payload for the reviewer. The graph then waits, with no process blocked. When the answer arrives, the app resumes on the same thread, the state is loaded, and the node runs again with interrupt returning the reviewer’s value.
PhaseCode before interruptThe interrupt callCode after interrupt
First runRunsSaves state and pausesDoes not run yet
After resumeRuns againReturns the resume valueRuns

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:

  1. Anything before interrupt runs again. Put non-repeatable work after it, or in another node, or make it idempotent.
  2. Do not wrap interrupt in a bare try/except. The pause is implemented as an exception, and you would catch it. Catch specific exception types.
  3. 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.
  4. Pass simple data, not functions or class instances.
  5. Avoid a while True loop around interrupt. Call it once per node run and use a conditional edge to ask again.
  6. 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 happensWhat reruns on resume
Between stepsNothing: the run continues from the last saved state
Inside a nodeThat node, from its start, so outside effects can repeat
After an interruptThe 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.

ModeWhen state is savedSpeedRisk
exitOnly when the run exitsFastestCannot recover from a crash mid-run
asyncIn the background while the next step runsMiddleMay lose the latest checkpoint if the process dies
syncBefore each next stepSlowestSafest

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.

Diagram: Forking from the checkpoint before step 4 with a corrected state creates a new branch.

fork: update state, then invoke

checkpoint 1

checkpoint 2

checkpoint 3
(before step 4)

step 4: wrong assumption

... to step 9

new step 4 with corrected state

... new steps 5 to 9

Diagram summary: Forking from the checkpoint before step 4 with a corrected state creates a new branch. Steps 1 to 3 are not repeated, steps 4 to 9 run again on the new branch, and the original history stays untouched. Side effects in the re-run steps fire again.

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.
  • interrupt saves state and pauses; resume with the same thread and a resume command; the node restarts from its top.
  • Side effects before interrupt run 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: “interrupt continues from the exact line, so earlier code does not run again.” It restarts the node.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Hands-on

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.

0 of 12 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveDistinguish the checkpointer from the store by scope, key and purpose, and say what a thread id selects.

  1. Question 1 of 12A user's preferred language should be remembered across all of their future conversations. Which persistence mechanism holds it?

    Choose one answer.

  2. Question 2 of 12What does the thread id in the run config select?

    Choose one answer.

  3. Question 3 of 12A service uses the in-memory checkpointer from the tutorials in production. What goes wrong?

    Choose one answer.

ObjectiveImplement a pause for human approval with interrupt and a resume command, and state what re-executes when the run resumes.

  1. Question 4 of 12A node calls interrupt, a reviewer approves two days later, and the graph is resumed with the resume command on the same thread. Where does execution continue?

    Choose one answer.

  2. Question 5 of 12Inside an approval node, the first line sends a "your refund is pending" email and the next line calls interrupt. What is the problem?

    Choose one answer.

  3. Question 6 of 12Which of these are real requirements or rules for using interrupt? Select all that apply.

    Choose all that apply.

ObjectiveExplain why a step can run twice after a failure or resume, and design side effects, durability settings and approvals to be safe.

  1. Question 7 of 12A power cut kills the process in the middle of a node that has already charged a card. The graph resumes. What is the guarantee for the charge?

    Choose one answer.

  2. Question 8 of 12Two managers both click approve on the same refund within a second, and each click resumes the run. What design keeps the refund single?

    Choose one answer.

  3. Question 9 of 12A team needs the fastest possible run and accepts that a mid-run crash cannot be recovered. Which durability choice matches?

    Choose one answer.

ObjectiveUse history, replay and fork correctly, and say what replay re-runs and what a fork leaves untouched.

  1. Question 10 of 12Replaying a thread from an earlier checkpoint re-runs the later nodes. What does that mean for a node that calls a paid API?

    Choose one answer.

  2. Question 11 of 12An agent made a wrong assumption at step 4 of 9. You want to correct it without redoing steps 1 to 3. What is the right move?

    Choose one answer.

  3. Question 12 of 12After forking from an earlier checkpoint, what happens to the original thread history?

    Choose one answer.