Checkpoints, Threads and Replay
Compile a LangGraph graph with SqliteSaver, kill the process mid-run and resume the thread, list its history with get_state_history, replay from an earlier checkpoint and fork it with update_state, and see why replay repeats side effects.
Contentsand lesson path
On this page
- The Reality of Process Failures
- Checkpoints, Threads and Time Travel
- Lab: Crash, Resume, Replay and Fork
- Verify Your Understanding
- Apply It
- Review Prompt
Lessons of Stateful Agent Graphs
- Agents as State Machines Concept · 15 min
- State, Nodes and Reducers Worked example · 20 min
- Lab: Routing, Cycles and Parallel Branches Lab · 25 min
- Checkpoints, Threads and Replay Lab · 25 min
- Graph Framework, Agent SDK or Plain Code? Concept · 15 min
- Check: Trace a Graph Execution Knowledge check · 8 questions
What you will learn
- Persist state with a checkpointer to resume a thread, inspect its history and replay from an earlier step.
Prerequisites: Agent Loops & ReAct
01. The Reality of Process Failures
An agent run can take minutes of tool calls or days of waiting for a person. If its state lives only in memory, one container restart or out-of-memory kill loses all of it, and the user starts again. Debugging is hard too: when the agent goes wrong at step 4, you want to see the exact state it had at step 3.
A checkpointer solves both problems. It saves the graph state after every step, so a run can continue after a crash and you can inspect, replay or change any earlier step. In this lab you use the real LangGraph APIs for that, and you also see the limits: replay runs code again, and a thread id is not a permission.
02. Checkpoints, Threads and Time Travel
Four ideas carry this lesson:
- Thread. You compile the graph with
builder.compile(checkpointer=...)and call it with a config such as{"configurable": {"thread_id": "t-1"}}. Every checkpoint of that run is stored under the thread id. Calling the graph again with the same id continues the same run; a new id starts a fresh one. - Checkpoint. After each super-step the checkpointer saves a full snapshot of the state, not a list of changes.
graph.get_state(config)returns the latest one as aStateSnapshot:values(the state),next(the nodes that will run next),config(which adds acheckpoint_id),metadata(including thestepnumber),parent_configandcreated_at.graph.get_state_history(config)returns every snapshot of the thread, newest first. - Replay. Invoking with input
Noneand a past snapshot's config, which contains itscheckpoint_id, continues from that point. Nodes before it are not run again; nodes after it are, including model calls and tools. - Fork.
graph.update_state(past_config, {"query": ...})writes a new checkpoint that branches from the past one with your change. The original history stays as it was.graph.invoke(None, new_config)then runs forward on the branch.
Replaying is not reproducing. A model may answer differently the second time, and every side effect after the checkpoint (an email, a payment, a database write) happens again. Replay against sandboxed tools, or make side-effecting nodes idempotent. For audit, keep a separate log of external effects: checkpoints record graph state, not what happened in the outside world.
A thread id is a lookup key, not an access control. Anyone who can pass a thread id to your API could read or resume that thread unless you check. Store the owner of each thread in your own table and check it on every read, resume, replay and fork. LangGraph looks up a checkpoint by thread id and checkpoint id together, so a checkpoint id from another thread finds nothing. Keep that binding if you ever build your own lookup by checkpoint id.
Three checkpointers cover most needs. They share one interface, so switching means changing the import and the constructor:
InMemorySaverships with LangGraph. It is ideal for tests and notebooks, and everything is lost when the process ends.SqliteSaveris in the separate packagelanggraph-checkpoint-sqlite. It writes to a local file: good for one machine, demos and this lab.PostgresSaveris inlanggraph-checkpoint-postgres. Use it when several workers or machines share threads. Callsetup()once to create its tables.
# pip install langgraph-checkpoint-postgres
import os
from langgraph.checkpoint.postgres import PostgresSaver
with PostgresSaver.from_conn_string(os.environ["CHECKPOINT_DB_URI"]) as saver:
saver.setup() # creates the checkpoint tables; run it before first use
graph = builder.compile(checkpointer=saver)03. Lab: Crash, Resume, Replay and Fork
The graph has four nodes in a line: plan → search → send_email → summarize. send_email is the external effect: it writes a row to an outbox table in your own database, app.db, so you can count emails. That database also holds the threads table with each thread's owner. With CRASH=1, summarize kills the process with os._exit(1), which skips all cleanup, much like a killed container.
Every command below is a new Python process. Only checkpoints.db (written by SqliteSaver) and app.db carry anything from one command to the next. The script passes durability="sync", which makes LangGraph write each checkpoint before the next step starts, so a crash in one step does not lose the steps before it. The default mode, "async", writes while the next step is already running.
You need Python 3.12 or later. The lab was tested with Python 3.12, langgraph 1.2.22 and langgraph-checkpoint-sqlite 3.1.3.
mkdir ckpt-lab && cd ckpt-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "langgraph==1.2.22" "langgraph-checkpoint-sqlite==3.1.3""""Checkpoints, threads, history, replay and fork with LangGraph and SqliteSaver.
Each command is a new process; only checkpoints.db and app.db survive between them.
python ckpt_lab.py start THREAD OWNER QUESTION (CRASH=1 kills summarize once)
python ckpt_lab.py history THREAD OWNER [--memory]
python ckpt_lab.py resume THREAD OWNER
python ckpt_lab.py replay THREAD OWNER NODE re-run from the checkpoint before it
python ckpt_lab.py fork THREAD OWNER NODE QUERY change query there, then run on
python ckpt_lab.py id THREAD OWNER NODE print that checkpoint's id
python ckpt_lab.py peek THREAD OWNER CHECKPOINT_ID"""
import os
import sqlite3
import sys
from typing import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import END, START, StateGraph
app = sqlite3.connect("app.db") # your own tables: thread owners, effects log
app.execute("CREATE TABLE IF NOT EXISTS threads (thread_id TEXT PRIMARY KEY, owner)")
app.execute("CREATE TABLE IF NOT EXISTS outbox (thread_id TEXT, body TEXT)")
class State(TypedDict, total=False):
thread: str
question: str
query: str
hits: int
emailed: bool
summary: str
def plan(s):
return {"query": s["question"].lower()}
def search(s): # a fake search tool: deterministic hit count
return {"hits": len(s["query"].split())}
def send_email(s): # an external effect: logged in the outbox, outside the graph
app.execute("INSERT INTO outbox VALUES (?, ?)", (s["thread"], s["query"]))
app.commit()
return {"emailed": True}
def summarize(s):
if os.environ.get("CRASH") == "1":
print("summarize: worker killed", flush=True)
os._exit(1) # a hard crash: no cleanup, no exception handling
return {"summary": f"{s['hits']} hits for '{s['query']}'"}
builder = StateGraph(State)
for name, node in [("plan", plan), ("search", search),
("send_email", send_email), ("summarize", summarize)]:
builder.add_node(name, node)
builder.add_edge(START, "plan")
builder.add_edge("plan", "search")
builder.add_edge("search", "send_email")
builder.add_edge("send_email", "summarize")
builder.add_edge("summarize", END)
def config(thread, owner): # a thread id is a lookup key, not a permission
sql = "SELECT owner FROM threads WHERE thread_id=?"
row = app.execute(sql, (thread,)).fetchone()
if row is None or row[0] != owner:
sys.exit(f"refused: {owner} cannot access {thread}")
return {"configurable": {"thread_id": thread}}
def before(graph, cfg, node): # newest checkpoint whose next node is NODE
for snap in graph.get_state_history(cfg): # newest first
if snap.next == (node,):
return snap.config # holds thread_id and checkpoint_id
sys.exit(f"no checkpoint before {node}")
def show(state):
print("summary:", state.get("summary"), "| emails sent:", emails(state["thread"]))
def emails(thread):
sql = "SELECT COUNT(*) FROM outbox WHERE thread_id=?"
return app.execute(sql, (thread,)).fetchone()[0]
def main(graph, command, args):
if command == "start":
thread, owner, question = args
app.execute("INSERT INTO threads VALUES (?, ?)", (thread, owner))
app.commit()
cfg = config(thread, owner)
show(graph.invoke({"thread": thread, "question": question}, cfg,
durability="sync")) # save each step before the next
elif command == "history":
cfg = config(*args[:2])
for snap in graph.get_state_history(cfg):
step, keys = snap.metadata["step"], sorted(snap.values)
print(f"step {step:>2} next={snap.next} values={keys}")
print("latest next:", graph.get_state(cfg).next)
elif command == "resume": # None = no new input: continue from the last checkpoint
show(graph.invoke(None, config(*args), durability="sync"))
elif command == "replay":
past = before(graph, config(*args[:2]), args[2])
show(graph.invoke(None, past, durability="sync"))
elif command == "fork":
past = before(graph, config(*args[:2]), args[2])
forked = graph.update_state(past, {"query": args[3]}) # a new checkpoint
show(graph.invoke(None, forked, durability="sync"))
elif command == "id":
past = before(graph, config(*args[:2]), args[2])
print(past["configurable"]["checkpoint_id"])
elif command == "peek": # the saver looks up (thread_id, checkpoint_id) together
cfg = config(*args[:2])
cfg["configurable"]["checkpoint_id"] = args[2]
print("values:", sorted(graph.get_state(cfg).values) or "not in this thread")
command, *args = sys.argv[1:]
if "--memory" in args: # InMemorySaver: fine for tests, empty in every new process
main(builder.compile(checkpointer=InMemorySaver()), command, args[:-1])
else:
with SqliteSaver.from_conn_string("checkpoints.db") as saver:
main(builder.compile(checkpointer=saver), command, args)Step 1: start a run that crashes. The process dies inside summarize, after send_email has already run.
CRASH=1 python ckpt_lab.py start t-1 acme "Late parcels in May"; echo "exit code: $?"summarize: worker killed
exit code: 1Step 2: inspect the history from a new process. The run before the crash saved one checkpoint per step. Step -1 is the input checkpoint: it shows values=[] because the input is still a pending write that the __start__ step applies. Each later checkpoint shows which keys the state had and which node was due next. The latest checkpoint says summarize is next. The same command with --memory uses InMemorySaver, which starts empty in every new process, so it finds nothing.
python ckpt_lab.py history t-1 acme
python ckpt_lab.py history t-1 acme --memorystep 3 next=('summarize',) values=['emailed', 'hits', 'query', 'question', 'thread']
step 2 next=('send_email',) values=['hits', 'query', 'question', 'thread']
step 1 next=('search',) values=['query', 'question', 'thread']
step 0 next=('plan',) values=['question', 'thread']
step -1 next=('__start__',) values=[]
latest next: ('summarize',)
latest next: ()Step 3: resume the thread. graph.invoke(None, config) with the same thread id and no new input continues from the latest checkpoint. Only summarize runs, so the email count stays at 1.
python ckpt_lab.py resume t-1 acmesummary: 4 hits for 'late parcels in may' | emails sent: 1Step 4: replay, then fork. replay finds the newest checkpoint whose next is send_email and invokes from its config. send_email and summarize run again, and the customer gets a second email. fork takes the checkpoint before search, changes query with update_state, and runs on from the new branch. The new query gives a different summary, and a third email goes out, because send_email comes after the fork point too.
python ckpt_lab.py replay t-1 acme send_email
python ckpt_lab.py fork t-1 acme search "late parcels in june 2026"summary: 4 hits for 'late parcels in may' | emails sent: 2
summary: 5 hits for 'late parcels in june 2026' | emails sent: 3Step 5: test access. A second tenant, globex, creates its own thread t-2. It is refused when it asks for acme's thread. It then passes a real checkpoint id from t-1 while naming its own thread, and get_state finds nothing, because the checkpointer looks up thread and checkpoint id together. The same id under t-1, by its owner, works.
python ckpt_lab.py start t-2 globex "Globex question"
python ckpt_lab.py history t-1 globex
ID=$(python ckpt_lab.py id t-1 acme search)
python ckpt_lab.py peek t-2 globex "$ID"
python ckpt_lab.py peek t-1 acme "$ID"summary: 2 hits for 'globex question' | emails sent: 1
refused: globex cannot access t-1
values: not in this thread
values: ['query', 'question', 'thread']Two lessons come out of these steps. Resume is safe here because send_email was checkpointed before the crash, so it did not run twice. Replay and fork are not safe by default: each one sent another real email. Checkpoints also help across deployments, with limits. Work since the last checkpoint runs again when a new worker resumes the thread, and a new version of the graph may not understand state saved by the old one, so plan state changes like database migrations.
04. Verify Your Understanding
05. Apply It
This is the persistence half of the skill's practice project. In your graph agent:
- Compile with
SqliteSaverorPostgresSaver, kill the process mid-run, and resume the thread withinvoke(None, config). - Use
get_state_historyto find the checkpoint before your tool node, fork it withupdate_stateand a changed input, and compare the two branches. - Route every external effect through an outbox or an idempotency key, and show that a replay does not repeat it.
- Keep only plain, serialisable data in state (ids, not open connections), and decide how long to keep old checkpoints.
06. Review Prompt
Without looking back, explain what a thread and a checkpoint are, and list four fields of a StateSnapshot. Describe the calls that resume a thread after a crash, list its history, replay from an earlier checkpoint and fork it. Then explain why resume did not send a second email in the lab but replay did, when you would use InMemorySaver, SqliteSaver or PostgresSaver, and why a thread id must not be treated as a permission.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.