8  Save & Resume

Every graph so far has been an amnesiac. You call invoke, the state flows through the nodes, an answer comes back — and the instant that call returns, the whole run evaporates. If the process crashes halfway, there is nothing to go back to; you start over from the top.

This chapter hands the compiled graph a checkpointer:

A checkpointer lets a graph retain its execution state. After every superstep the runtime auto-saves the full state under a thread_id, so a run can resume from the last saved step — and you can even rewind to an earlier checkpoint and fork a new run from it.

Durability is a property of the compiled graph, not of the logic inside it: the nodes never learn they are being saved. InMemorySaver, used throughout this chapter, resumes within a single process, so the demos below recover from a caught exception, not a real crash. Surviving a restart needs a persistent saver (Taking it to production, below). This chapter also runs at the default "async" durability mode; the Gold challenge is where the modes matter.

8.1 What we’re building

We reuse the branching doc-bot, grown into the small loop from Chapter 6. The agent routes to the next step and comes back to itself between each one — internal docs, then the web, then generate. The loop matters here because it gives us several supersteps, and therefore several checkpoints, to inspect, resume from, and travel back to.

flowchart LR
    START(["START"]) --> agent{"agent"}
    agent -.->|route = search| search("search_docs") --> agent
    agent -.->|route = web| web("web_search") --> agent
    agent -.->|route = generate| generate("generate") --> END(["END"])

Branch, act, loop back, decide again. What is new does not show in the diagram: the checkpointer wrapped around it.

8.2 The state and the nodes

The state carries the same six fields as Chapter 7, and the graph is the same shape. The node bodies are not Chapter 7’s, though, and the difference is deliberate. This chapter is about the wrapper, so the work inside each node shrinks to one print line that says expensive. Those lines are the chapter’s measuring instrument — when a resumed run doesn’t print them, you are watching the checkpoint do its job.

class State(TypedDict):
    question: str                        # input, set by the caller
    route: NotRequired[str]              # written by agent: search/web/generate
    docs: NotRequired[list[str]]         # written by search_docs
    web_results: NotRequired[list[str]]  # written by web_search
    iterations: NotRequired[int]         # bumped by agent each time it runs
    answer: NotRequired[str]             # written by generate


def agent_node(state: State) -> dict:
    docs = state.get("docs", [])
    web = state.get("web_results", [])
    if not docs:
        route = "search"
    elif not web:
        route = "web"
    else:
        route = "generate"
    print(f"[agent] docs={len(docs)} web={len(web)} -> {route}")
    return {"route": route, "iterations": state.get("iterations", 0) + 1}


def search_docs_node(state: State) -> dict:
    # Pretend this is a slow, expensive retrieval call.
    print("[search_docs] searching internal docs (expensive)")
    return {"docs": ["doc-1", "doc-2"]}


def web_search_node(state: State) -> dict:
    # Also slow and expensive — the kind of work you don't want to redo.
    print("[web_search] searching the web (expensive)")
    return {"web_results": ["web-A"]}


def generate_node(state: State) -> dict:
    print("[generate] composing the final answer")
    # ... a fault switch lands here in "Crashing and resuming" ...
    docs = state.get("docs", [])
    web = state.get("web_results", [])
    answer = (
        "Final answer synthesized from the docs and web results "
        f"(docs={len(docs)}, web={len(web)})"
    )
    return {"answer": answer}

Chapter 7’s agent fell back to the web only when the local search missed; this one visits both search nodes every time — a change you will see in every transcript below. A longer run leaves more checkpoints to inspect, resume from, and rewind.

8.3 Turning on durability

To turn on durability, you need to compile the graph with a checkpointer, and invoke with a thread_id:

from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver

# ... builder.add_node(...) / add_edge(...) as before ...

# The one new line: hand the compiled graph a checkpointer.
graph = builder.compile(checkpointer=InMemorySaver())

run1_cfg = {"configurable": {"thread_id": "run-001"}}
run1 = graph.invoke({"question": "How do I configure Kafka?"}, config=run1_cfg)

flowchart TD
    START(["START"]) --> agent{"agent"}
    agent -.->|search| search_docs("search_docs") --> agent
    agent -.->|web| web_search("web_search") --> agent
    agent -.->|generate| generate("generate") --> END(["END"])

The nodes and edges are untouched, and once a checkpointer is attached, every invoke needs a thread_id in its config. The thread_id is a filing label. Everything that happens on "run-001" is saved together as one timeline, separate from every other thread. Think of it as a conversation id; it has nothing to do with Python threads.

What gets saved is the full merged state after each superstep — the same merge you met in Chapter 3, persisted each time. (How those snapshots are stored is the subject of Chapter 26; here we only use them.)

8.4 Reading the snapshots

A durable run leaves a trail, and the key to it is the same config you passed to invoke: {"configurable": {"thread_id": "run-001"}}. graph.get_state(config) hands back the thread’s latest snapshot; graph.get_state_history(config) yields every snapshot on it, newest first. Each snapshot carries the state values, the next nodes still to run, and metadata like the step number.

def show_history(config: dict) -> None:
    # get_state_history yields snapshots newest-first; reverse for a timeline.
    history = list(graph.get_state_history(config))
    print(f"snapshots saved on this thread: {len(history)}")
    for snap in reversed(history):
        vals = snap.values
        nxt = ", ".join(snap.next) if snap.next else "(done)"   # empty == done
        print(
            f"  step {snap.metadata.get('step'):>2}  next={nxt:<12}"
            f"  docs={len(vals.get('docs', []))}"
            f" web={len(vals.get('web_results', []))}"
            f" iter={vals.get('iterations', '-')}"
            f" answer={'yes' if 'answer' in vals else 'no'}"
        )

Run the autosave block from Section 8.3 with show_history at the end of it, and the trail comes out like this:

===== 1. Autosave: one run, snapshots persist (thread_id=run-001) =====
[agent] docs=0 web=0 -> search
[search_docs] searching internal docs (expensive)
[agent] docs=2 web=0 -> web
[web_search] searching the web (expensive)
[agent] docs=2 web=1 -> generate
[generate] composing the final answer
answer: Final answer synthesized from the docs and web results (docs=2, web=1)

latest snapshot: next=(done)  iterations=3
snapshots saved on this thread: 8
  step -1  next=__start__     docs=0 web=0 iter=- answer=no
  step  0  next=agent         docs=0 web=0 iter=- answer=no
  step  1  next=search_docs   docs=0 web=0 iter=1 answer=no
  step  2  next=agent         docs=2 web=0 iter=1 answer=no
  step  3  next=web_search    docs=2 web=0 iter=2 answer=no
  step  4  next=agent         docs=2 web=1 iter=2 answer=no
  step  5  next=generate      docs=2 web=1 iter=3 answer=no
  step  6  next=(done)        docs=2 web=1 iter=3 answer=yes

Eight snapshots for six node runs — agent went around three times. Steps 1 to 6 are one per superstep; the two before them are the input arriving and the state it left behind. Read next as the node the thread would run if you resumed it here, which makes the (done) on the last row an empty next: nothing left to run. That last row is the one get_state hands back.

Each snapshot is a StateSnapshot with these fields:

The fields of a StateSnapshot.
Field What it holds Example
values The full merged state at this point {'question': …, 'docs': […], 'iterations': 2}
next The node names still due to run; empty when the run is done. Can be a subset of tasks ('agent',)
metadata Source and step number {'source': 'loop', 'step': 4, 'parents': {}}
config Addresses this snapshot: thread_id plus a checkpoint_ns and a checkpoint_id {'configurable': {'thread_id': 'run-001', 'checkpoint_ns': '', 'checkpoint_id': '1f19…'}}
parent_config Same for the previous snapshot; None for the first
created_at Timestamp, to the microsecond '2026-08-22T17:34:42.949233+00:00'
tasks One PregelTask1 per task in this checkpoint’s batch: the node name, plus its result, error, or interrupt once attempted. A sibling that already finished still appears here, so tasks can outnumber next (PregelTask(name='agent', result={…}),)
interrupts Pending interrupt() calls (Chapter 9) ()

show_history reads only values, next, and metadata; the checkpoint_id inside config is what Section 8.6 uses to pick an older snapshot. Printed as a timeline it shows the state filling in one superstep at a time — docs, then web_results, then answer — with agent appearing several times because it’s a loop. Two setup snapshots sit at the top: step -1 pristine, step 0 holding the input with agent still to run.

8.5 Crashing and resuming

We stage a crash: a global flag makes generate raise once, as if a downstream model timed out.

SIMULATE_OUTAGE = False


def generate_node(state: State) -> dict:
    print("[generate] composing the final answer")
    if SIMULATE_OUTAGE:
        raise RuntimeError("downstream model timed out")
    # ... compose the answer as before ...
crash_cfg = {"configurable": {"thread_id": "run-crash-002"}}
SIMULATE_OUTAGE = True
try:
    graph.invoke({"question": "How do I configure Kafka?"}, config=crash_cfg)
except RuntimeError as err:
    print("caught:", err)

parked = graph.get_state(crash_cfg)   # next == ('generate',); docs & web intact

The run got all the way to generate and died there. But the expensive work before it — the doc search, the web search — was checkpointed as it happened. The parked snapshot still holds docs and web_results, and its next points at the node that failed, generate.

flowchart LR
    a1("agent") --> sd("search_docs") --> a2("agent") --> ws("web_search") --> a3("agent") -- "SIMULATE_OUTAGE" --> g("generate<br/>✗ RuntimeError")
    a3 -. "checkpoint saved<br/>next = ('generate',)" .-> cp[("InMemorySaver")]
    classDef crash fill:#f8d7da,stroke:#b02a37,color:#000;
    classDef saver fill:#d6e6f7,stroke:#3b6ea5,color:#000;
    class g crash;
    class cp saver;

To resume, we fix the fault and call invoke(None, ...) on the same thread:

SIMULATE_OUTAGE = False
# invoke(None) means: no new input, just continue from the saved point.
resumed = graph.invoke(None, config=crash_cfg)

Only generate runs on resume, because the checkpoint remembers that the run stopped just before it. search_docs and web_search do not fire again, and iterations picks up where it left off instead of resetting to zero. Resuming restores the graph’s state, not a Python call stack; the recovery granularity is one node. That holds even in a parallel step (Chapter 10). If sibling a finished and b crashed, a’s result is already saved, and only b re-runs on resume — the whole step does not repeat.

WarningGotcha: a checkpoint is not long-term memory

Reaching for the same thread_id next week to “remember” a user gets you a run that never ended rather than memory. Last week’s docs, web_results and answer are already filled in, and the agent routes on that stale state, not on the new question (the Silver challenge runs into this). Long-term memory is a different tool — the Store, Chapter 17 — deliberate and distilled where checkpoints are automatic and lossless.

8.6 Time travel

Because every superstep is saved, the history isn’t just for reading — you can go back to any snapshot, change something, and continue from there. That forks a new line off the old timeline; the original run stays intact.

# The snapshot from the first run, just before `generate` ran.
before_generate = next(
    s for s in graph.get_state_history(run1_cfg)
1    if s.next == ("generate",)
)
2forked_cfg = graph.update_state(
    before_generate.config,
    {"web_results": ["web-A", "web-B", "web-C"]},
3    as_node="agent",
)
4fork_run = graph.invoke(None, config=forked_cfg)
1
The moment just before the answer was written: the snapshot whose next is generate — which is the same instant as just after agent returned. Hold on to that "agent"; note 3 needs it.
2
update_state writes the change into a new checkpoint branched off the old one and hands back a config pointing at it.
3
Treat the edit as if agent had just returned it, so agent’s outgoing edge decides next. That edge reads route, still the "generate" that agent wrote at step 5; the edit did not touch it. as_node has to name a real node: it is not a label, it picks whose edge runs next.
4
Feeding the forked config to invoke(None, ...) resumes from the fork.

flowchart TD
    START(["START"]) --> agent{"agent"}
    agent -.->|search| search_docs("search_docs") --> agent
    agent -.->|web| web_search("web_search") --> agent
    agent -.->|generate| generate("generate") --> END(["END"])
    classDef asnode fill:#d6e6f7,stroke:#3b6ea5,color:#000;
    classDef rerun fill:#bfb6fc,stroke:#6b5fd0,color:#000;
    class agent asnode;
    class generate rerun;

The two shaded nodes are the seam we rewind to. The edit is handed to agent (blue), so it is agent’s outgoing edge that decides where the fork goes — and generate (purple) is where it sends it.

We pretended the web search had returned three hits instead of one and let only generate re-run — so the forked answer is built from richer evidence while the original answer is untouched and still readable by its own checkpoint.

What time travel is for

It is a debugging and correction tool, not a recovery path — Chapter 21’s retries are the automatic recovery. It has four uses:

  • Replay a production thread from the step where the agent went wrong.
  • Correct and continue: fix a tool result by hand, as we faked three web hits above. (Chapter 9 builds this into the graph as a pause that waits for a human.)
  • Compare by forking one checkpoint several ways.
  • Edit a conversation, backing a chat UI’s “edit my last message” — the edited turn becomes a branch and the old one stays readable.

8.7 Running it

The program runs all three moves in order — autosave, crash-and-resume, and a fork — on the same durable doc-bot. There is no new code in it. Each move is the block already printed in its own section above, and every snapshots saved on this thread table is one call to the show_history helper from Section 8.4. Move 1 is the output already shown there, so what follows picks up at move 2.

if __name__ == "__main__":
    # 1) autosave        invoke on run-001, then show_history(run1_cfg)
    # 2) crash & resume  invoke on run-crash-002 with SIMULATE_OUTAGE, then
    #                    flip it back and invoke(None, ...) on the same thread
    # 3) time travel     find the pre-generate snapshot on run-001,
    #                    update_state(..., as_node="agent"), invoke(None, ...)
    ...
===== 2. Crash & resume on the same thread (thread_id=run-crash-002) =====
-- first attempt (downstream is down) --
[agent] docs=0 web=0 -> search
[search_docs] searching internal docs (expensive)
[agent] docs=2 web=0 -> web
[web_search] searching the web (expensive)
[agent] docs=2 web=1 -> generate
[generate] composing the final answer
caught: downstream model timed out
parked at: next=generate | docs=2 web=1 iterations=3
-- resume (downstream recovered) --
[generate] composing the final answer
resumed answer: Final answer synthesized from the docs and web results (docs=2, web=1)
1iterations=3  (not restarted from 0 — it resumed mid-run)
note: no new [search_docs]/[web_search] lines — the expensive work came from the checkpoint

===== 3. Time travel: rewind, change a field, fork (thread_id=run-001 again) =====
original run: web_results=['web-A'] iterations=3
              answer=Final answer synthesized from the docs and web results (docs=2, web=1)
rewound to the pre-generate snapshot, injected 3 web results…
[generate] composing the final answer
forked run:   web_results=['web-A', 'web-B', 'web-C'] iterations=3
              answer=Final answer synthesized from the docs and web results (docs=2, web=3)

answers differ after the fork: True
original run still intact: True
snapshots saved on this thread: 10
  step -1  next=__start__     docs=0 web=0 iter=- answer=no
  step  0  next=agent         docs=0 web=0 iter=- answer=no
  step  1  next=search_docs   docs=0 web=0 iter=1 answer=no
  step  2  next=agent         docs=2 web=0 iter=1 answer=no
  step  3  next=web_search    docs=2 web=0 iter=2 answer=no
  step  4  next=agent         docs=2 web=1 iter=2 answer=no
  step  5  next=generate      docs=2 web=1 iter=3 answer=no
  step  6  next=(done)        docs=2 web=1 iter=3 answer=yes
2  step  6  next=generate      docs=2 web=3 iter=3 answer=no
  step  7  next=(done)        docs=2 web=3 iter=3 answer=yes
1
The counter survived the crash. A run that had started over would read iterations=1; the resumed run picked up the state the checkpoint was holding and carried on counting.
2
Two rows say step 6 — that is the fork, on one thread. The first is the original run, finished. This one branched off step 5 instead, and its next is generate because the edit was handed to agent, whose edge still routes there.

In block 2 the resume prints a single new [generate] line: the doc search and the web search did not run again. Block 3 does not start a thread of its own — it goes back to run-001, the thread block 1 finished, and rewinds it, which is why the forked answer reads web=3 while the original still reads web=1.

TipTry it: change the question, then rewind somewhere else

Change the crash thread’s question to a plain greeting like "Hi there!" and look at where the run parks. The agent routes on what it has gathered, not on the question, so the parked snapshot is the same: next=generate, docs and web intact.

Then, in the time-travel block, rewind to the ('web_search',) snapshot instead of the ('generate',) one and resume. Now web_search runs again, then agent, then generate — three [...] lines instead of one — and watch what happens to the web_results you injected: web_search re-runs and overwrites them, so the forked answer reads web=1 again. Where you rewind to decides what re-runs, and whatever a re-run node writes wins over your edit. (Now try as_node="web_search" on that same snapshot: the runtime treats your edit as web_search’s output, skips straight to agent, and your three results survive.)

8.8 Taking it to production

InMemorySaver is fine for learning and demos. A few things change when a graph like this runs for real, all of them Part III topics; none of them touch the nodes:

  • Use a durable checkpointer. InMemorySaver dies with the process. The durable options are a ladder, SqliteSaver for single-machine durability, PostgresSaver for production, and a Redis saver, each in its own langgraph-checkpoint-* package, each the same compile(checkpointer=...) swap. (Two things that swap does not carry: the SQL savers want a one-time .setup() to create their tables before the first run, and an async server wants the Async… variant of the class, not the sync one under await — Section 23.12 shows the error the sync one raises there.)
  • Tune when saves land, if you must. invoke takes a durability argument — "sync", "async" (the default), or "exit" — trading latency against how much of a run survives a crash. The Gold challenge runs all three.
  • Remember what “complete” means. Everything in State is written every superstep and kept until checkpointer.delete_thread(thread_id). Keep secrets and bulky payloads out of State, and plan a retention policy. “Written” means written in the clear: Chapter 26 closes by grepping a real key back out of a SqliteSaver file, and shows the serializer swap that stops it.

8.9 The same shape elsewhere

Commit the small step so a crash costs you the step and not the job: databases have called this a write-ahead log for forty years, and workflow engines call it durable execution. get_state_history is event sourcing read plainly — the trail is the log, and time travel is replay to an earlier offset.

Know the line between this and a workflow engine before you reach for either. Temporal replays your workflow code against a recorded history, which is why a Temporal workflow body must be deterministic — no direct reads of the system clock, no bare random numbers, no outside I/O. The SDK supplies workflow-safe versions of the first two, and side effects go into activities.2 LangGraph restores state and re-enters at a node boundary, so a node body may do as it likes.

8.10 What we learned

  • A checkpointer makes a graph resumable, as durably as the saver is. compile(checkpointer=...) auto-saves the full merged state after every superstep; nothing inside the nodes changes, and every invoke now needs a thread_id to file the snapshots under. How far that survives is the saver’s choice, not the graph’s: InMemorySaver for the length of a process, a persistent saver across restarts.
  • Resume continues; it doesn’t restart. invoke(None, config) picks up from the parked checkpoint — recovery granularity is one node, and earlier work is preserved.
  • Time travel forks. get_state_history walks the trail; update_state writes a change into a new checkpoint branched off an older one, and resuming from it runs a new line while the original stays intact.
  • A checkpoint is not long-term memory. Automatic, lossless, scoped to one thread. Cross-session memory is the Store (Chapter 17).

The next chapter uses the same machinery to stop on purpose: to put a human in the loop, we interrupt a run before a risky step, save the state, wait however long it takes for a person to approve, and resume from that checkpoint with their decision folded in.

New pieces in this chapter

Piece Usage
Type
InMemorySaver In-process checkpointer from langgraph.checkpoint.memory. InMemorySaver(); lives in memory — it can’t survive a process restart
Value
thread_id Config key in invoke’s config["configurable"] that files a run’s snapshots as one timeline. config={"configurable": {"thread_id": "run-001"}}; required on every invoke once a checkpointer is attached
API
compile(checkpointer=…) Keyword arg: attaches a checkpointer so the full merged state is auto-saved after every superstep. graph = builder.compile(checkpointer=InMemorySaver()); the only change — nodes and edges are untouched
graph.get_state() Return the latest snapshot for a thread. graph.get_state(config); a snapshot carries values, the next nodes still to run, and step metadata
graph.get_state_history() Yield every snapshot on a thread, newest first. list(graph.get_state_history(config)); reverse for a timeline; opens with two setup snapshots
graph.update_state() Write a change into a new checkpoint forked off an older one. graph.update_state(snap.config, {…}, as_node="agent"); resume the returned config with invoke(None, …)

Code in this chapter

File What it runs
code/ch06_save_resume.py A checkpointer makes the run durable: resume after a crash, and rewind to an older checkpoint to take a different path.

Challenge

🥉 Bronze — prove threads are isolated

Run two different questions on two different thread_ids through one compiled graph, then walk each thread’s get_state_history.

Confirm the timelines never touch: nothing on thread A carries the other thread’s question, and each thread’s latest snapshot is its own. (Watch out for the very first, pristine snapshot — it has no question yet.)

office hours Worked solution with tests: code/answers/ch06_thread_isolation.py.

🥈 Silver — prove resume doesn’t redo work

Put a call counter inside each expensive node, crash at generate, resume on the same thread, and confirm each expensive node ran once across the crash and the resume — not twice — while iterations never reset to zero.

(Gotcha you’ll hit: use a fresh thread_id per run, or a completed thread’s saved state short-circuits the next run.)

office hours Worked solution with tests: code/answers/ch06_resume_no_redo.py.

🥇 Gold — when does a checkpoint actually land?

Run the chapter’s loop graph once per durability mode — "sync", "async", "exit" — each on a fresh thread_id, and count the snapshots get_state_history holds afterwards.

graph.invoke(inputs, config=config, durability="sync")    # persist, then step
graph.invoke(inputs, config=config, durability="async")   # the default
graph.invoke(inputs, config=config, durability="exit")    # persist once, at the end

Then crash it: put a plain raise in generate and run all three modes again. What is parked on the thread afterwards, and what does a resume have to redo?

You’ve got it when you can say, for each mode, what a clean run leaves and what a crashed one leaves — and which of those two runs is the one that separates all three modes. Predict both before you run, then check against get_state_history. A raise is not a kill -9, either: say what that difference costs under each mode.

Hint: durability goes on invoke (and stream), not on compile — one compiled graph runs under all three modes.


  1. Pregel is the name of LangGraph’s execution engine, after Google’s graph-processing model of the same name (Malewicz et al., “Pregel: A System for Large-Scale Graph Processing,” SIGMOD 2010); the superstep comes from there too. A PregelTask is the engine’s record of one node execution: which node, what it returned (result), what it raised (error), and any interrupt() it is paused on.↩︎

  2. Temporal’s deterministic constraints: https://docs.temporal.io/workflows; the Python SDK’s workflow-safe time and random APIs: https://github.com/temporalio/sdk-python.↩︎