Velamuvi AIAcademy
LangGraph

Lesson 6 of 11 · Agents

Checkpoints and Persistence

Save LangGraph state after every step: checkpointers, threads, memory across calls, state history, resuming after a crash, and SQLite or Postgres savers.

  • 8 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Add a checkpointer so a graph saves its state after every step
  • Use thread IDs to keep conversations separate
  • Inspect the current state and the history of checkpoints
  • Resume a failed run from its last checkpoint without repeating work
  • Choose a durable checkpointer for production

Saving state after every step

So far each invoke started from nothing and forgot everything afterwards. A checkpointer changes that.

Memory across invocations

Compile with a checkpointer and pass a thread_id in the config:

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

def assistant(state: MessagesState) -> dict:
    """A rule-based stand-in for a model: it remembers order numbers from earlier messages."""
    said = " ".join(m.content for m in state["messages"] if m.type == "human")
    orders = re.findall(r"A-\d+", said)
    reply = f"Order {orders[-1]} is out for delivery today." if orders else "Which order number is it?"
    return {"messages": [("ai", reply)]}

builder = StateGraph(MessagesState)
builder.add_node("assistant", assistant)
builder.add_edge(START, "assistant")
builder.add_edge("assistant", END)
graph = builder.compile(checkpointer=InMemorySaver())     # save the state after every step

mei = {"configurable": {"thread_id": "mei"}}             # one thread per conversation
tom = {"configurable": {"thread_id": "tom"}}

graph.invoke({"messages": [("user", "Hi, my order is A-881.")]}, mei)
print("Mei:", graph.invoke({"messages": [("user", "Where is it?")]}, mei)["messages"][-1].content)
print("Tom:", graph.invoke({"messages": [("user", "Where is it?")]}, tom)["messages"][-1].content)
print("Messages saved for Mei:", len(graph.get_state(mei).values["messages"]))
Output
Mei: Order A-881 is out for delivery today.
Tom: Which order number is it?
Messages saved for Mei: 4

Mei's second message only says “Where is it?”, but her thread already holds the first message, so the assistant knows the order. Tom's thread is separate and empty. (A rule-based node stands in for a model here; with a model node, this is exactly how a LangGraph chatbot remembers a conversation.) graph.get_state(config) returns the current checkpoint: its values, and next, the nodes still to run.

Recovering from a crash

Checkpoints also make long jobs safe. If a step fails, the steps before it are already saved:

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

class State(TypedDict):
    invoice: str
    extracted: dict
    posted: bool

attempts = {"post": 0}

def extract(state: State) -> dict:
    print("  extract runs")
    return {"extracted": {"supplier": "Papelaria Lda", "total": 420.0}}

def post(state: State) -> dict:
    attempts["post"] += 1
    print(f"  post runs (attempt {attempts['post']})")
    if attempts["post"] == 1:
        raise ConnectionError("accounting system timed out")   # a crash part-way through
    return {"posted": True}

builder = StateGraph(State)
builder.add_node("extract", extract)
builder.add_node("post", post)
builder.add_edge(START, "extract")
builder.add_edge("extract", "post")
builder.add_edge("post", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "invoice-881"}}

try:
    graph.invoke({"invoice": "INV-881.pdf", "posted": False}, config)
except ConnectionError as e:
    print("Failed:", e)
    print("Next step saved in the checkpoint:", graph.get_state(config).next)

print("Resuming...")
result = graph.invoke(None, config)          # None = continue from the last checkpoint
print(result)
Output
  extract runs
  post runs (attempt 1)
Failed: accounting system timed out
Next step saved in the checkpoint: ('post',)
Resuming...
  post runs (attempt 2)
{'invoice': 'INV-881.pdf', 'extracted': {'supplier': 'Papelaria Lda', 'total': 420.0}, 'posted': True}

Invoking with None as the input means “continue this thread from its last checkpoint”. extract did not run again: its result was already saved. With model calls, that saves money; with actions such as sending emails, it prevents doing them twice.

Here is the mechanism in plain Python:

Try it yourselfPython
import copy

# What a checkpointer does, in plain Python: after every step, save a copy of the state
# and the next node, per thread. A crashed run resumes from its last checkpoint.
CHECKPOINTS = {}                                       # thread_id -> list of (step, next_node, state)

STEPS = ["extract", "validate", "post"]
def run_node(name, state, fail_on=None):
    if name == fail_on:
        raise ConnectionError(f"{name} failed")
    return {**state, name: "done"}

def run(thread_id, state=None, fail_on=None):
    saved = CHECKPOINTS.setdefault(thread_id, [])
    if state is None:                                  # resume: continue after the last checkpoint
        step, next_node, state = saved[-1]
        state = copy.deepcopy(state)
        start = STEPS.index(next_node)
    else:
        start = 0
    for i in range(start, len(STEPS)):
        state = run_node(STEPS[i], state, fail_on)
        nxt = STEPS[i + 1] if i + 1 < len(STEPS) else None
        saved.append((len(saved), nxt, copy.deepcopy(state)))   # save after every step
        print(f"  [{thread_id}] {STEPS[i]} done, checkpoint saved, next={nxt}")
    return state

try:
    run("invoice-881", {"invoice": "INV-881"}, fail_on="post")
except ConnectionError as e:
    print("Crash:", e)
print("Resume:")
print(run("invoice-881"))

Looking back through history

Every checkpoint is kept, so you can see how the state evolved:

# Every step's checkpoint is kept: list them, newest first
for snapshot in graph.get_state_history(config):
    print(f"step {snapshot.metadata['step']:>2}  next={snapshot.next}  posted={snapshot.values.get('posted')}")
Output
step  2  next=()  posted=True
step  1  next=('post',)  posted=False
step  0  next=('extract',)  posted=False
step -1  next=('__start__',)  posted=None

This history is a powerful debugging tool, and it enables time travel: you can continue a thread from an earlier checkpoint by passing that checkpoint's config, or edit the state with graph.update_state(config, {...}) and continue from there. The next lesson uses state edits for human review.

Durable checkpointers

InMemorySaver loses everything when the program stops, which is fine for learning and tests. For real applications, use a database-backed checkpointer:

from langgraph.checkpoint.sqlite import SqliteSaver

with SqliteSaver.from_conn_string("checkpoints.db") as saver:     # state survives restarts
    graph = builder.compile(checkpointer=saver)
    graph.invoke({"invoice": "INV-882.pdf", "posted": False}, {"configurable": {"thread_id": "invoice-882"}})
    print(graph.get_state({"configurable": {"thread_id": "invoice-882"}}).values["posted"])
Output
True

SqliteSaver (package langgraph-checkpoint-sqlite) stores checkpoints in a local file, good for single-machine apps. For web services with several servers, use PostgresSaver (package langgraph-checkpoint-postgres) or another shared database. The graph code doesn't change; only the checkpointer does.

Common mistakes

Practice exercise

Find a thread's latest checkpoint and decide whether it finished or where it would resume, as graph.get_state does.

Your solutionPython
checkpoints = [
    {"step": 0, "next": "extract", "values": {"invoice": "INV-7"}},
    {"step": 2, "next": None, "values": {"invoice": "INV-7", "extracted": True, "posted": True}},
    {"step": 1, "next": "post", "values": {"invoice": "INV-7", "extracted": True}},
]

# Find the checkpoint with the highest step. Print "finished" if its next is None,
# otherwise print "resume at <next>". Then print its values.
Knowledge check

A graph with a checkpointer fails at its third node. What does graph.invoke(None, config) do?

Summary

  • A checkpointer saves the state after every step; compile with compile(checkpointer=...).
  • A thread_id separates conversations or jobs; the same ID continues the same state.
  • get_state shows the current values and next nodes; get_state_history lists every checkpoint.
  • invoke(None, config) resumes after a failure without repeating finished steps.
  • Use SQLite or Postgres checkpointers in real applications, and treat checkpoints as personal data.

Next: human-in-the-loop.

Finished reading? Tick it off to track your progress.