08F.11 Persistence, Durable Execution and Memory
A language model remembers nothing. Lesson 02.7 said so, and 08B.2 built memory systems on top of that fact from scratch. A real product still has to answer "what did I say yesterday?", survive a deploy in the middle of a task, wait three days for a human to click approve, let a user rewind a conversation and try a different branch, and remember that this customer prefers formal replies. In LangGraph all of that rests on two pieces of machinery, and this lesson teaches both. The checkpointer saves a snapshot of the graph's state after every step, per thread, which gives you conversation continuity, pause and resume, crash recovery and time travel. The store keeps application-defined memories in a key-value space that is shared across threads, with optional semantic search. Around them sit the rules that make a restarted run correct (nodes re-run from their first line, so they must be idempotent), the knobs that decide how much is saved and when (durability modes, serializers, encryption, pruning), and the practical question of what to do when a thread's history grows too long for the model (trimming, deleting and summarizing messages).
Almost everything here runs on your laptop without a key. The samples use scripted stand-in models, in-memory and SQLite checkpointers, and a small hand-made embedding function, and the outputs you see are the real outputs of those runs on 14 November 2026. Only the Postgres, real-embedding and real-model samples are illustrative.
What you'll learn
- The two kinds of memory in LangGraph, what each one saves, where each is scoped, and which problem each solves
- Threads and
thread_id: how a thread continues, the four ways to callinvokeon one (new input, retry, resume, replay), and what happens with nothread_id - Checkpoints: what a super-step boundary saves, the
StateSnapshotfields, checkpoint metadata, namespaces, and pending writes that save the work of nodes that succeeded when a sibling failed - Reading and changing history:
get_state,get_state_history(newest first, withfilter,beforeandlimit), listing every thread,update_statewithas_node, andbulk_update_state - Time travel: replay (re-run from an old checkpoint) and fork (change the state first), what re-executes, why interrupts fire again, and the tree that history becomes
- Durability modes (
exit,async,sync) shown by killing a process, and the first-checkpoint caveat - The durable-execution rules: at-least-once execution, idempotency keys,
@taskfor work inside a node, determinism and the ordering trap, and what to do when you change code under in-flight threads - The checkpointer implementations:
InMemorySaver,SqliteSaverandAsyncSqliteSaver,PostgresSaverandAsyncPostgresSaver, the other backends,setup(), deleting and pruning, checkpoint growth andDeltaChannel, and how to test a custom saver - Serializers: what
JsonPlusSerializerround-trips, the pickle fallback, strict msgpack mode, and encrypting checkpoints at rest - The Store:
put,get,search,delete,list_namespaces, namespaces, filters, TTL,InMemoryStore,SqliteStoreandPostgresStore, and reaching the store from nodes, tools andcreate_agent - Semantic search over memories: the
indexconfiguration, per-item control, scores, and the traps - Memory design: semantic, episodic and procedural memory, profile versus collection, writing in the hot path versus in the background
- Managing the short-term memory of a long thread:
trim_messages,RemoveMessage, a summarizing node,SummarizationMiddleware, and why deleted messages still sit in old checkpoints - Legacy memory classes and the names you will meet in old tutorials, a production checklist and a failure gallery with the real error messages
What you don't need
- An API key, a database server or Docker. The Postgres and real-embedding samples are labelled illustrative and are not required to follow the lesson.
- The theory of agent memory. Lesson 08B.2 owns the taxonomy, write policies, forgetting, safety and evaluation of memory systems and builds a complete
MemoryStoreby hand. This lesson owns how LangGraph implements the storage and the plumbing, and links back instead of repeating it. interrupt,Command(resume=...)and approval flows. Lesson 08F.12 owns them. Here they appear only where they interact with checkpoints (resume rules, replay).- Subgraphs and multi-agent persistence in depth (08F.13), the Functional API (08F.14), and LangSmith Deployment (11A.5). Each gets a pointer in Part 11.
- The graph basics. Lesson 08F.10 taught state, reducers, nodes, edges and super-steps; this lesson uses them without re-teaching.
Setup
You need Python 3.11 or newer and uv (see 08F.4, Part 5 for the project setup; the first uv add fails outside a project, so create one first).
uv init memory-lab --bare --python 3.13 && cd memory-lab # first time only
uv add langchain langgraph-checkpoint-sqlite # langchain brings langgraph, langgraph-checkpoint and langgraph-prebuilt
uv add numpy pycryptodome # optional: faster InMemoryStore search (and a fake-embedding sample), AES encryption (Part 6)
uv add "psycopg[binary,pool]" langgraph-checkpoint-postgres # only for the illustrative Postgres samples (Part 5)
uv add python-dotenv langchain-openai # only for the illustrative real-embedding and real-model samples
# or with pip: pip install langchain langgraph-checkpoint-sqlite numpy pycryptodomelanggraph-checkpoint-sqlite pulls in aiosqlite and sqlite-vec. The in-memory saver and store ship inside langgraph-checkpoint, which langchain installs for you. No == pins are needed: uv records what it resolved in its lockfile. Two samples in Part 10 reuse fakes.py, the scripted-model helper from 08F.8, Part 1.3; copy it next to them. Run each sample with uv run python file.py. The samples that write a database file (chat_memory.sqlite, memory_store.sqlite) create it in the folder you run them from, and you can delete it afterwards.
Versions (current at time of writing, verified 14 November 2026 against PyPI and by running the samples): langgraph 1.2.22, langgraph-checkpoint 4.3.2, langgraph-checkpoint-sqlite 3.1.3, langgraph-checkpoint-postgres 3.2.1, langchain 1.5.0, langchain-core 1.8.0, langgraph-prebuilt 1.1.2. The sample runs resolved aiosqlite 0.22.1, ormsgpack 1.13.1 and, for Postgres, psycopg 3.3.9. These packages release often, and the third-party and AWS backends have their own cadence: check 08F.4, 5.10 for upgrading on purpose, and the pages in Further resources before you rely on an option this lesson marks "check the docs".
Free practice path. The scripted models make every graph run with no key. GenericFakeChatModel and the helper classes in fakes.py replay a fixed list of messages; a plain class with an invoke method works just as well when you only need a stand-in. What the fakes cannot show is real model behaviour (whether a summary is good, whether an extractor finds the right facts), so Exercise 8 sends you to a real model for that. For a free local model, lesson 03.1, Part 12 covers the Ollama stand-in.
What you must be able to do after this lesson#
- Continue a conversation on a thread with a checkpointer
- Read and update the state history of a thread
- Choose a checkpointer for development and production
- Store and search long-term memory in the Store
- Explain why durable execution needs idempotent side effects
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "The bot forgets everything on the next message." | Part 1: no checkpointer, or a new thread_id every time |
| "What is a thread, and what is a checkpoint?" | Part 2 |
| "Restart the server, and the pending approval is gone." | 5.1 and 5.2: an in-memory saver loses everything |
| "Let the user go back and try a different answer." | Part 3 |
| "The charge ran twice after the retry." | Part 4 |
"Can we use Postgres for checkpoints? Do we run setup()?" |
5.3 |
| "The checkpoint table is huge." | 5.6 |
| "Can checkpoints contain customer data? Encrypt them." | Part 6 |
| "Remember the customer's preferences across conversations." | Part 7 |
| "Search memories by meaning, not by exact key." | Part 8 |
| "Which memories should the agent write, and when?" | Part 9 |
| "The thread is 200 messages long and the model is slow and expensive." | Part 10 |
"This tutorial uses ConversationBufferMemory / RunnableWithMessageHistory / MemorySaver." |
Part 11 |
| "How do we ship this?" | Part 12 |
Part 1: Two kinds of memory, and a first persistent chat#
1.1 What "memory" means in LangGraph#
A graph run is a function call: state goes in, state comes out, and when the call returns the process forgets it. LangGraph adds memory by writing to a database at defined moments, and it offers exactly two mechanisms. They are easy to confuse because both are called "memory" in the docs, so fix the difference first.
| Checkpointer | Store | |
|---|---|---|
| What it persists | Snapshots of the graph state | Application-defined key-value documents |
| Scope | One thread | Across threads (and across users, if you want that) |
| Memory type | Short-term, thread-scoped | Long-term, cross-thread |
| Typical use | Conversation continuity, human-in-the-loop pauses, time travel, crash recovery | User preferences, learned facts, shared knowledge, past examples |
| Who writes it | The runtime, automatically, after every step | Your code, on purpose, from a node, a tool or the application |
| How you address it | thread_id in the run config |
A namespace (a tuple of strings) and a key |
| Attach it with | compile(checkpointer=...) |
compile(store=...) |
You can use either, both or neither. A stateless pipeline needs neither. A chatbot that must continue a conversation needs a checkpointer. An assistant that should remember a customer's preferences next month, in a new conversation, needs a store as well. When you run on a LangSmith Agent Server (Part 11), the platform supplies both and you configure neither.
flowchart LR
user(["user_id: ada"]) --> app["your app"]
app -- "thread_id: mon" --> g1["graph run 1"]
app -- "thread_id: tue" --> g2["graph run 2"]
subgraph short ["Checkpointer: short-term, one thread"]
c1[("thread mon<br/>checkpoint 1, 2, 3 ...")]
c2[("thread tue<br/>checkpoint 1, 2 ...")]
end
subgraph long ["Store: long-term, across threads"]
s1[("namespace (ada, memories)<br/>key, value, embedding")]
end
g1 <--> c1
g2 <--> c2
g1 <--> s1
g2 <--> s1Each thread reads and writes only its own checkpoints. Both threads read and write the same namespace in the store, because both belong to the same user. That is the whole architecture; the rest of the lesson fills in the details.
1.2 A first persistent chat#
The smallest useful demonstration: the same graph compiled twice, once without and once with a checkpointer. The "model" is a plain class that reports how many user messages it was shown, so the effect of memory is visible without any provider.
# p01_threads.py: a chat graph with a checkpointer: same thread_id remembers, a new thread_id starts empty
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import START, MessagesState, StateGraph
# a scripted "model": it answers by counting what it was shown, so we can see what memory did
class CountingModel:
def invoke(self, messages):
humans = [m.content for m in messages if m.type == "human"]
return AIMessage(content=f"I have seen {len(humans)} user message(s): {humans}")
model = CountingModel()
def chat(state: MessagesState):
return {"messages": [model.invoke(state["messages"])]}
builder = StateGraph(MessagesState)
builder.add_node("chat", chat)
builder.add_edge(START, "chat")
no_memory = builder.compile() # no checkpointer
graph = builder.compile(checkpointer=InMemorySaver()) # with a checkpointer
def say(g, text, thread=None):
config = {"configurable": {"thread_id": thread}} if thread else None
out = g.invoke({"messages": [{"role": "user", "content": text}]}, config)
return out["messages"][-1].content
print("without a checkpointer:")
print(" ", say(no_memory, "Hi, I am Bob"))
print(" ", say(no_memory, "What is my name?"))
print("with a checkpointer, thread 'a':")
print(" ", say(graph, "Hi, I am Bob", "a"))
print(" ", say(graph, "What is my name?", "a"))
print("thread 'b' is separate:")
print(" ", say(graph, "What is my name?", "b"))
print("thread 'a' again, third turn:")
print(" ", say(graph, "Thanks", "a"))without a checkpointer:
I have seen 1 user message(s): ['Hi, I am Bob']
I have seen 1 user message(s): ['What is my name?']
with a checkpointer, thread 'a':
I have seen 1 user message(s): ['Hi, I am Bob']
I have seen 2 user message(s): ['Hi, I am Bob', 'What is my name?']
thread 'b' is separate:
I have seen 1 user message(s): ['What is my name?']
thread 'a' again, third turn:
I have seen 3 user message(s): ['Hi, I am Bob', 'What is my name?', 'Thanks']Read the output in three groups.
- Without a checkpointer the second call has no idea there was a first call: each
invokesees exactly one user message. The state your graph returns lives only for the duration of the call. - With a checkpointer and
thread_id="a"the second call sees both user messages and the third sees three. You did not append anything yourself: you passed only the new message, and LangGraph loaded the saved state, applied your input to it through the reducers (hereadd_messageson themessageskey, 08F.10, 3.4), ran the graph and saved the result. - A different
thread_idis a different, empty conversation. Thread"b"sees one message even though thread"a"already has several.
Three rules fall out of this sample, and every later part builds on them.
- Memory exists only if you compile with a checkpointer and pass the same
thread_idagain. There is no default checkpointer and no automatic thread. Forget either half and the graph silently behaves as in the first group. - A thread never resets by itself. Input is always applied on top of the saved state. To start fresh, use a new
thread_id. To shrink a thread you must change its state (Part 10). - The
thread_idgoes inconfig["configurable"]. That is the second positional argument ofinvokeandstream. (context=, the per-run immutable data from 08F.10, Part 9, is a different channel and is not saved in checkpoints.)
1.3 The two pieces in one compile()#
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
checkpointer = InMemorySaver()
store = InMemoryStore()
graph = builder.compile(checkpointer=checkpointer, store=store)
graph.invoke(
{"messages": [{"role": "user", "content": "Hi, my name is Bob."}]},
{"configurable": {"thread_id": "thread-1"}},
)This fragment is the shape from the docs, and builder is any StateGraph builder from 08F.10. The checkpointer is needed for human-in-the-loop interrupts, memory across turns, time travel and fault tolerance. The store is optional. Both calls accept None (the default), a real object, and, for a subgraph, True and False with special meanings (11.2). Passing anything else, a file name for example, fails at compile():
TypeError: Invalid checkpointer provided. Expected an instance of `BaseCheckpointSaver`, `True`, `False`, or `None`. Received str. Pass a proper saver (e.g., InMemorySaver, AsyncPostgresSaver).A frequent beginner mistake is compile(checkpointer="sqlite.db"): the saver is an object you construct (Part 5), not a path.
Part 2: Threads and checkpoints#
2.1 Threads and thread_id#
A thread is a sequence of runs that share accumulated state. The checkpointer uses the thread_id as its primary key: every checkpoint row carries it, and every read filters by it. You pass it in the run config.
config = {"configurable": {"thread_id": "support-ticket-8841"}}
graph.invoke({"messages": [...]}, config)Practical rules for choosing ids:
- Make it stable and opaque. A conversation id your UI keeps, or a UUID you generate once at the start of a conversation and store with the conversation record. Do not put personal data in it: it appears in logs, traces and database rows.
- Keep it short for Postgres. The docs' troubleshooting note says to keep
thread_idunder 255 characters. A UUID is 36. - One thread per independent conversation or workflow instance, not one per user. A user with three open support tickets has three threads. What is shared between them (the user's preferences) goes in the store (Part 7).
- Time-ordered ids are convenient. The docs generate them with
uuid7, whichlangchain-coreprovides:from langchain_core.utils.uuid import uuid7, thenstr(uuid7()). A UUID v7 starts with a timestamp, so ids sort roughly by creation time. - Ids that are not strings are converted. Passing
thread_id=42works, andget_statefinds it under"42". Prefer strings anyway so that what you store and what you query always match.
What happens when you forget the thread_id is worth seeing once, together with the other thread-related errors. The sample below also shows the first of two things this part needs: how a crash in one branch of a run is recovered.
# p03_resume_errors.py: crash in one parallel branch, pending writes, invoke(None) to resume; plus the errors you meet
from operator import add
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
calls = {"fast": 0, "flaky": 0, "join": 0}
fail_flaky = {"on": True}
class State(TypedDict):
log: Annotated[list[str], add]
def fast(state: State):
calls["fast"] += 1
return {"log": ["fast done"]}
def flaky(state: State):
calls["flaky"] += 1
if fail_flaky["on"]:
raise RuntimeError("upstream API timed out")
return {"log": ["flaky done"]}
def join(state: State):
calls["join"] += 1
return {"log": [f"join saw {len(state['log'])} entries"]}
graph = (
StateGraph(State)
.add_node("fast", fast).add_node("flaky", flaky).add_node("join", join)
.add_edge(START, "fast").add_edge(START, "flaky")
.add_edge(["fast", "flaky"], "join").add_edge("join", END)
.compile(checkpointer=InMemorySaver())
)
config = {"configurable": {"thread_id": "t1"}}
try:
graph.invoke({"log": []}, config)
except RuntimeError as exc:
print("run failed:", exc)
print("calls after failure:", calls)
snap = graph.get_state(config)
print("next:", snap.next)
for task in snap.tasks:
print(" task", task.name, "error:", task.error, "| result:", task.result)
fail_flaky["on"] = False # the outage is over
out = graph.invoke(None, config) # None = "continue from the latest checkpoint"
print("after invoke(None):", out)
print("calls after resume:", calls)
# resuming a finished thread returns the saved result without running anything
print("invoke(None) again:", graph.invoke(None, config) == out, calls)
# --- errors ---------------------------------------------------------------------
for label, thunk in [
("no config at all", lambda: graph.invoke({"log": []})),
("config without configurable", lambda: graph.invoke({"log": []}, {"tags": ["x"]})),
("configurable without thread_id", lambda: graph.invoke({"log": []}, {"configurable": {"user": "x"}})),
("invoke(None) on an unknown thread", lambda: graph.invoke(None, {"configurable": {"thread_id": "never-used"}})),
]:
try:
r = thunk()
print(f"{label}: no error, returned {r}")
except Exception as exc:
print(f"{label}: {type(exc).__name__}: {str(exc)[:110]}")run failed: upstream API timed out
calls after failure: {'fast': 1, 'flaky': 1, 'join': 0}
next: ('flaky',)
task fast error: None | result: {'log': ['fast done']}
task flaky error: RuntimeError('upstream API timed out') | result: None
after invoke(None): {'log': ['fast done', 'flaky done', 'join saw 2 entries']}
calls after resume: {'fast': 1, 'flaky': 2, 'join': 1}
invoke(None) again: True {'fast': 1, 'flaky': 2, 'join': 1}
no config at all: ValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, checkpoint_ns, checkpoint_i
config without configurable: ValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, checkpoint_ns, checkpoint_i
configurable without thread_id: KeyError: 'thread_id'
invoke(None) on an unknown thread: EmptyInputError: Received no input for __start__The last four lines are the errors, and they are worth memorizing:
- No
configurableat all raisesValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, checkpoint_ns, checkpoint_id. This is the error you get the first time you add a checkpointer and forget the config. - A
configurabledict withoutthread_idraises a bareKeyError: 'thread_id', a less helpful message for the same mistake. A typo such as"threadId"produces it. invoke(None, config)on a thread with no checkpoint raisesEmptyInputError: Received no input for __start__. It means "continue", and there is nothing to continue. It also appears if the first run crashed before its first checkpoint became durable (2.6 and 4.1).
2.2 Four ways to call invoke on a thread#
One thread, four different intentions, four different calls. The docs' table, reproduced because mixing them up causes real bugs:
| Goal | Call | What happens |
|---|---|---|
| Submit new input | graph.invoke(input, config) |
Applies input to the saved state through the reducers and starts from the entry point |
| Continue after an error | graph.invoke(None, config) |
Loads the latest checkpoint and retries the unfinished work (leave out checkpoint_id) |
Answer an interrupt() |
graph.invoke(Command(resume=answer), config) |
Supplies the interrupt's return value; the interrupted node restarts from its beginning (08F.12) |
| Replay history | graph.invoke(None, snapshot.config) |
Uses a snapshot from get_state_history() and re-executes the nodes after that checkpoint (Part 3) |
Two consequences you can see in the sample above:
- Resuming a finished thread is harmless.
invoke(None, config)on a thread whose latest checkpoint has no unfinished work returns the saved result and runs no node (the sample printsTrueand the call counters do not move). - New input never clears the thread. To start with empty state, use a new
thread_id.
flowchart TD
start(["invoke or stream"]) --> load["load latest checkpoint for thread_id"]
load --> pending{"unfinished work<br/>or new input?"}
pending -- "new input" --> reducers["apply input through reducers<br/>start at the entry point"]
pending -- "None or Command(resume)" --> restore["restore pending writes<br/>re-run only unfinished tasks"]
reducers --> step["run a super-step"]
restore --> step
step --> save["write checkpoint<br/>exit, async or sync"]
save --> more{"more nodes?"}
more -- "yes" --> step
more -- "no" --> finish(["return output"])
step -. "crash or interrupt" .-> halt(["process stops<br/>checkpoint stays"])
halt -. "later: invoke(None, config)" .-> start2.3 What a checkpoint is: super-steps, snapshots and the four-checkpoint run#
A checkpoint is saved at every super-step boundary (the unit of execution from 08F.10, 1.3: plan, execute in parallel, apply writes). A checkpoint is therefore not saved in the middle of a node, which is the root of the durable-execution rules in Part 4.
The clearest way to see this is to run a two-node graph and list what was saved.
# p02_checkpoints.py: one run, four checkpoints: what a snapshot holds and how history is ordered
from operator import add
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
foo: str
bar: Annotated[list[str], add]
def node_a(state: State):
return {"foo": "a", "bar": ["a"]}
def node_b(state: State):
return {"foo": "b", "bar": ["b"]}
graph = (
StateGraph(State)
.add_node("node_a", node_a)
.add_node("node_b", node_b)
.add_edge(START, "node_a")
.add_edge("node_a", "node_b")
.add_edge("node_b", END)
.compile(checkpointer=InMemorySaver())
)
config = {"configurable": {"thread_id": "1"}}
graph.invoke({"foo": "", "bar": []}, config)
latest = graph.get_state(config)
print("get_state type:", type(latest).__name__)
print("fields:", latest._fields)
print("values:", latest.values, "| next:", latest.next)
print("config keys:", sorted(latest.config["configurable"]))
print("metadata:", latest.metadata)
print("parent_config is None:", latest.parent_config is None)
print()
history = list(graph.get_state_history(config))
print("number of checkpoints:", len(history), "(index 0 is the NEWEST)")
for i, snap in enumerate(history):
m = snap.metadata
print(f"[{i}] step={m['step']:>2} source={m['source']:<5} next={snap.next!s:<14} values={snap.values}")
# time ordering and parent chain
ids = [s.config["configurable"]["checkpoint_id"] for s in history]
print("ids sorted newest-first:", ids == sorted(ids, reverse=True))
print("parent of [0] is [1]:", history[0].parent_config["configurable"]["checkpoint_id"] == ids[1])
print("created_at is an ISO string:", isinstance(history[0].created_at, str))
# filter / limit / before
print("limit=2:", [s.metadata["step"] for s in graph.get_state_history(config, limit=2)])
print("before [1]:", [s.metadata["step"] for s in graph.get_state_history(config, before=history[1].config)])
print("filter source=input:", [s.metadata["step"] for s in graph.get_state_history(config, filter={"source": "input"})])
# a specific checkpoint
past = graph.get_state({"configurable": {"thread_id": "1", "checkpoint_id": ids[2]}})
print("checkpoint [2] values:", past.values, "next:", past.next)get_state type: StateSnapshot
fields: ('values', 'next', 'config', 'metadata', 'created_at', 'parent_config', 'tasks', 'interrupts')
values: {'foo': 'b', 'bar': ['a', 'b']} | next: ()
config keys: ['checkpoint_id', 'checkpoint_ns', 'thread_id']
metadata: {'source': 'loop', 'step': 2, 'parents': {}}
parent_config is None: False
number of checkpoints: 4 (index 0 is the NEWEST)
[0] step= 2 source=loop next=() values={'foo': 'b', 'bar': ['a', 'b']}
[1] step= 1 source=loop next=('node_b',) values={'foo': 'a', 'bar': ['a']}
[2] step= 0 source=loop next=('node_a',) values={'foo': '', 'bar': []}
[3] step=-1 source=input next=('__start__',) values={'bar': []}
ids sorted newest-first: True
parent of [0] is [1]: True
created_at is an ISO string: True
limit=2: [2, 1]
before [1]: [0, -1]
filter source=input: [-1]
checkpoint [2] values: {'foo': '', 'bar': []} next: ('node_a',)A two-node graph produces four checkpoints, numbered by metadata["step"]:
| Index in history | step |
source |
next |
Meaning |
|---|---|---|---|---|
| 3 (oldest) | -1 | input |
('__start__',) |
Your input was received; no node has run |
| 2 | 0 | loop |
('node_a',) |
The input has been applied to the channels; node_a is about to run |
| 1 | 1 | loop |
('node_b',) |
node_a has run |
| 0 (newest) | 2 | loop |
() |
node_b has run; nothing is left |
A run of N sequential nodes saves N + 2 checkpoints. The empty next tuple is how you recognize a finished run. A checkpoint with a non-empty next is resumable: it says "these nodes are what you would run next".
A few details visible in the output:
- Index 3 shows
values={'bar': []}, withoutfoo. At the input checkpoint the channels have not all been populated yet (index 2, one step later, shows both keys). Do not build logic on the exact contents of the first checkpoint. historyis newest first, andhistory[0]is the same asget_state(config). This is the opposite of the order most people expect.- The checkpoint ids sort. They are time-ordered (the docs describe them as ULID or UUID-like, "larger values are newer"), which is why
sorted(ids, reverse=True)equals the history order. Do not parse them. parent_configpoints at the previous checkpoint, so history is a linked list (a tree, once you fork, Part 3).created_atis an ISO 8601 string.
2.4 The StateSnapshot and its metadata#
get_state and get_state_history return a StateSnapshot, a named tuple. Its fields, as printed by the sample above and as defined in the source of langgraph 1.2.22:
| Field | Type | Meaning |
|---|---|---|
values |
dict (the state) | The channel values at this checkpoint |
next |
tuple[str, ...] |
The nodes that would run next; () means finished |
config |
dict | configurable with thread_id, checkpoint_ns and checkpoint_id: pass it back to invoke or get_state to address this exact checkpoint |
metadata |
dict | source, step, parents and, in other versions and runs, more (see below) |
created_at |
str or None |
ISO 8601 timestamp |
parent_config |
dict or None |
The previous checkpoint's config; None for the first |
tasks |
tuple[PregelTask, ...] |
What is pending or has run at this checkpoint: each task has id, name, path, error, interrupts, state and result |
interrupts |
tuple[Interrupt, ...] |
Interrupts raised in this step (see 2.4.1) |
The docs' field table omits interrupts and the path and result attributes of a task. The source has them, and the printed fields tuple above confirms it.
Metadata keys. In the sample the metadata printed as {'source': 'loop', 'step': 2, 'parents': {}}. The documented set of source values is input, loop and update; the source of 1.2.22 also has fork, which you will see in Part 3 (a replay writes a fork checkpoint). step is -1 for the input checkpoint and 0 for the first loop checkpoint. parents maps checkpoint namespaces to parent checkpoint ids. The docs' examples also show a writes key (what the previous step wrote) and the source mentions run_id, but they did not appear in the 1.2.22 runs here: treat metadata as informational, read it with .get, and do not depend on a key you did not see.
The config of a snapshot. It carries three keys. thread_id you know. checkpoint_id identifies the snapshot. checkpoint_ns is the checkpoint namespace: an empty string for the top-level graph, "node_name:uuid" for a subgraph run inside that node, and nested namespaces joined with | ("outer:uuid|inner:uuid"). You will mostly see the empty string until 08F.13. A node can read its own namespace from config["configurable"]["checkpoint_ns"].
Tasks. snapshot.tasks is the most useful field when something has gone wrong. In the failing run above, the snapshot taken after the crash listed both branches: fast with its result and flaky with its error. For a thread paused at an interrupt() the pending task carries the interrupt's payload in task.interrupts. For a subgraph, get_state(config, subgraphs=True) fills task.state with the child's snapshot.
2.4.1 The interrupts field
For get_state(config) without a checkpoint_id, snapshot.interrupts holds only the interrupts that are still waiting for an answer. For a specific checkpoint or an entry from history it holds the most recent interrupt each task raised in that step. To find a paused checkpoint in history, the docs use s.tasks and any(t.interrupts for t in s.tasks).
2.5 Pending writes: why one failed branch does not redo the others#
Look again at the failing run in 2.1. Two nodes ran in parallel in one super-step. fast succeeded; flaky raised. The run stopped with an exception, and the checkpoint for that super-step was never written, because the step did not complete. Yet after the fix, invoke(None, config) re-ran only flaky (calls after resume: {'fast': 1, 'flaky': 2, 'join': 1}): fast was not run again.
The mechanism is pending writes. Each task's writes are saved the moment that task finishes (the saver method is put_writes; Postgres keeps them in the checkpoint_writes table, SQLite in writes). When you resume, LangGraph loads the last full checkpoint, applies the pending writes of the tasks that finished, and runs only the tasks that did not. This is what the docs mean by "you do not re-run the successful nodes".
Two limits:
- Pending writes are not snapshots. They exist so a resume is cheap, and they are not a point you can time-travel to; time travel resumes from full super-step checkpoints only.
- They only help parallel branches in the same super-step. A single node that fails has nothing to save, and a node that fails after doing half its work is re-run from its first line (Part 4).
2.6 When does a thread exist?#
get_state on a thread that has never run does not raise. It returns an empty snapshot:
StateSnapshot(values={}, next=(), config={'configurable': {'thread_id': 'unused'}}, metadata=None, created_at=None, parent_config=None, tasks=(), interrupts=())and get_state_history yields nothing. A thread exists exactly when it has a durable checkpoint. With the default durability mode, a crash before the first checkpoint reaches the database leaves the thread indistinguishable from one that was never invoked (a saver's get_tuple returns None, and invoke(None, config) raises EmptyInputError). If "this request was accepted" must survive a crash, record the admission yourself, for example with a row in your own table written before you call the graph (an outbox), and do not infer it from the checkpointer. 4.1 shows the modes that move this boundary.
Part 2 (continued): reading and changing a thread's history#
2.7 get_state, get_state_history and finding a checkpoint#
Here are the signatures, as in the source of langgraph 1.2.22 (each has an async twin, aget_state and aget_state_history):
graph.get_state(config, *, subgraphs=False) -> StateSnapshot
graph.get_state_history(config, *, filter=None, before=None, limit=None) -> Iterator[StateSnapshot]get_state(config)returns the latest checkpoint. Add"checkpoint_id"toconfigurableto read a specific one.get_state_history(config)yields checkpoints newest first.limitcaps how many;beforetakes a config and returns only checkpoints older than it;filtermatches against checkpoint metadata. The sample printedlimit=2giving steps[2, 1],beforethe second-newest giving[0, -1], andfilter={"source": "input"}giving[-1].
The docs give four idioms for finding the checkpoint you want in a history list. Memorize them, because time travel starts with one of them:
history = list(graph.get_state_history(config))
before_b = next(s for s in history if s.next == ("node_b",)) # by what runs next
at_step_2 = next(s for s in history if s.metadata["step"] == 2) # by step number
by_update = [s for s in history if s.metadata["source"] == "update"] # created by update_state
paused = [s for s in history if s.tasks and any(t.interrupts for t in s.tasks)]These are fragments for reading, using the graph and config of the earlier samples.
2.8 update_state: writing into history#
graph.update_state(config, values, as_node=None, task_id=None) -> RunnableConfigupdate_state writes values into the thread as if a node had returned them, and it returns the config of the new checkpoint it created. Four facts matter.
- It creates a new checkpoint with
metadata["source"] == "update". It does not modify the old one and it does not roll anything back. It branches (Part 3). - Values pass through the reducers. On a key with a reducer,
update_stateaccumulates; it does not overwrite. In the earlier experiment, updatinglogwith["manual"]on a thread whoselogwas['a']gave['a', 'manual']. To replace a reduced value, useOverwrite(08F.10, 3.5) orRemoveMessagefor messages. as_nodedecides who "wrote" the update, and therefore what runs next. By default LangGraph infers the node from the checkpoint's history. Passas_nodewhen the inference is ambiguous (two parallel branches updated in the same step raisesInvalidUpdateError), when the thread has no history yet (a test that sets up state before the first run), or when you want to skip nodes:as_node="pick_topic"means "pretendpick_topicproduced this", so execution continues with its successor.- The update takes effect on the next run. Calling
update_statealone runs nothing. You follow it withgraph.invoke(None, returned_config)(Part 3 does exactly that).
For several updates in one call there is bulk_update_state(config, supersteps), where supersteps is a sequence of sequences of StateUpdate(values, as_node=None, task_id=None) (from langgraph.types import StateUpdate). Each inner sequence is one super-step; the call returns the config of the final checkpoint. Section 3.2 runs it.
Part 3: Time travel: replay and fork#
Deep-dive
Because every super-step is saved, a thread is not just a current state but a history you can return to. LangGraph calls this time travel, and it comes in two forms that both work by resuming from an earlier checkpoint:
- Replay: resume from an old checkpoint unchanged and let the later nodes run again. Use it to re-try a step that failed for a transient reason or to see whether a non-deterministic step comes out differently.
- Fork: change the state at an old checkpoint first, then resume. Use it to ask "what if the user had answered differently?", to correct a bad intermediate value, or to let a user branch a conversation.
The rule that surprises people is the same for both: nodes before the checkpoint are not run again (their results are saved), and nodes after it are run again, including their LLM calls, API requests and interrupts. Time travel is not a cache read. It re-executes the future, and the future may produce different results.
3.1 A replay and a fork you can run#
The graph below has three nodes. A module-level list runs records every node execution, so the output shows exactly what ran each time. drafts_written is never cleared, so the draft text shows how many real executions of write_draft have happened.
# p04_timetravel.py: replay and fork: which nodes run again, and what update_state does to history
from typing_extensions import NotRequired, TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import START, StateGraph
runs = []
drafts_written = [] # never cleared: counts every real execution of write_draft
class State(TypedDict):
topic: NotRequired[str]
draft: NotRequired[str]
reviewed: NotRequired[str]
def pick_topic(state: State):
runs.append("pick_topic")
return {"topic": "socks in the dryer"}
def write_draft(state: State):
runs.append("write_draft")
drafts_written.append(state["topic"])
return {"draft": f"A short note about {state['topic']} (execution #{len(drafts_written)})"}
def review(state: State):
runs.append("review")
return {"reviewed": state["draft"].upper()}
graph = (
StateGraph(State)
.add_node("pick_topic", pick_topic).add_node("write_draft", write_draft).add_node("review", review)
.add_edge(START, "pick_topic").add_edge("pick_topic", "write_draft").add_edge("write_draft", "review")
.compile(checkpointer=InMemorySaver())
)
config = {"configurable": {"thread_id": "tt"}}
graph.invoke({}, config)
print("first run executed:", runs)
history = list(graph.get_state_history(config)) # newest first
before_draft = next(s for s in history if s.next == ("write_draft",))
print("found checkpoint before write_draft, values:", before_draft.values)
# --- replay: resume from an old checkpoint; nodes AFTER it run again, nodes before it do not
runs.clear()
out = graph.invoke(None, before_draft.config)
print("replay executed:", runs, "->", out["draft"])
# replay from the final checkpoint is a no-op
runs.clear()
final = graph.get_state(config)
graph.invoke(None, final.config)
print("replay from the last checkpoint executed:", runs)
# --- fork: update_state at an old checkpoint creates a NEW checkpoint on a new branch
runs.clear()
fork_config = graph.update_state(before_draft.config, {"topic": "chickens"})
print("fork checkpoint id differs:", fork_config["configurable"]["checkpoint_id"] != before_draft.config["configurable"]["checkpoint_id"])
forked = graph.get_state(fork_config)
print("fork snapshot: source =", forked.metadata["source"], "| next =", forked.next, "| values =", forked.values)
out = graph.invoke(None, fork_config)
print("fork executed:", runs, "->", out["draft"])
# the original branch is untouched, and the thread's 'latest' is now whatever ran last
print("number of checkpoints now:", len(list(graph.get_state_history(config))))
print("latest values topic:", graph.get_state(config).values["topic"])
# --- as_node: pretend a node produced the update, so execution continues AFTER it
runs.clear()
cfg2 = graph.update_state(before_draft.config, {"topic": "umbrellas"}, as_node="pick_topic")
print("as_node='pick_topic' ->", graph.get_state(cfg2).next)
graph.invoke(None, cfg2)
print("executed:", runs)
# update_state on a fresh thread: there is no history to infer the node from
cfg3 = {"configurable": {"thread_id": "fresh"}}
cfg3 = graph.update_state(cfg3, {"topic": "kites"}, as_node="pick_topic")
runs.clear()
print("fresh thread with as_node:", graph.invoke(None, cfg3)["reviewed"], runs)
print()
print("whole history of thread 'tt' (newest first):")
for s in graph.get_state_history(config):
pc = s.parent_config["configurable"]["checkpoint_id"][-6:] if s.parent_config else None
print(f" id=...{s.config['configurable']['checkpoint_id'][-6:]} parent=...{pc} step={s.metadata['step']:>2} source={s.metadata['source']:<6} next={s.next}")first run executed: ['pick_topic', 'write_draft', 'review']
found checkpoint before write_draft, values: {'topic': 'socks in the dryer'}
replay executed: ['write_draft', 'review'] -> A short note about socks in the dryer (execution #2)
replay from the last checkpoint executed: []
fork checkpoint id differs: True
fork snapshot: source = update | next = ('write_draft',) | values = {'topic': 'chickens'}
fork executed: ['write_draft', 'review'] -> A short note about chickens (execution #3)
number of checkpoints now: 12
latest values topic: chickens
as_node='pick_topic' -> ('write_draft',)
executed: ['write_draft', 'review']
fresh thread with as_node: A SHORT NOTE ABOUT KITES (EXECUTION #5) ['write_draft', 'review']
whole history of thread 'tt' (newest first):
id=...08f69b parent=...015d46 step= 4 source=loop next=()
id=...015d46 parent=...be3c9a step= 3 source=loop next=('review',)
id=...be3c9a parent=...7b8fd4 step= 2 source=update next=('write_draft',)
id=...785343 parent=...777fc0 step= 4 source=loop next=()
id=...777fc0 parent=...b565f4 step= 3 source=loop next=('review',)
id=...b565f4 parent=...7b8fd4 step= 2 source=update next=('write_draft',)
id=...a0dcd8 parent=...e79ab3 step= 5 source=fork next=()
id=...e79ab3 parent=...c303d3 step= 4 source=loop next=()
id=...c303d3 parent=...3e02b9 step= 3 source=loop next=('review',)
id=...3e02b9 parent=...7b8fd4 step= 2 source=fork next=('write_draft',)
id=...2ef55f parent=...74ef3a step= 3 source=loop next=()
id=...74ef3a parent=...7b8fd4 step= 2 source=loop next=('review',)
id=...7b8fd4 parent=...5a93ef step= 1 source=loop next=('write_draft',)
id=...5a93ef parent=...a4d7ba step= 0 source=loop next=('pick_topic',)
id=...a4d7ba parent=...None step=-1 source=input next=('__start__',)Walk through it.
- First run. All three nodes ran.
- Finding the checkpoint.
next(s for s in history if s.next == ("write_draft",))picks the checkpoint taken right beforewrite_draft. Its values hold only the topic. - Replay.
graph.invoke(None, before_draft.config)ranwrite_draftandreviewand notpick_topic. The draft text ends inexecution #2: the node really ran again. Ifwrite_draftcalled a model, you paid for a second call and might have received a different draft. - Replay from the last checkpoint ran nothing. There is no
next, so there is nothing to re-run. (It is not entirely free: the history listing at the end shows it still wrote onefork-sourced checkpoint.) - Fork.
update_state(before_draft.config, {"topic": "chickens"})created a new checkpoint withsource = update, whosenextis still('write_draft',).invoke(None, fork_config)then ranwrite_draftandreviewon the new topic. as_node. Passingas_node="pick_topic"made the update count aspick_topic's output, so the next node waswrite_draftas well. On a thread with no history (the last case) it is how you set up a state to resume from.
The full history printed at the end is the most informative part: history is a tree, not a line. Every replay and fork adds a branch whose first checkpoint has parent pointing back at the checkpoint you started from. get_state_history returns the checkpoints of all branches, newest first, and get_state(config) with no checkpoint_id returns whichever checkpoint was written last: after the fork above, the thread's "latest" state is the forked branch, with the topic chickens. The original branch still exists and you can still address it by checkpoint_id.
flowchart TD
i["step -1: input<br/>next: __start__"] --> s0["step 0<br/>next: pick_topic"]
s0 --> s1["step 1: after pick_topic<br/>next: write_draft"]
s1 --> s2["step 2: after write_draft<br/>next: review"]
s2 --> s3["step 3: after review<br/>next: none"]
s1 -. "replay: invoke(None, s1.config)" .-> r2["new checkpoint, source: fork"]
r2 --> r3["write_draft runs again"]
s1 -. "fork: update_state(s1.config, values)" .-> u["new checkpoint, source: update<br/>topic changed"]
u --> u2["write_draft, review run on the new topic"]3.2 Interrupts fire again#
If a node after the chosen checkpoint contains an interrupt() (the human-in-the-loop pause of 08F.12), replay and fork stop at that interrupt again and wait for a new Command(resume=...). That is by design: a replay re-executes the future, and the future contained a question. Two patterns follow, and the sample below runs both on a graph with two questions.
- Replay from before the second question to let the user answer it differently. The answer to the first question is kept, because that node ran before the checkpoint.
- Fork between the two questions, with
update_state(..., as_node="first"), to change an earlier answer without asking the first question again.
# p13_interrupt_replay.py: interrupts always fire again on replay and fork; and bulk_update_state
from typing_extensions import NotRequired, TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, StateUpdate, interrupt
class State(TypedDict):
ask1: NotRequired[str]
ask2: NotRequired[str]
summary: NotRequired[str]
def first(state: State):
return {"ask1": interrupt("Question 1: your name?")}
def second(state: State):
return {"ask2": interrupt("Question 2: your city?")}
def done(state: State):
return {"summary": f"{state['ask1']} from {state['ask2']}"}
graph = (StateGraph(State).add_node("first", first).add_node("second", second).add_node("done", done)
.add_edge(START, "first").add_edge("first", "second").add_edge("second", "done").add_edge("done", END)
.compile(checkpointer=InMemorySaver()))
cfg = {"configurable": {"thread_id": "form"}}
r = graph.invoke({}, cfg); print("1.", r["__interrupt__"][0].value)
r = graph.invoke(Command(resume="Ada"), cfg); print("2.", r["__interrupt__"][0].value)
r = graph.invoke(Command(resume="Chennai"), cfg); print("3.", r["summary"])
history = list(graph.get_state_history(cfg))
for s in history:
asked = [i.value for t in s.tasks for i in t.interrupts]
print(f" step={s.metadata['step']:>2} next={s.next!s:<12} interrupts recorded on the checkpoint: {asked}")
# replay from the checkpoint before 'second': the earlier answer is kept, the second interrupt fires AGAIN
before_second = next(s for s in history if s.next == ("second",))
r = graph.invoke(None, before_second.config)
print("4. replay from before 'second' ->", r["__interrupt__"][0].value)
print(" the replayed answer to question 1 is kept:", graph.get_state(cfg).values)
r = graph.invoke(Command(resume="Mumbai"), cfg) # the thread's latest checkpoint is the replayed branch
print("5. answer the new question ->", r["summary"])
# fork instead: change the FIRST answer without asking question 1 again
fork = graph.update_state(next(s for s in history if s.next == ("first",)).config, {"ask1": "Grace"}, as_node="first")
r = graph.invoke(None, fork)
print("6. fork at 'first' with as_node='first' ->", r["__interrupt__"][0].value, "(question 2 asks again, question 1 does not)")
# several updates as ordered super-steps in one call
cfg2 = {"configurable": {"thread_id": "bulk"}}
new_cfg = graph.bulk_update_state(cfg2, [
[StateUpdate({"ask1": "Linus"}, "first")],
[StateUpdate({"ask2": "Helsinki"}, "second")],
])
print("7. bulk_update_state ->", graph.get_state(new_cfg).values, "| next:", graph.get_state(new_cfg).next)
print(" then invoke(None):", graph.invoke(None, new_cfg)["summary"])1. Question 1: your name?
2. Question 2: your city?
3. Ada from Chennai
step= 3 next=() interrupts recorded on the checkpoint: []
step= 2 next=('done',) interrupts recorded on the checkpoint: []
step= 1 next=('second',) interrupts recorded on the checkpoint: ['Question 2: your city?']
step= 0 next=('first',) interrupts recorded on the checkpoint: ['Question 1: your name?']
step=-1 next=('__start__',) interrupts recorded on the checkpoint: []
4. replay from before 'second' -> Question 2: your city?
the replayed answer to question 1 is kept: {'ask1': 'Ada'}
5. answer the new question -> Ada from Mumbai
6. fork at 'first' with as_node='first' -> Question 2: your city? (question 2 asks again, question 1 does not)
7. bulk_update_state -> {'ask1': 'Linus', 'ask2': 'Helsinki'} | next: ('done',)
then invoke(None): Linus from HelsinkiReading it:
- Steps 1 to 3 are a normal two-question run. The history listing shows that a checkpoint records the interrupt that its pending task raised (
interrupts recorded on the checkpoint), which is how a UI can find "the checkpoint where the user was asked X". - Step 4 replays from before
second: the second question fires again, and the first answer (Ada) is still in the state. - Step 5 answers it with a new value (
Mumbai) on the thread's latest checkpoint, which is the replayed branch. - Step 6 forks at
first. Withas_node="first"the update counts as the answer to question 1, so the run continues with question 2 and does not ask question 1. - Step 7 builds a state from nothing with
bulk_update_state: two updates, two super-steps, each naming the node it stands in for. This is the cleanest way to prepare a thread for a test that starts in the middle of a flow.
3.3 Time travel and subgraphs#
By default a subgraph inherits its parent's checkpointer and the whole subgraph run counts as one super-step of the parent. You cannot time-travel to a point between the nodes inside it. If you need that granularity, compile the subgraph with checkpointer=True so it keeps its own history, then fetch its config from the parent snapshot: graph.get_state(config, subgraphs=True).tasks[0].state.config, and fork from that. 08F.13 covers the three subgraph modes; 11.2 summarizes them.
3.4 What time travel is good for, and what it is not#
| Use time travel to... | Do not use it to... |
|---|---|
| Retry from a failed or poor step with the same state | Undo a side effect. Replaying send_email sends another email (Part 4) |
| Let a user edit an earlier answer and branch the conversation | Delete data. Old checkpoints keep it until you prune or delete the thread (5.5) |
| Debug: reproduce a bad step from the exact state that caused it | Guarantee an identical result. Models and APIs are not deterministic |
Build test fixtures with update_state and bulk_update_state |
Skip nodes in production without a plan. as_node makes the graph behave as if the node had run |
| Compare two branches (different prompts, different models) from the same checkpoint | Treat a very long history as free. Every branch is stored (5.6) |
Part 4: Durable execution: the rules that make a restart correct#
Deep-dive
Durable execution means a run can be stopped at any moment (a crash, a deploy, a human who takes three days to answer) and continued later without losing completed work and without doing it twice. Checkpoints give you the first half. The second half is a set of rules about your code, because "continue" means "run the unfinished part again", and a node that was half done is run from its first line.
4.1 Durability modes: exit, async and sync#
A checkpoint has to be written to the database, and writing costs time. The durability mode says when. You pass it per call, to invoke, stream, ainvoke or astream:
graph.invoke(input, config, durability="sync") # "exit", "async" (the default) or "sync"| Mode | Behaviour | Trade-off |
|---|---|---|
"exit" |
Writes checkpoints only when the run exits: success, error, or an interrupt for human input | Fastest for long graphs. If the process dies, all intermediate state of that run is lost |
"async" (default) |
Writes each checkpoint in the background while the next step runs | Good speed and durability. A crash can lose the checkpoint of the step that was just finishing |
"sync" |
Writes each checkpoint before the next step starts | The strongest guarantee, with some overhead per step |
The default is "async" (None means "async"). The easiest way to understand the modes is to kill a process in the middle of a run. The script below runs a four-node graph on a SQLite file and, when the environment variable KILL=1 is set, calls os._exit(137) inside the third node. That is what kill -9 looks like to the program: no cleanup, no flushing, no exception. A second invocation then opens the same file and reports what survived.
# p07_durability.py: kill the process in the middle of a run and see what each durability mode saved
# usage: python p07_durability.py crash <mode> <db> then python p07_durability.py inspect <db>
import os
import sqlite3
import sys
from operator import add
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
log: Annotated[list[str], add]
def step_a(state: State):
return {"log": ["a done"]}
def step_b(state: State):
return {"log": ["b done"]}
def step_c(state: State):
if os.environ.get("KILL") == "1":
os._exit(137) # simulates kill -9: no cleanup, no flushing, no exception
return {"log": ["c done"]}
def build(saver):
return (StateGraph(State)
.add_node("step_a", step_a).add_node("step_b", step_b).add_node("step_c", step_c)
.add_edge(START, "step_a").add_edge("step_a", "step_b").add_edge("step_b", "step_c")
.add_edge("step_c", END).compile(checkpointer=saver))
phase, *rest = sys.argv[1:]
config = {"configurable": {"thread_id": "job-1"}}
if phase == "crash":
mode, db = rest
graph = build(SqliteSaver(sqlite3.connect(db, check_same_thread=False)))
graph.invoke({"log": []}, config, durability=mode)
else:
(db,) = rest
graph = build(SqliteSaver(sqlite3.connect(db, check_same_thread=False)))
snap = graph.get_state(config)
print(" checkpoints on disk:", len(list(graph.get_state_history(config))),
"| next:", snap.next, "| log:", snap.values.get("log"))Run it once per mode (the file name and mode are arguments), then inspect. The three runs below are the real output on 14 November 2026:
for mode in exit async sync; do
rm -f job_$mode.db; echo "durability=$mode"
KILL=1 uv run python p07_durability.py crash $mode job_$mode.db; echo " exit code: $?"
uv run python p07_durability.py inspect job_$mode.db
donedurability=exit
exit code: 137
checkpoints on disk: 0 | next: () | log: None
durability=async
exit code: 137
checkpoints on disk: 1 | next: ('__start__',) | log: []
durability=sync
exit code: 137
checkpoints on disk: 4 | next: ('step_c',) | log: ['a done', 'b done']What each line says:
exit: nothing on disk. The run never exited normally, so nothing was written. A restart would see a thread that never existed. This mode is for runs where losing the whole run on a crash is acceptable (a short job you would simply re-submit), or where you accept that trade for speed.async: only the first checkpoint. The write of the input checkpoint had started; the later ones were still in flight when the process died. That count is a race, not a rule: you can get more or fewer on another run or machine. What is guaranteed is only that a crash can lose the most recent checkpoints.sync: four checkpoints, andnextis('step_c',). Everything up to the end ofstep_bwas committed beforestep_cbegan. Resuming withinvoke(None, config)would runstep_cnext, exactly where the process died.
The first-checkpoint caveat. On a new thread, exit writes nothing until the run ends. async starts the input checkpoint's write before the first node but may not have committed it. sync commits the input checkpoint (step -1) and step 0 before the first node runs. In every mode, a crash before the first checkpoint is durable leaves the thread looking like it was never invoked (2.6). The safe design for "I must not lose this request" is to record it yourself first.
Choosing a mode.
| Situation | Mode | Why |
|---|---|---|
| Interactive chat, steps take seconds | async (default) |
A lost last checkpoint costs one repeated step |
| Steps with expensive or irreversible work, long pauses, approvals | sync |
You never want to repeat a step you already paid for |
| Short batch jobs you can simply re-run, or tests | exit |
The speed is worth it, and failure means "run it again" |
| Anything where you need a guarantee, not a probability | sync, plus idempotent nodes (4.3) |
async is "small risk", which is not "none" |
Other facts about durability:
- Without a checkpointer it does nothing.
durability="exit"and"async"on a graph compiled without one emit the warning "durabilityhas no effect when no checkpointer is present". In the 1.2.22 runs,durability="sync"on a graph with no checkpointer did worse: it raisedAttributeError: 'SyncPregelLoop' object has no attribute '_put_checkpoint_fut'. That looks like a bug, so do not passdurabilityto a graph that has no checkpointer. - A misspelled mode is not rejected.
durability="eventually"raised no error in the same runs. Copy the three words from the table. - The predecessor is deprecated.
checkpoint_during=Truemeant today's"async"andFalsemeant"exit". It emitsLangGraphDeprecatedSinceV10("checkpoint_duringis deprecated and will be removed. Please usedurabilityinstead") and raises if you pass both.
4.2 The replay model: a node runs again from its first line#
After a crash, an error retry or an interrupt, the checkpoint LangGraph resumes from was taken at a super-step boundary. So the node that was running when things stopped is run again from the start of its function, and any side effect it performed before the stop is performed again. Everything in the rest of this part follows from that single sentence. 08F.10, 4.7 introduced it with a table for choosing the unit of work (plain function, task, subgraph, graph node); this part adds the machinery and the proofs.
The consequence is at-least-once execution: a step is attempted until it succeeds, which may be more than once. It is not exactly-once. You cannot get exactly-once from a checkpointer. You get it by making each step safe to repeat.
4.3 Idempotency: making a repeat harmless#
An operation is idempotent if doing it twice has the same effect as doing it once. The tools:
| Technique | Example |
|---|---|
| Idempotency key | Send Idempotency-Key: charge-order-17 to the payment provider. A repeat returns the first result |
| Upsert | INSERT ... ON CONFLICT (order_id) DO UPDATE instead of INSERT |
| Read-before-write | Check whether the email for this ticket was already sent, then send |
| Natural keys | File name or object key derived from the order id, not from a timestamp |
Three rules the docs stress, because the first attempt at each goes wrong in the same way.
- The key must be reproducible from durable state. Derive it from something that is already saved when the node starts:
f"charge:{state['order_id']}". A key generated inside the failing node (uuid4()) is lost with the crash, and the retry generates a different one, so the provider sees two distinct requests. - If there is no business identity, give the key its own node. A first node generates and stores the key in state, with
durability="sync"if it must survive a process crash, and the node that charges reads it from state. The checkpoint after the first node protects the key. - A lost acknowledgement is "unknown", not "did not happen". The charge may have succeeded and the response may have been lost. Before you compensate (refund, retry, mark failed), ask the provider what happened.
# illustrative: payments is a stand-in for your payment client; nothing here calls a real service
from typing_extensions import TypedDict
class State(TypedDict):
order_id: str
amount_cents: int
charge_id: str
def charge_card(state: State):
# BAD: if this node is retried after the provider answered, the card is charged twice
# charge = payments.charge(state["amount_cents"])
# GOOD: the key comes from saved state, so a repeat is a no-op on the provider's side
charge = payments.charge(
state["amount_cents"],
idempotency_key=f"charge:{state['order_id']}",
)
return {"charge_id": charge.id}This sample is illustrative: payments is not defined, and it shows the shape only. 08A.9, 6.2 is the course's durability checklist for non-LangGraph code, and 03.8 covers idempotency for API calls generally.
4.4 @task: checkpointing work inside a node#
Sometimes one node does several expensive or side-effecting things in a row: call three APIs, send two emails. If it crashes after the second, a plain re-run repeats the first two. Splitting it into three nodes is one fix. The other is to wrap each unit in a @task (from langgraph.func, the Functional API primitive of 08F.14). A task's result is saved when it finishes, and on a re-run the saved result is returned instead of running the function again. Tasks work inside an ordinary StateGraph node.
# p05_tasks.py: a node that crashes half-way: plain code repeats on resume, @task results are restored
from typing_extensions import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import task
from langgraph.graph import END, START, StateGraph
effects = [] # stands in for the outside world: emails sent, cards charged
crash = {"on": True}
class State(TypedDict):
order_id: str
report: str
def send_receipt_plain(order_id: str):
effects.append(f"plain: receipt for {order_id}") # a side effect, in ordinary code
@task
def send_receipt_task(order_id: str) -> str:
effects.append(f"task: receipt for {order_id}") # the same side effect, wrapped in a task
return f"receipt-{order_id}"
def fulfil(state: State):
send_receipt_plain(state["order_id"]) # runs again after a crash below
receipt = send_receipt_task(state["order_id"]).result() # result saved once it has finished
if crash["on"]:
raise RuntimeError("worker killed after sending the receipt")
return {"report": f"done, {receipt}"}
graph = (
StateGraph(State).add_node("fulfil", fulfil)
.add_edge(START, "fulfil").add_edge("fulfil", END)
.compile(checkpointer=InMemorySaver())
)
config = {"configurable": {"thread_id": "order-7"}}
try:
graph.invoke({"order_id": "7", "report": ""}, config)
except RuntimeError as exc:
print("first attempt failed:", exc)
print("effects so far:", effects)
crash["on"] = False
print("resumed:", graph.invoke(None, config))
print("effects in total:")
for e in effects:
print(" ", e)first attempt failed: worker killed after sending the receipt
effects so far: ['plain: receipt for 7', 'task: receipt for 7']
resumed: {'order_id': '7', 'report': 'done, receipt-7'}
effects in total:
plain: receipt for 7
task: receipt for 7
plain: receipt for 7The node did two things before crashing: a plain function call and a task call, each recording an "email sent" effect. After the resume, the plain effect appears twice (the node re-ran from its first line) and the task effect appears once (its saved result was returned). Three rules about tasks:
- A finished task is restored; a task that started but did not finish may run again. Tasks narrow the window; they do not remove it. The idempotency key rule still applies inside a task.
- The result is stored in the checkpoint, so it must be serializable (Part 6) and you should not return megabytes.
- A task costs nothing in graph structure. It adds no node and no edge and creates no new graph checkpoint. That is why it suits fine-grained steps that do not need a routing decision after them.
4.5 Determinism: the order of your calls is the identity of your results#
When a node with tasks or an interrupt is re-run, LangGraph has to decide which saved result belongs to which call. It does that by the call's identity: the task's function name plus its position in the node (the first call, the second call, and so on). If the code takes a different path on the re-run, a result can attach to the wrong call, as the second sample below shows. The docs call this the determinism requirement, and it applies to anything that replays: nodes that use tasks or interrupts, and every Functional API entrypoint.
The first sample swaps two different tasks on the re-run. It is the benign case.
# p06_determinism.py: what happens when a node replays and its task calls come in a different order
from typing_extensions import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import task
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
out: str
@task
def lookup_customer(name: str) -> str:
print(f" (task body) lookup_customer({name})")
return f"customer:{name}"
@task
def lookup_invoice(name: str) -> str:
print(f" (task body) lookup_invoice({name})")
return f"invoice:{name}"
state = {"mode": "A", "crash": True}
def work(s: State):
if state["mode"] == "A":
a = lookup_customer("ada").result()
b = lookup_invoice("ada").result()
else: # "new code": the calls are swapped
b = lookup_invoice("ada").result()
a = lookup_customer("ada").result()
if state["crash"]:
raise RuntimeError("crash after both tasks")
return {"out": f"{a} / {b}"}
graph = (StateGraph(State).add_node("work", work).add_edge(START, "work").add_edge("work", END)
.compile(checkpointer=InMemorySaver()))
for label, resume_mode in [("same order on resume", "A"), ("swapped order on resume", "B")]:
print(label)
cfg = {"configurable": {"thread_id": label}}
state.update(mode="A", crash=True)
try:
graph.invoke({"out": ""}, cfg)
except RuntimeError:
print(" crashed")
state.update(mode=resume_mode, crash=False)
print(" result:", graph.invoke(None, cfg)["out"])same order on resume
(task body) lookup_customer(ada)
(task body) lookup_invoice(ada)
crashed
result: customer:ada / invoice:ada
swapped order on resume
(task body) lookup_customer(ada)
(task body) lookup_invoice(ada)
crashed
(task body) lookup_invoice(ada)
(task body) lookup_customer(ada)
result: customer:ada / invoice:adaWhen the order is swapped, the saved results did not match, so both tasks ran again: costly, but correct. The second sample is the dangerous case, one task called twice with different arguments, then called in the other order.
# p06b_determinism.py: the same task called twice with different arguments, then replayed in the other order
from typing_extensions import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import task
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
out: str
@task
def lookup(name: str) -> str:
print(f" (task body) lookup({name})")
return f"customer:{name}"
state = {"order": ["ada", "bob"], "crash": True}
def work(s: State):
first = lookup(state["order"][0]).result()
second = lookup(state["order"][1]).result()
if state["crash"]:
raise RuntimeError("crash after both tasks")
return {"out": f"{first} / {second}"}
graph = (StateGraph(State).add_node("work", work).add_edge(START, "work").add_edge("work", END)
.compile(checkpointer=InMemorySaver()))
cfg = {"configurable": {"thread_id": "x"}}
try:
graph.invoke({"out": ""}, cfg)
except RuntimeError:
print(" crashed")
state.update(order=["bob", "ada"], crash=False) # new code asks in the other order
print(" result:", graph.invoke(None, cfg)["out"]) (task body) lookup(ada)
(task body) lookup(bob)
crashed
result: customer:ada / customer:bobRead the result carefully. The new code asked for lookup("bob") first and lookup("ada") second, yet the result is customer:ada / customer:bob. The first call received the saved result of the first original call, which was for ada. No task body ran, and no error was raised. The program got a wrong answer silently. That is what "matching is positional" means in practice.
The rule, stated exactly. A saved result is found by the task's function name plus its call position, and not by its arguments. Two cases follow, and both samples in this section ran them:
- A different task at that position (the first sample:
lookup_customerandlookup_invoiceswapped). Nothing matches, so the task runs again. This costs repeated work (a repeated effect or model call) but the answer is correct. - The same task at that position with different arguments (the second sample:
lookupcalled withbobfirst instead ofada). The saved result of the old call is returned. This is silent and wrong.
Interrupts have no name at all, so for an interrupt call position is the whole identity (08F.12, 4.2). The Functional API sample in 08F.14, 3.4 is a related case: it swaps two different tasks, so it shows the re-run and not the silent swap. A new entrypoint name also isolates old results, so a rename alone can hide this hazard.
The rules that prevent it:
- Put anything non-deterministic inside a task. Random numbers, the current time, a UUID, a model call, a network read. The first execution saves the value; a replay reads it back, so the code after it sees the same value both times.
- Do not branch on non-deterministic values outside tasks.
if random.random() < 0.5: task_a() else: task_b()takes a different path on replay. - Do not add, remove or reorder task or interrupt calls, and do not change the arguments of a task called repeatedly at a fixed position, in a node that has threads in flight. Add a new task at the end, or after the resume point (4.6).
- Loops over saved data are fine if the data comes from state or from a task result, because the iteration order is then the same on replay.
4.6 Changing code while threads are in flight#
LangGraph applies the latest graph to every thread, including threads that were paused before you deployed. 08F.10, 14.1 has the full tables (which topology and state-schema changes are safe, why renaming a node breaks paused threads, why renaming a key silently drops saved values, the flow_version pattern). The points to add here:
- State, not topology, is what the checkpoint holds. The edges are in your code. A resumed thread loads saved state and runs the current graph from the saved
next. - Safe changes: add a state key declared
NotRequired; add an edge; add a node. Unsafe: rename or remove a node a paused thread is about to enter; rename or remove a state key a thread has used; tighten a type so old data fails validation. - Business-logic changes that must not apply to old threads: stamp a
flow_versionin state when the thread starts, and branch on it. - Entrypoints (Functional API) with runs in flight: let them drain, wrap the new logic in a new
@task(a task that did not exist when the run started simply runs), or register the new version under a new graph name. - Test it. Restore a recent production checkpoint into a test environment, run the new code on it and resume.
4.7 Graceful shutdown, and finding threads that are in flight#
Two operational questions have short answers here and longer ones in later lessons.
- A deploy is coming. How do I stop cleanly? In LangGraph 1.2 and later you can ask a run to drain:
RunControl().request_drain("sigterm")andgraph.invoke(..., control=control)make the run stop after the current super-step with a resumable checkpoint, raisingGraphDrained. Resume later withgraph.invoke(None, config). This is documented on the Fault tolerance page; 08F.12 covers retries, timeouts and cancellation and is the better place to learn the details. - Which threads were in flight when the process died? Call
graph.get_state(config)per thread: a non-emptynextmeans unfinished work, andtasks[...].errortells you why. If you also run an Agent Server (Part 11), its thread search filters by status (idle,busy,interrupted,error), and LangSmith tracing shows the runs. For a self-hosted graph, keep your own table of active thread ids; enumerating all checkpoints (2.7) is a last resort.
4.8 The durable-node checklist#
Before a node goes to production with a checkpointer, check each line:
| Check | Why |
|---|---|
| Can it run twice with the same input and cause no harm? | Resume and retry re-run it from the top |
| Is every external write protected by an idempotency key built from saved state? | A key made inside the node is lost with the node |
| Is each irreversible effect in its own node, after the decision? | The checkpoint between them stops a double decision |
Is non-deterministic work (time, random, model, network) inside a @task if the node also has tasks or interrupts? |
Replay matches results by task name and call position, never by arguments |
| Did I avoid adding, removing or reordering tasks and interrupts in nodes with in-flight threads? | The silent wrong answer in 4.5 |
| Does every value it returns serialize (Part 6)? | Otherwise the checkpoint write fails |
Do I know my durability mode and what a crash costs in it? |
The default can lose the last checkpoint |
Is there a flow_version or a drain plan for the next deploy? |
In-flight threads run the new code |
Part 5: Checkpointer implementations#
A checkpointer is any object that implements BaseCheckpointSaver. LangGraph ships three in the repository (in-memory, SQLite, Postgres) and the ecosystem adds more. Which one you use decides whether memory survives a restart, whether several processes can share it, and how it scales.
5.1 Which saver, when#
| Saver | Package | Survives restart | Several processes | Use for |
|---|---|---|---|---|
InMemorySaver |
langgraph-checkpoint (installed with langgraph) |
No | No | Tests, notebooks, demos |
SqliteSaver / AsyncSqliteSaver |
langgraph-checkpoint-sqlite |
Yes (a file) | Poorly | Local tools, small single-process apps, prototypes |
PostgresSaver / AsyncPostgresSaver |
langgraph-checkpoint-postgres |
Yes | Yes | Production |
| MongoDB, Redis, AWS (DynamoDB, Bedrock, Valkey), Azure Cosmos DB, CockroachDB and others | Separate packages (langgraph-checkpoint-mongodb, langgraph-checkpoint-redis, langgraph-checkpoint-aws, ...) |
Depends on the backend | Depends | When that database is already your standard |
| None: LangSmith Agent Server | Built in | Yes | Yes | You deploy on the platform and configure no saver (Part 11) |
Notes on the table. The InMemorySaver docstring itself says it is for debugging and testing and recommends the Postgres savers for production. MemorySaver is the old name and is kept as an alias (MemorySaver is InMemorySaver prints True); new code and the current docs use InMemorySaver. The Redis saver is maintained by the Redis team, not by LangChain Inc, and MongoDB and AWS have their own packages with their own release schedules: check each package's page before you adopt it, and read the integrations index linked in Further resources, which lists them all. langgraph-checkpoint-duckdb exists on PyPI, but its last release was in January 2025 and the docs' table does not list it.
5.2 SqliteSaver and AsyncSqliteSaver#
SQLite needs no server, which makes it the right first step beyond memory. The next sample is run twice, in two separate processes, to prove the point: the second process continues the conversations the first one started.
# p08_sqlite.py: SqliteSaver: memory that survives a restart, listing threads, deleting and pruning
# run it twice: the second run continues the conversations the first run started
import sys
from langchain_core.messages import AIMessage
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import START, MessagesState, StateGraph
def chat(state: MessagesState):
n = sum(1 for m in state["messages"] if m.type == "human")
return {"messages": [AIMessage(content=f"turn {n}")]}
builder = StateGraph(MessagesState).add_node("chat", chat).add_edge(START, "chat")
with SqliteSaver.from_conn_string("chat_memory.sqlite") as saver: # creates the file; setup() is automatic
graph = builder.compile(checkpointer=saver)
for thread in ("alice", "bob"):
cfg = {"configurable": {"thread_id": thread}}
out = graph.invoke({"messages": [("user", f"hello from {thread}")]}, cfg)
print(thread, "->", out["messages"][-1].content, f"({len(out['messages'])} messages in thread)")
# list every thread: call .list(None) on the saver itself (None, not {})
ids = {t.config["configurable"]["thread_id"] for t in saver.list(None)}
print("threads in the database:", sorted(ids))
rows = sum(1 for _ in saver.list(None))
print("checkpoint rows:", rows)
if len(sys.argv) > 1 and sys.argv[1] == "maintain":
for name, call in [
("prune(['alice'])", lambda: saver.prune(["alice"], strategy="keep_latest")),
("copy_thread('alice', 'alice-copy')", lambda: saver.copy_thread("alice", "alice-copy")),
("delete_for_runs(['r1'])", lambda: saver.delete_for_runs(["r1"])),
]:
try:
call()
print(name, "-> ok")
except NotImplementedError:
print(name, "-> NotImplementedError (this saver does not implement it)")
saver.delete_thread("bob")
print("after delete_thread('bob'):", sorted({t.config["configurable"]["thread_id"] for t in saver.list(None)}))Run it three times (the first two prove persistence, the third demonstrates the maintenance calls):
uv run python p08_sqlite.py # first process
uv run python p08_sqlite.py # a new process: the same threads continue
uv run python p08_sqlite.py maintain # maintenance calls--- first run
alice -> turn 1 (2 messages in thread)
bob -> turn 1 (2 messages in thread)
threads in the database: ['alice', 'bob']
checkpoint rows: 6
--- second run (new process)
alice -> turn 2 (4 messages in thread)
bob -> turn 2 (4 messages in thread)
threads in the database: ['alice', 'bob']
checkpoint rows: 12
--- maintenance
alice -> turn 3 (6 messages in thread)
bob -> turn 3 (6 messages in thread)
threads in the database: ['alice', 'bob']
checkpoint rows: 18
prune(['alice']) -> NotImplementedError (this saver does not implement it)
copy_thread('alice', 'alice-copy') -> NotImplementedError (this saver does not implement it)
delete_for_runs(['r1']) -> NotImplementedError (this saver does not implement it)
after delete_thread('bob'): ['alice']What to take from it:
- Persistence across processes. The second run's
turn 2and4 messages in threadshow that the new process loaded the threads fromchat_memory.sqlite. The database file is the memory. SqliteSaver.from_conn_string("file")is a context manager that opens the connection withcheck_same_thread=False, creates the tables, and closes the connection on exit.setup()is called for you ("should not be called directly"). The alternative is to build it yourself,SqliteSaver(sqlite3.connect("file", check_same_thread=False)), which the docs' interrupt pages use; you then own closing the connection.- Listing threads.
saver.list(None)yielded every checkpoint of every thread (6 rows after one run of 2 threads: 3 checkpoints per turn per thread), and the sample groups them into a set of thread ids. delete_thread(thread_id)removes everything stored for a thread and is implemented by all three bundled savers.prune,copy_threadanddelete_for_runsare not implemented bySqliteSaver(and not byInMemorySaver): they raiseNotImplementedError. They are optional methods on the base class. Inlanggraph-checkpoint-postgres3.2.1 the source definespruneandcopy_threadon both Postgres savers, but this lesson did not run them (no database in the content phase), so test them before you depend on them.- Source notes:
SqliteSaveris "meant for lightweight, synchronous use cases (demos and small projects) and does not scale to multiple threads". The implementation guards the connection with a lock, which is whycheck_same_thread=Falseis safe, but concurrent writers still contend for SQLite's single write lock.
The async saver. Async graph execution (ainvoke, astream) calls the saver's async methods. A sync-only saver in an async graph fails, and AsyncSqliteSaver is the answer for SQLite (it needs aiosqlite, which comes with the package).
# p09_async_inmem.py: async graphs need an async-capable saver; what InMemorySaver and the SQLite savers implement
import asyncio
import sqlite3
from langchain_core.messages import AIMessage
from langgraph.checkpoint.memory import InMemorySaver, MemorySaver
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from langgraph.graph import START, MessagesState, StateGraph
async def chat(state: MessagesState):
return {"messages": [AIMessage(content=f"turn {sum(m.type == 'human' for m in state['messages'])}")]}
builder = StateGraph(MessagesState).add_node("chat", chat).add_edge(START, "chat")
def turn(text):
return {"messages": [("user", text)]}
async def main():
print("MemorySaver is InMemorySaver:", MemorySaver is InMemorySaver)
# 1. InMemorySaver works for sync and async
mem = InMemorySaver()
g = builder.compile(checkpointer=mem)
cfg = {"configurable": {"thread_id": "a"}}
await g.ainvoke(turn("hi"), cfg)
print("InMemorySaver ainvoke ok, messages:", len((await g.aget_state(cfg)).values["messages"]))
for name, call in [
("prune", lambda: mem.prune(["a"])),
("copy_thread", lambda: mem.copy_thread("a", "b")),
("delete_thread", lambda: mem.delete_thread("a")),
]:
try:
call(); print("InMemorySaver", name, "-> ok")
except NotImplementedError:
print("InMemorySaver", name, "-> NotImplementedError")
# 2. the sync SqliteSaver with an async graph
sync_saver = SqliteSaver(sqlite3.connect(":memory:", check_same_thread=False))
g2 = builder.compile(checkpointer=sync_saver)
try:
await g2.ainvoke(turn("hi"), {"configurable": {"thread_id": "x"}})
print("SqliteSaver + ainvoke: worked")
except Exception as exc:
print("SqliteSaver + ainvoke:", type(exc).__name__, str(exc)[:100])
# 3. AsyncSqliteSaver: use `async with` so the connection is closed
async with AsyncSqliteSaver.from_conn_string("async_memory.sqlite") as saver:
g3 = builder.compile(checkpointer=saver)
c = {"configurable": {"thread_id": "t"}}
await g3.ainvoke(turn("one"), c)
await g3.ainvoke(turn("two"), c)
print("AsyncSqliteSaver messages:", len((await g3.aget_state(c)).values["messages"]))
threads = {t.config["configurable"]["thread_id"] async for t in saver.alist(None)}
print("threads:", sorted(threads))
await saver.adelete_thread("t")
print("after adelete_thread:", sorted({t.config["configurable"]["thread_id"] async for t in saver.alist(None)}))
asyncio.run(main())MemorySaver is InMemorySaver: True
InMemorySaver ainvoke ok, messages: 2
InMemorySaver prune -> NotImplementedError
InMemorySaver copy_thread -> NotImplementedError
InMemorySaver delete_thread -> ok
SqliteSaver + ainvoke: NotImplementedError The SqliteSaver does not support async methods. Consider using AsyncSqliteSaver instead.
from langgr
AsyncSqliteSaver messages: 4
threads: ['t']
after adelete_thread: []InMemorySaverworks for both sync and async, and implementsdelete_threadbut notpruneorcopy_thread.SqliteSaverwithainvokeraisesNotImplementedError: The SqliteSaver does not support async methods. Consider using AsyncSqliteSaver instead.The message names the fix.AsyncSqliteSaver.from_conn_stringis an async context manager. Useasync with. The source warns that if you do not close the connection the program may hang at exit, and that the async saver is "not recommended for production workloads due to limitations in SQLite's write performance".
5.3 PostgresSaver and AsyncPostgresSaver#
Postgres is the production choice: concurrent writers, replication, backups and the operational tooling you already have. Install with the binary and pool extras of psycopg (the checkpoint package installs plain psycopg, which needs the system libpq; the binary extra bundles it).
# illustrative: needs a running Postgres server, which this lesson does not start
from langgraph.checkpoint.postgres import PostgresSaver
DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" # use your own secret, never commit one
with PostgresSaver.from_conn_string(DB_URI) as checkpointer:
checkpointer.setup() # FIRST use only: creates the tables and runs migrations
graph = builder.compile(checkpointer=checkpointer)
graph.invoke({"messages": [("user", "hello")]}, {"configurable": {"thread_id": "t-1"}})That first sample is illustrative (it needs a Postgres server). Its async twin, for async graphs and web servers:
# illustrative: the async twin, for async graphs and web servers
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
async def run(builder, DB_URI: str):
async with AsyncPostgresSaver.from_conn_string(DB_URI) as checkpointer:
await checkpointer.setup()
graph = builder.compile(checkpointer=checkpointer)
await graph.ainvoke({"messages": [("user", "hello")]}, {"configurable": {"thread_id": "t-1"}})Both samples are illustrative: they need a Postgres server and a database URI, and builder stands for any StateGraph builder from earlier parts. What the Postgres savers need and do, from the package source (3.2.1) and README:
setup()must be called by you, the first time. It creates four tables,checkpoints,checkpoint_blobs,checkpoint_writesandcheckpoint_migrations, and later releases add migrations (there were ten at 3.2.1). The docs' advice is to run migrations as a dedicated deployment step or at server start, not on every request. A missingsetup()gives "relation does not exist" errors on the first write.from_conn_stringis what you want almost always. It opens the connection withautocommit=True,prepare_threshold=0androw_factory=dict_rowfor you.- If you create the connection yourself, pass
autocommit=Trueandrow_factory=dict_row(from psycopg.rows import dict_row). The README warns that without them tables may not persist and you may getTypeErrors. You can hand the saver apsycopgConnectionor aConnectionPool(PostgresSaver(conn)); pipeline mode (pipeline=True) works only with a single connection, otherwiseValueError. - Keep
thread_idunder 255 characters. The docs list this under troubleshooting. - Signatures in 3.2.1:
PostgresSaver(conn, pipe=None, serde=None),PostgresSaver.from_conn_string(conn_string, *, pipeline=False);AsyncPostgresSaver(conn, pipe=None, serde=None),AsyncPostgresSaver.from_conn_string(conn_string, *, pipeline=False, serde=None). Note that only the asyncfrom_conn_stringacceptsserde. The docs' encryption example passesserde=toPostgresSaver.from_conn_string; the 3.2.1 source does not accept it there. Part 6 shows the form that works. - Connection pools in a web server. One saver per process, created at startup and shared by all requests, with a pool sized for your concurrency. Do not create a saver per request.
5.4 The checkpointer interface, and async#
Every saver implements BaseCheckpointSaver. You will not call these directly, but they explain behaviour and are what a custom saver must provide.
| Method (and async twin) | Purpose |
|---|---|
put (aput) |
Store a checkpoint |
put_writes (aput_writes) |
Store the pending writes of one finished task |
get_tuple (aget_tuple) |
Load a checkpoint (with config, metadata, parent and pending writes) |
list (alist) |
Iterate checkpoints, optionally filtered and limited |
delete_thread (adelete_thread) |
Remove everything for a thread |
delete_for_runs, copy_thread, prune (optional) |
Optional maintenance; default NotImplementedError |
A rule of thumb for which saver an async graph needs: if you call ainvoke or astream, the saver must implement the async twins. InMemorySaver, AsyncSqliteSaver and AsyncPostgresSaver do. The sync SqliteSaver does not.
5.5 Deleting, pruning and retention#
Checkpoints are history, and history grows (5.6). Four tools exist, and they differ:
| Tool | Effect | Availability |
|---|---|---|
checkpointer.delete_thread(thread_id) |
Deletes all checkpoints and writes of the thread | All three bundled savers; adelete_thread for async |
checkpointer.prune(thread_ids, strategy="keep_latest") |
Keeps only the latest checkpoint per namespace for those threads; "delete" removes everything |
Implemented in the Postgres savers' 3.2.1 source; not in SqliteSaver or InMemorySaver (verified by running) |
checkpointer.copy_thread(source, target) |
Copies a thread's history to a new id | Optional; implemented by the Postgres savers (not run here), not by SqliteSaver or InMemorySaver |
| A scheduled job of your own | Delete threads older than N days, by your own thread index | Always possible |
The docs' guidance for "checkpoints growing unboundedly" is to prune periodically or set a retention policy, run as a cron job. There is no built-in TTL for checkpoints. Design a retention rule early:
- Delete a thread when the product says the conversation is over: ticket closed plus 30 days, say. Keep that rule in a job.
keep_latestpruning keeps the thread usable for new turns but throws away its time-travel history.- Erasure requests (a user asks you to delete their data) must delete threads and store items. Removing messages from state does not remove them from older checkpoints (10.5).
delete_threaddoes.
5.6 Checkpoint growth, and DeltaChannel (beta)#
By default every checkpoint stores the full value of every channel. A messages list with 200 messages is written in full at every step, so storage grows roughly with the square of the conversation length: n steps, each storing up to n messages. Three remedies, in the order to try them:
- Keep state small. Do not put large documents, base64 images or whole tool outputs in state; put a reference (an id, a URL, a store key) and fetch the body when needed.
- Prune and delete (5.5).
DeltaChannel(beta,langgraph1.2 and later) stores only the writes of each step, plus a full snapshot every so often, and rebuilds the value when you read it.
The experiment below appends 200 characters per step for 100 steps, once with an ordinary list and operator.add and once with a DeltaChannel, and measures the bytes in the SQLite checkpoints table.
# c01_delta.py: checkpoint growth: a list that is rewritten in full every step versus DeltaChannel (beta)
import os
import sqlite3
from operator import add
from typing import Annotated, Sequence
from typing_extensions import TypedDict
from langgraph.channels import DeltaChannel
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import END, START, StateGraph
def bulk_append(state: list, writes: Sequence[list]) -> list:
"""A BULK reducer: current list plus a sequence of writes. Must be pure and associative."""
merged = list(state)
for w in writes:
merged.extend(w)
return merged
class Plain(TypedDict):
n: int
log: Annotated[list[str], add]
class Delta(TypedDict):
n: int
log: Annotated[list[str], DeltaChannel(bulk_append, snapshot_frequency=50)]
def tick(state):
return {"n": state["n"] + 1, "log": ["x" * 200]} # 200 bytes appended per step
def route(state):
return "tick" if state["n"] < 100 else END
def build(schema, path):
if os.path.exists(path):
os.remove(path)
conn = sqlite3.connect(path, check_same_thread=False)
g = (StateGraph(schema).add_node("tick", tick).add_edge(START, "tick")
.add_conditional_edges("tick", route, ["tick", END]).compile(checkpointer=SqliteSaver(conn)))
return g, conn
for label, schema in [("plain list + add reducer", Plain), ("DeltaChannel", Delta)]:
g, conn = build(schema, f"growth_{schema.__name__}.sqlite")
cfg = {"configurable": {"thread_id": "t"}}
out = g.invoke({"n": 0, "log": []}, cfg)
rows = conn.execute("select count(*), sum(length(checkpoint)) from checkpoints").fetchone()
print(f"{label:<26} steps={out['n']} log entries={len(out['log'])} checkpoint rows={rows[0]} bytes stored={rows[1]:,}")
# reading state back through the API gives the full list either way
print(f"{'':<26} get_state log length: {len(g.get_state(cfg).values['log'])}")
conn.close()plain list + add reducer steps=100 log entries=100 checkpoint rows=102 bytes stored=1,080,810
get_state log length: 100
DeltaChannel steps=100 log entries=100 checkpoint rows=102 bytes stored=90,094
get_state log length: 100Both runs saved 102 checkpoint rows and both read back a log of 100 entries through get_state, but the delta run stored about 12 times fewer bytes in the checkpoint column (90,094 against 1,080,810 in this run; your byte counts will differ a little, but the ratio stays about 12 times). The cost is moved to read time: the value is rebuilt from the writes and snapshots.
How to use it, and what to respect:
- The reducer is a bulk reducer:
(state: list, writes: Sequence[list]) -> list, not the pairwise reducer ofadd. It must be pure and associative because it runs on reconstruction (when reading), not when writing. snapshot_frequency: the sample passes 50. The package source defaults it to 100 (the 1.2.18 release notes say "default delta snapshots to 100 updates"), while the runtime docs page says the default isNone(no snapshots). The docs disagree with the source, so set it explicitly. The source also forces a snapshot after 5,000 super-steps.- Do not change an existing thread's channel between delta and non-delta.
- Do not roll back to
langgraph<1.2after threads usedDeltaChannel: older versions cannot read those checkpoints. - Custom checkpointers,
prune,delete_for_runsandcopy_threadmust be delta-aware.
Treat it as an advanced optimization for long-running threads, measure the benefit on your own state, and re-read the "LangGraph runtime" page (Further resources) before you adopt it, since a beta feature can change.
5.7 Writing and testing a custom checkpointer#
If your standard database has no saver, you can write one: subclass BaseCheckpointSaver, implement the five core methods (put, put_writes, get_tuple, list, delete_thread and, for async graphs, the async twins), serialize through self.serde.dumps_typed and loads_typed, store the checkpoint metadata in full, and use WRITES_IDX_MAP from langgraph.checkpoint.base for the special write indexes. The docs' "Build a custom checkpointer" section walks through it. You do not have to guess whether yours is right: the separate package langgraph-checkpoint-conformance (version 0.0.2 at the time of writing, so expect change) runs a test suite against any saver.
# c02_conformance.py: run the checkpointer conformance suite against the built-in InMemorySaver
import asyncio
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.conformance import checkpointer_test, validate
@checkpointer_test(name="InMemorySaver")
async def make_saver():
yield InMemorySaver()
async def main():
report = await validate(make_saver)
report.print_report()
print("passed all base:", report.passed_all_base())
asyncio.run(main())Run it with uv run --with langgraph-checkpoint-conformance python c02_conformance.py. Output:
====================================================
Checkpointer Validation: InMemorySaver
====================================================
BASE CAPABILITIES
✅ delete_thread
✅ get_tuple
✅ list
✅ put
✅ put_writes
EXTENDED CAPABILITIES
⊘ copy_thread (not implemented)
⊘ delete_for_runs (not implemented)
⊘ prune (not implemented)
Result: FULL (5/5)
====================================================
passed all base: TrueThe report separates base capabilities, which every saver must pass (delete_thread, get_tuple, list, put, put_writes), from extended ones that are optional (copy_thread, delete_for_runs, prune). The built-in InMemorySaver passes all five base checks and implements none of the extended ones, which matches what the earlier samples found. Point validate at your own saver factory in a test in CI.
Part 6: Serializers, pickle and encryption#
Reference
Everything a checkpointer saves, the state values, interrupt payloads, resume values and Command.update data, has to be turned into bytes and back. That is the job of the serializer (the serde argument of every saver). The default is JsonPlusSerializer (from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer). It combines ormsgpack (a fast MessagePack encoder) with JSON, and it knows the types LangChain and LangGraph use: messages, datetimes, enums, UUIDs, Decimal, Pydantic v2 models, dataclasses, and numpy arrays. Its constructor is JsonPlusSerializer(*, pickle_fallback=False, allowed_json_modules=None, allowed_msgpack_modules=<default>).
6.1 What survives a round trip#
The sample puts typical values through dumps_typed and loads_typed, the pair of methods every saver uses.
# p10_serde.py: what the default serializer round-trips, what it refuses, and the pickle opt-in
import warnings
from dataclasses import dataclass
from datetime import datetime, timezone
from decimal import Decimal
from enum import Enum
from uuid import UUID
from langchain_core.messages import AIMessage, HumanMessage
from pydantic import BaseModel
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
class Colour(Enum):
RED = "red"
@dataclass
class Ticket:
id: int
tags: list[str]
class Invoice(BaseModel):
number: str
total: Decimal
class Plain: # an ordinary class: no dataclass, no Pydantic
def __init__(self):
self.x = 1
serde = JsonPlusSerializer()
samples = {
"dict/list/str/int/None": {"a": [1, 2.5, "x", None]},
"datetime (tz-aware)": datetime(2026, 11, 14, 9, 30, tzinfo=timezone.utc),
"UUID": UUID("12345678-1234-5678-1234-567812345678"),
"Decimal": Decimal("19.99"),
"set": {1, 2, 3},
"tuple": (1, "two"),
"bytes": b"\x00\x01",
"Enum": Colour.RED,
"dataclass": Ticket(1, ["urgent"]),
"pydantic model": Invoice(number="INV-1", total=Decimal("12.50")),
"LangChain messages": [HumanMessage("hi"), AIMessage("hello")],
}
for label, value in samples.items():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
try:
kind, blob = serde.dumps_typed(value)
back = serde.loads_typed((kind, blob))
ok = back == value
note = f"{kind}, round-trip equal: {ok}"
except Exception as exc:
note = f"FAILED {type(exc).__name__}: {str(exc)[:70]}"
print(f"{label:<24} {note}" + (f" [warning: {str(w[0].message)[:60]}]" if w else ""))
print()
try:
serde.dumps_typed(Plain())
print("Plain object: serialized")
except Exception as exc:
print("Plain object:", type(exc).__name__, str(exc)[:100])
pickling = JsonPlusSerializer(pickle_fallback=True)
kind, blob = pickling.dumps_typed(Plain())
print("with pickle_fallback=True:", kind, "->", type(pickling.loads_typed((kind, blob))).__name__)Output (the three log lines at the top go to the logger, not to standard output; they are the serializer warnings explained in 6.3):
Deserializing unregistered type __main__.Colour from checkpoint. This will be blocked in a future version. Set LANGGRAPH_STRICT_MSGPACK=true to block now, or add to allowed_msgpack_modules to allow explicitly: [('__main__', 'Colour')]
Deserializing unregistered type __main__.Ticket from checkpoint. This will be blocked in a future version. Set LANGGRAPH_STRICT_MSGPACK=true to block now, or add to allowed_msgpack_modules to allow explicitly: [('__main__', 'Ticket')]
Deserializing unregistered type __main__.Invoice from checkpoint. This will be blocked in a future version. Set LANGGRAPH_STRICT_MSGPACK=true to block now, or add to allowed_msgpack_modules to allow explicitly: [('__main__', 'Invoice')]
dict/list/str/int/None msgpack, round-trip equal: True
datetime (tz-aware) msgpack, round-trip equal: True
UUID msgpack, round-trip equal: True
Decimal msgpack, round-trip equal: True
set msgpack, round-trip equal: True
tuple msgpack, round-trip equal: False
bytes bytes, round-trip equal: True
Enum msgpack, round-trip equal: True
dataclass msgpack, round-trip equal: True
pydantic model msgpack, round-trip equal: True
LangChain messages msgpack, round-trip equal: True
Plain object: TypeError Type is not msgpack serializable: Plain
with pickle_fallback=True: pickle -> PlainReading the table of results:
- Plain data, datetimes, UUIDs,
Decimal, enums, sets, dataclasses, Pydantic models and LangChain messages all round-trip and compare equal. Return them from nodes without worry. - A tuple comes back as a list (
round-trip equal: False; the next sample prints[1, 'two']). JSON-style encodings have no tuple. If your state needs a real tuple, convert on read, or avoid tuples in state. This is a source of "my==check fails only after a resume" bugs. bytesuse their own type tag and round-trip.- An ordinary class (not a dataclass, not Pydantic) raises
TypeError: Type is not msgpack serializable: Plain. That is the error you see when a node returns something the serializer does not know, such as a database cursor, a client object, a lock, or a function. Keep state to data: put clients in closures, inRuntimecontext (08F.10, Part 9), or on the module. - The pickle fallback (
JsonPlusSerializer(pickle_fallback=True)) serializes the ordinary class aspickle. The docs show it for objects such as pandas DataFrames:InMemorySaver(serde=JsonPlusSerializer(pickle_fallback=True)).
6.2 What the checkpoint stores, and what that means for privacy#
State is stored as it is, in full. If a node puts a customer's address, a token or a medical-style note in state, it is now in your checkpoint tables, in every checkpoint of the thread, including old ones, and in your backups. Three consequences:
- Do not keep secrets in state. API keys and passwords belong in the environment or in
Runtimecontext (which is not saved in checkpoints, 08F.10, Part 9). A bearer token in state is a bearer token in the database. - Plan erasure (5.5) before you plan features.
- Encrypt at rest if the data is sensitive (6.4), in addition to the database's own disk encryption, which does not protect against someone who can run
SELECT.
Module 12 owns PII handling in depth.
6.3 Strict msgpack mode (security hardening)#
Deserializing a type that your code did not declare is how a tampered checkpoint could instantiate an unexpected class. The 1.2.22 source has a hardening switch for this. By default the serializer is permissive with a warning: it deserializes the type but logs a message such as
Deserializing unregistered type __main__.Ticket from checkpoint. This will be blocked in a future version. Set LANGGRAPH_STRICT_MSGPACK=true to block now, or add to allowed_msgpack_modules to allow explicitly: [('__main__', 'Ticket')]The warning tells you the plan: a future version will block unregistered types. To get that behaviour now, set LANGGRAPH_STRICT_MSGPACK=true in the environment, and list the types you accept with allowed_msgpack_modules=[(module, class_name), ...]. In strict mode, StateGraph.compile() builds the allowlist from your state, input, output and context schemas and applies it to the checkpointer for you, so a normal graph needs no manual list. The sample below shows the serializer itself, with the switch off and on:
# p11_strict.py: strict msgpack mode: what changes when LANGGRAPH_STRICT_MSGPACK=true, and the allowlist
import os
from dataclasses import dataclass
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
@dataclass
class Ticket:
id: int
print("STRICT env:", os.environ.get("LANGGRAPH_STRICT_MSGPACK"))
print("tuple comes back as:", JsonPlusSerializer().loads_typed(JsonPlusSerializer().dumps_typed((1, "two"))))
for label, serde in [
("default serializer", JsonPlusSerializer()),
("allowlisted Ticket", JsonPlusSerializer(allowed_msgpack_modules=[(Ticket.__module__, "Ticket")])),
]:
typed = serde.dumps_typed(Ticket(7))
try:
print(f"{label}: ->", serde.loads_typed(typed))
except Exception as exc:
print(f"{label}: {type(exc).__name__}: {str(exc)[:110]}")Deserializing unregistered type __main__.Ticket from checkpoint. This will be blocked in a future version. Set LANGGRAPH_STRICT_MSGPACK=true to block now, or add to allowed_msgpack_modules to allow explicitly: [('__main__', 'Ticket')]
STRICT env: None
tuple comes back as: [1, 'two']
default serializer: -> Ticket(id=7)
allowlisted Ticket: -> Ticket(id=7)Blocked deserialization of __main__.Ticket - not in allowed_msgpack_modules. Add to allowed_msgpack_modules to allow: [('__main__', 'Ticket')]
STRICT env: true
tuple comes back as: [1, 'two']
default serializer: -> {'id': 7}
allowlisted Ticket: -> Ticket(id=7)In strict mode the unlisted Ticket was blocked: it came back as the plain dict {'id': 7} and the logger said why, while the allowlisted copy was rebuilt as a Ticket. A blocked type degrades to data, so code that expects an object fails later with an AttributeError that does not mention serialization. Two practical rules follow: run your tests once with the variable set, and read your logs for the "Deserializing unregistered type" message before an upgrade makes it an error.
6.4 Encrypting checkpoints at rest#
EncryptedSerializer wraps another serializer and encrypts its output. The docs' recipe uses AES from pycryptodome:
from langgraph.checkpoint.serde.encrypted import EncryptedSerializer
serde = EncryptedSerializer.from_pycryptodome_aes() # reads the key from the LANGGRAPH_AES_KEY environment variableThis fragment shows only the constructor. The key can also be passed as key=... (bytes). The source requires a key of 16, 24 or 32 bytes (AES-128, 192 or 256) and uses AES in EAX mode. With no key, it raises ValueError: LANGGRAPH_AES_KEY environment variable is not set. For custom ciphers, implement CipherProtocol. The next sample proves that the data on disk becomes ciphertext, by searching the raw bytes of the stored checkpoint for a card number.
# p12_encrypt.py: EncryptedSerializer: checkpoints on disk become ciphertext
import os
import sqlite3
import secrets
from langchain_core.messages import AIMessage
from langgraph.checkpoint.serde.encrypted import EncryptedSerializer
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import START, MessagesState, StateGraph
# for the demo only: a throw-away random 32-byte key (AES-256). In real life it comes from your secret manager.
os.environ["LANGGRAPH_AES_KEY"] = secrets.token_hex(16) # 32 characters = 32 bytes
def chat(state: MessagesState):
return {"messages": [AIMessage(content="Your card ending 4242 was refunded.")]}
def build(serde):
conn = sqlite3.connect("secret.sqlite", check_same_thread=False)
saver = SqliteSaver(conn, serde=serde)
graph = StateGraph(MessagesState).add_node("chat", chat).add_edge(START, "chat").compile(checkpointer=saver)
return graph, conn
cfg = {"configurable": {"thread_id": "t"}}
graph, conn = build(EncryptedSerializer.from_pycryptodome_aes())
graph.invoke({"messages": [("user", "refund my card 4242")]}, cfg)
print("readable through the graph:", graph.get_state(cfg).values["messages"][-1].content)
raw = conn.execute("select type, checkpoint from checkpoints limit 1").fetchone()
print("stored type column:", raw[0])
print("'4242' visible in the raw checkpoint bytes:", b"4242" in raw[1])
conn.close()
plain = sqlite3.connect("secret_plain.sqlite", check_same_thread=False)
g2 = StateGraph(MessagesState).add_node("chat", chat).add_edge(START, "chat").compile(checkpointer=SqliteSaver(plain))
g2.invoke({"messages": [("user", "refund my card 4242")]}, cfg)
raw = plain.execute("select checkpoint from checkpoints order by rowid desc limit 1").fetchone()
print("unencrypted: '4242' visible in the raw checkpoint bytes:", b"4242" in raw[0])
del os.environ["LANGGRAPH_AES_KEY"]
try:
EncryptedSerializer.from_pycryptodome_aes()
except Exception as exc:
print("no key:", type(exc).__name__, exc)Run it with uv run python p12_encrypt.py (it needs pycryptodome). Output:
Downloaded pycryptodome
readable through the graph: Your card ending 4242 was refunded.
stored type column: msgpack+aes
'4242' visible in the raw checkpoint bytes: False
unencrypted: '4242' visible in the raw checkpoint bytes: True
no key: ValueError LANGGRAPH_AES_KEY environment variable is not set.The encrypted database's type column reads msgpack+aes, the string 4242 is not visible in the stored bytes, and the same graph, read through the saver, still returns the message. The unencrypted control run shows the number in plain text in the file. (The demo key is a random throw-away value generated in the script. In real code the key comes from your secret manager, and the script must never print or log it.)
Facts and cautions:
- Pass the same
serdeto every saver instance that reads the data, in every process. A process without the key cannot read the checkpoints. - Postgres. The docs' example passes
serde=toPostgresSaver.from_conn_string, but the 3.2.1 source of that method has no such parameter (the asyncAsyncPostgresSaver.from_conn_stringdoes). The form that matches the source for the sync saver is to create the connection yourself and use the constructor, which takesserde:
# illustrative: needs a running Postgres server; the DB_URI comes from your environment
import os
from psycopg import Connection
from psycopg.rows import dict_row
from langgraph.checkpoint.postgres import PostgresSaver
from langgraph.checkpoint.serde.encrypted import EncryptedSerializer
serde = EncryptedSerializer.from_pycryptodome_aes()
with Connection.connect(os.environ["DB_URI"], autocommit=True, prepare_threshold=0, row_factory=dict_row) as conn:
checkpointer = PostgresSaver(conn, serde=serde)
checkpointer.setup()This sample is illustrative: it needs a database. The autocommit=True and dict_row arguments are the README's requirements for hand-made connections (5.3). Verify the serde argument against the version you install.
- LangSmith deployments encrypt automatically when
LANGGRAPH_AES_KEYis present in the environment (docs). - Key rotation. The serializer in the source holds one key. If you need to rotate, plan a re-encryption job or a custom cipher, and check the docs for the current guidance: this lesson did not verify a rotation recipe.
- Encryption protects the data at rest, not in use. Anyone who can run your graph can read state through
get_state. It is a defence against database leaks and backups, not against your own code.
Part 7: The Store: long-term memory across threads#
The checkpointer remembers one conversation. The store remembers things that outlive and cross conversations: a customer's preferred language, the facts an agent learned about a project, a library of past solved tickets. It is a small, deliberately simple database: namespaced key-value documents, with filtering and, optionally, semantic search.
7.1 The data model#
| Concept | What it is |
|---|---|
| Namespace | A tuple of strings that works like a folder path: ("user_42", "memories") |
| Key | A string unique inside its namespace |
| Value | A JSON-serializable dict: your document |
Item |
What you get back: value, key, namespace, created_at, updated_at |
SearchItem |
An Item plus a score (only filled when you searched with a query) |
The store class is BaseStore (from langgraph.store.base import BaseStore), and the type annotation to use in your own signatures is always BaseStore, whatever backend you run. The methods, with the signatures of 1.2.22 (each has an async twin with an a prefix: aput, aget, asearch, adelete, alist_namespaces, abatch):
store.put(namespace, key, value, index=None, *, ttl=NOT_PROVIDED) -> None
store.get(namespace, key, *, refresh_ttl=None) -> Item | None
store.search(namespace_prefix, /, *, query=None, filter=None, limit=10, offset=0, refresh_ttl=None) -> list[SearchItem]
store.delete(namespace, key) -> None
store.list_namespaces(*, prefix=None, suffix=None, max_depth=None, limit=100, offset=0) -> list[tuple[str, ...]]
store.batch(ops) / store.abatch(ops)These signatures are shown for reading. put has no return value and never reports whether the key existed.
7.2 A tour of the API, with its traps#
# s01_store_api.py: the Store API on InMemoryStore: put, get, search, filter, list_namespaces, delete and the traps
from langchain_core.utils.uuid import uuid7
from langgraph.store.base import Item
from langgraph.store.memory import InMemoryStore
store = InMemoryStore()
ns = ("user_42", "memories")
store.put(ns, "pizza", {"text": "likes pizza", "kind": "food"})
store.put(ns, "dark", {"text": "prefers dark mode", "kind": "ui"})
store.put(ns, str(uuid7()), {"text": "lives in Chennai", "kind": "profile"}) # a time-ordered unique key
store.put(("user_42", "tickets"), "T-1", {"text": "refund for order 17", "kind": "ticket"})
store.put(("user_7", "memories"), "pizza", {"text": "hates pizza", "kind": "food"})
item = store.get(ns, "pizza")
print(type(item).__name__, "| key:", item.key, "| namespace:", item.namespace, "| value:", item.value)
print("created_at is datetime:", type(item.created_at).__name__, "| updated_at >= created_at:", item.updated_at >= item.created_at)
print("missing key ->", store.get(ns, "nope"))
# put on an existing key replaces the WHOLE value (it is not a merge) and bumps updated_at
store.put(ns, "pizza", {"text": "likes pizza with olives"})
print("after second put:", store.get(ns, "pizza").value, "(the 'kind' field is gone)")
print()
print("search(('user_42',)) matches by PREFIX:", sorted({i.namespace for i in store.search(("user_42",))}))
print("search(ns) returns", len(store.search(ns)), "items, oldest first:", [i.key for i in store.search(ns)][:2], "...")
print("filter kind=ui:", [i.key for i in store.search(ns, filter={"kind": "ui"})])
print("no query -> score:", store.search(ns)[0].score)
print("list_namespaces():", store.list_namespaces())
print("list_namespaces(prefix=('user_42',)):", store.list_namespaces(prefix=("user_42",)))
print("list_namespaces(suffix=('memories',)):", store.list_namespaces(suffix=("memories",)))
print("list_namespaces(max_depth=1):", store.list_namespaces(max_depth=1))
# the default limit is 10: results past it are silently dropped
for i in range(25):
store.put(("bulk",), f"k{i:02}", {"n": i})
print("25 items stored, search returns:", len(store.search(("bulk",))))
print("limit=100 returns:", len(store.search(("bulk",), limit=100)))
print("page 2 (offset=10, limit=10):", [i.key for i in store.search(("bulk",), limit=10, offset=10)][:3], "...")
print("order, first three:", [i.key for i in store.search(("bulk",))][:3])
store.delete(ns, "dark")
print("deleting a missing key is fine:", store.delete(ns, "never-existed"))
print()
for label, bad in [("empty namespace", ()), ("dot in label", ("user.42", "memories")),
("reserved root", ("langgraph", "x")), ("empty label", ("", "x"))]:
try:
store.put(bad, "k", {"a": 1})
print(label, "-> accepted")
except Exception as exc:
print(f"{label}: {type(exc).__name__}: {str(exc)[:80]}")
try:
store.put(ns, "k", "just a string")
except Exception as exc:
print("non-dict value:", type(exc).__name__, str(exc)[:80])
try:
store.put(ns, "k", {"a": 1}, ttl=5)
except Exception as exc:
print("ttl on InMemoryStore:", type(exc).__name__, str(exc)[:80])
print("supports_ttl:", store.supports_ttl)Item | key: pizza | namespace: ('user_42', 'memories') | value: {'text': 'likes pizza', 'kind': 'food'}
created_at is datetime: datetime | updated_at >= created_at: True
missing key -> None
after second put: {'text': 'likes pizza with olives'} (the 'kind' field is gone)
search(('user_42',)) matches by PREFIX: [('user_42', 'memories'), ('user_42', 'tickets')]
search(ns) returns 3 items, oldest first: ['pizza', 'dark'] ...
filter kind=ui: ['dark']
no query -> score: None
list_namespaces(): [('user_42', 'memories'), ('user_42', 'tickets'), ('user_7', 'memories')]
list_namespaces(prefix=('user_42',)): [('user_42', 'memories'), ('user_42', 'tickets')]
list_namespaces(suffix=('memories',)): [('user_42', 'memories'), ('user_7', 'memories')]
list_namespaces(max_depth=1): [('user_42',), ('user_7',)]
25 items stored, search returns: 10
limit=100 returns: 25
page 2 (offset=10, limit=10): ['k10', 'k11', 'k12'] ...
order, first three: ['k00', 'k01', 'k02']
deleting a missing key is fine: None
empty namespace: InvalidNamespaceError: Namespace cannot be empty.
dot in label: InvalidNamespaceError: Invalid namespace label 'user.42' found in ('user.42', 'memories'). Namespace la
reserved root: InvalidNamespaceError: Root label for namespace cannot be "langgraph". Got: ('langgraph', 'x')
empty label: InvalidNamespaceError: Namespace labels cannot be empty strings. Got in ('', 'x')
non-dict value: ValueError dictionary update sequence element #0 has length 1; 2 is required
ttl on InMemoryStore: NotImplementedError TTL is not supported by InMemoryStore. Use a store implementation that supports
supports_ttl: FalseGo through the traps one at a time.
puton an existing key replaces the whole value. It is not a merge. After the secondput, thekindfield ofpizzais gone. To update one field, read the item, change the dict, write it back, and see 7.8 for why that read-modify-write is racy.getof a missing key returnsNone, not an exception.deleteof a missing key is silent.searchmatches the namespace by prefix.search(("user_42",))returned items from both("user_42", "memories")and("user_42", "tickets"). That is useful (one call for everything a user owns) and dangerous if namespaces are not designed with it in mind (7.3).searchsilently truncates atlimit, default 10. The sample stored 25 items andsearchreturned 10, with no warning and no "more available" flag. Always passlimitexplicitly, and page withoffsetwhen you must read everything.- Without a
queryand afilter,searchis a listing. Order is backend-specific:InMemoryStorereturned insertion order (oldest first, so the most recent is last); the docs sayPostgresStoreorders byupdated_at, newest first. Do not rely on the order unless you sort yourself. filtermatches fields inside the value.filter={"kind": "ui"}founddark. Operators are covered in 7.4.scoreisNoneunless aquerywas used (printed asno query -> score: None).list_namespacesanswers "what namespaces exist": all of them, or filtered byprefix,suffixormax_depth.max_depth=1collapsed the namespaces to their first label, which is how you list users.- Namespace rules. The source raises
InvalidNamespaceErrorfor an empty namespace, an empty label, a label containing a period., and a root label of"langgraph"(reserved). A user id that is an email address (ada@example.com) fails because of the dot. Use an opaque id, or replace the dots yourself. - Keys are cast with
str(key). Values must be dicts; a string raised an unhelpfulValueError: dictionary update sequence element #0 has length 1; 2 is required. ttlonInMemoryStoreraisesNotImplementedError(TTL is not supported by InMemoryStore);supports_ttlisFalse. 7.6 covers TTL where it works.
7.3 Designing namespaces#
The namespace is your access-control and organization boundary. Everything below it is reachable from a prefix search, so design the tuple from the most general scope to the most specific.
| Namespace | Meaning |
|---|---|
(user_id, "memories") |
Everything the agent learned about one user (the docs' default shape) |
(user_id, application_context) |
The same, split by product area, such as (user_id, "billing") |
(org_id, user_id, "profile") |
Multi-tenant: the organization is the first label so one prefix scan returns a tenant |
("shared", "faq") |
Knowledge visible to everyone; write access is a separate decision |
(user_id, "episodes", task_type) |
Past examples by task, for few-shot recall |
Rules of thumb:
- Put the tenant or user id first, and take it from trusted context (
runtime.context.user_id), never from model output or from user text. A model that can choose the namespace can read another user's memories. 08F.8, 3.2 makes the same point for tools, and 08B.2, Part 5 develops the multi-tenant model fully. - The store has no access control of its own. There are no per-namespace permissions: whatever code holds the store can read every namespace. Isolation is something you enforce by always deriving the namespace from trusted context. On the LangSmith Agent Server there are authentication and authorization handlers for this (11A.5).
- Remember the prefix rule.
search(("acme",))returns everything under("acme", ...). A namespace of(user_id,)for one thing and(user_id, "x")for another mixes them in a prefix search. Give every namespace the same depth for the same kind of thing.
7.4 Filters, limits and pagination#
filter is a dict matched against fields in the stored value. Besides equality, the bundled stores support comparison operators. The sample below runs them against a SqliteStore, which also shows the persistent store in action (7.5).
# s02_sqlite_store.py: SqliteStore: survives restarts, filter operators, and TTL (minutes) with the sweeper
import time
from langgraph.store.sqlite import SqliteStore
with SqliteStore.from_conn_string("memory_store.sqlite") as store:
store.setup()
print("supports_ttl:", store.supports_ttl)
ns = ("shop", "orders")
for n in range(1, 6):
store.put(ns, f"o{n}", {"total": n * 10, "status": "open" if n % 2 else "shipped"})
print("filter status=open:", sorted(i.key for i in store.search(ns, filter={"status": "open"})))
for op in ("$eq", "$ne", "$gt", "$gte", "$lt"):
print(f"filter total {op} 30:", sorted(i.key for i in store.search(ns, filter={"total": {op: 30}})))
try:
store.search(ns, filter={"status": {"$in": ["shipped"]}})
except ValueError as exc:
print("filter $in ->", exc)
print("--- a new connection sees the data")
with SqliteStore.from_conn_string("memory_store.sqlite") as store:
print("orders still there:", len(store.search(("shop", "orders"), limit=50)))
print("--- TTL (in minutes): 0.02 minutes is about 1.2 seconds")
for omit in (False, True):
with SqliteStore.from_conn_string("memory_store.sqlite", ttl={"omit_expired": omit, "refresh_on_read": False}) as store:
store.put(("cache",), "soon-gone", {"v": 1}, ttl=0.02)
store.put(("cache",), "stays", {"v": 2})
time.sleep(2.2)
print(f"omit_expired={omit}: search ->", sorted(i.key for i in store.search(("cache",))),
"| get ->", store.get(("cache",), "soon-gone") is not None)
print(" sweep_ttl() deleted:", store.sweep_ttl(), "| search after sweep ->", sorted(i.key for i in store.search(("cache",))))
store.delete(("cache",), "stays")supports_ttl: True
filter status=open: ['o1', 'o3', 'o5']
filter total $eq 30: ['o3']
filter total $ne 30: ['o1', 'o2', 'o4', 'o5']
filter total $gt 30: ['o4', 'o5']
filter total $gte 30: ['o3', 'o4', 'o5']
filter total $lt 30: ['o1', 'o2']
filter $in -> Unsupported operator: $in
--- a new connection sees the data
orders still there: 5
--- TTL (in minutes): 0.02 minutes is about 1.2 seconds
omit_expired=False: search -> ['soon-gone', 'stays'] | get -> True
sweep_ttl() deleted: 1 | search after sweep -> ['stays']
omit_expired=True: search -> ['soon-gone', 'stays'] | get -> True
sweep_ttl() deleted: 1 | search after sweep -> ['stays']- Equality is
{"status": "open"}. Operators are written{"total": {"$gt": 30}}.$eq,$ne,$gt,$gteand$ltworked onSqliteStorein the 3.1.3 package;$inraisedValueError: Unsupported operator: $in. The docs show only simple equality filters, so check the reference for the store you use before you build on an operator. - Filtering is applied inside the store, so it respects
limitandoffsetonly after the filter. For a large collection, filter and page; do not read everything and filter in Python. - Combine
filterwith aquery(semantic search, Part 8) to restrict the candidates by metadata first, such as "memories of kindticket".
7.5 Backends: in-memory, SQLite and Postgres#
| Store | Import | Persistent | TTL | Semantic search | Notes |
|---|---|---|---|---|---|
InMemoryStore |
langgraph.store.memory |
No | No | Yes (needs an index) |
Dev and tests. Uses numpy for speed if installed, otherwise pure Python and a warning |
SqliteStore |
langgraph.store.sqlite |
Yes | Yes | Not verified here (7.5.1) | Ships in langgraph-checkpoint-sqlite 3.1.3; not listed in the docs' store integrations table |
PostgresStore / AsyncPostgresStore |
langgraph.store.postgres, langgraph.store.postgres.aio |
Yes | Yes | Yes, with the pgvector extension |
Production |
MongoDB (langgraph-store-mongodb), Redis, Upstash and others |
Separate packages | Depends | Depends | Depends | See the long-term-memory integrations index (Further resources) |
All of them implement BaseStore, so your nodes do not change when the backend does. PostgresStore mirrors the Postgres saver: PostgresStore.from_conn_string(conn_string, *, pipeline=False, pool_config=None, index=None, ttl=None) is a context manager, and setup() must be called on first use to create its tables (store, and store_vectors for embeddings). Vector search needs the pgvector extension (CREATE EXTENSION vector).
# illustrative: needs a running Postgres server (with pgvector for semantic search)
from langgraph.store.postgres import PostgresStore
with PostgresStore.from_conn_string(DB_URI) as store: # DB_URI from your environment
store.setup() # first use only
store.put(("user_42", "memories"), "pizza", {"text": "likes pizza"})
graph = builder.compile(checkpointer=checkpointer, store=store)This sample is illustrative: it needs a database, and DB_URI, checkpointer and builder come from the earlier samples. Use the same Postgres database for both the checkpointer and the store in production if you can: one connection pool to size, one backup, one set of credentials.
Differences you will notice between backends (seen in the runs): a SqliteStore item had created_at as a string and namespace as a list, where InMemoryStore gave datetime objects and a tuple. If you serialize items yourself (Item.dict()), normalize the values. A namespace that is a list instead of a tuple also means item.namespace == ("a", "b") is false on SQLite. Compare through tuple(...).
7.5.1 What was not verified
The index parameter exists on SqliteStore.from_conn_string, backed by the sqlite-vec package that the SQLite checkpoint package installs. In a quick keyless test on 14 November 2026 a query returned scores of None and 0.0 and not the ranking the same embedding function produced on InMemoryStore, so this lesson treats vector search on SQLite as unverified. In later tests it ranked correctly for some texts and returned score None for others (a short item such as "likes pizza"), so the behaviour looked data-dependent; treat it as unreliable until you have tested your own data, and consider reporting it upstream. For semantic memory use InMemoryStore for development and PostgresStore with pgvector for production, and check the docs before you try SQLite.
7.6 TTL: memories that expire#
Some memories should not live forever: a "user is on holiday until Friday" note, a cache of an expensive lookup. put(..., ttl=minutes) sets a time to live in minutes (a float is allowed), on stores that support it (SqliteStore and PostgresStore; store.supports_ttl tells you). By default reads and writes refresh the TTL (refresh_on_read). Store-level options come from TTLConfig(refresh_on_read, omit_expired, default_ttl, sweep_interval_minutes), passed as ttl={...} to the constructor.
The last part of the sample above stored an item with ttl=0.02 (about 1.2 seconds), waited 2.2 seconds, and read the store with omit_expired both False and True:
- Expired items stayed visible in
searchandget, in both settings, untilsweep_ttl()ran. It reported1deleted, after which the item was gone. - That means on
SqliteStore3.1.3 expiry is cleanup, not an access rule.omit_expiredis accepted but not read anywhere in the 3.1.3SqliteStoresource (the only expiry logic is theexpires_atcolumn, refresh on read and the sweep), so it has no effect there; check whether a newer release implements it. If an expired memory must never be returned, delete expired items on a schedule (callsweep_ttl()or start the sweeper) and also check the item's age in your own code. - Postgres: if you pass a
ttl=config you must callstart_ttl_sweeper()andstop_ttl_sweeper()yourself (docs).
7.7 Using the store inside a graph#
You can use the store from application code (store.put(...) in a script or an API handler), and you will, for administrative tasks like "show this user their memories" and "delete them". Inside a graph the recommended way is the Runtime object (08F.10, Part 9): compile with store=, declare runtime: Runtime[Context] in the node, and read runtime.store and runtime.context. The sample is a two-node graph: remember writes a memory when the user says "I like ...", and answer reads the memories back. A rule stands in for the LLM extractor, so everything is deterministic.
# s03_store_in_graph.py: long-term memory across threads: the store read and written from nodes
import re
from dataclasses import dataclass
from langchain_core.messages import AIMessage
from langchain_core.utils.uuid import uuid7
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.config import get_store
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.runtime import Runtime
from langgraph.store.base import BaseStore
from langgraph.store.memory import InMemoryStore
@dataclass
class Context:
user_id: str
def remember(state: MessagesState, runtime: Runtime[Context]):
"""Write path: a rule stands in for an LLM extractor ("I like X" becomes a memory)."""
text = state["messages"][-1].content
namespace = (runtime.context.user_id, "memories")
for fact in re.findall(r"I like ([\w ]+)", text):
runtime.store.put(namespace, str(uuid7()), {"fact": f"likes {fact.strip()}"})
def answer(state: MessagesState, runtime: Runtime[Context], store: BaseStore):
"""Read path: two ways to reach the same store: runtime.store and the injected `store` parameter."""
namespace = (runtime.context.user_id, "memories")
memories = [item.value["fact"] for item in runtime.store.search(namespace)]
assert store is runtime.store and get_store() is store # all three are the same object
return {"messages": [AIMessage(content=f"known facts: {memories}")]}
builder = StateGraph(MessagesState, context_schema=Context)
builder.add_node("remember", remember).add_node("answer", answer)
builder.add_edge(START, "remember").add_edge("remember", "answer").add_edge("answer", END)
store = InMemoryStore()
graph = builder.compile(checkpointer=InMemorySaver(), store=store)
def say(text, thread, user):
out = graph.invoke({"messages": [("user", text)]}, {"configurable": {"thread_id": thread}}, context=Context(user_id=user))
return out["messages"][-1].content
print(say("Hi. I like green tea", "thread-1", "ada"))
print(say("I like chess", "thread-1", "ada"))
print("new thread, same user:", say("What do I like?", "thread-2", "ada"))
print("new thread, other user:", say("What do I like?", "thread-3", "grace"))
print("namespaces in the store:", store.list_namespaces())
print("messages in thread-2 (short-term memory is per thread):", len(graph.get_state({"configurable": {"thread_id": "thread-2"}}).values["messages"]))known facts: ['likes green tea']
known facts: ['likes green tea', 'likes chess']
new thread, same user: known facts: ['likes green tea', 'likes chess']
new thread, other user: known facts: []
namespaces in the store: [('ada', 'memories')]
messages in thread-2 (short-term memory is per thread): 2Four things to see:
- Memory crossed threads.
thread-1wrote two facts;thread-2, a new conversation, read both. The other user's thread saw an empty list: the namespace came fromruntime.context.user_id, which the caller supplied per run. - Short-term memory did not cross.
thread-2has exactly two messages (its own). The store carries facts, not transcripts. - Three ways to reach the same store.
runtime.store, an injected parameter namedstoreannotatedBaseStore, andlanggraph.config.get_store()are the same object (theassertproves it). A node can use any;Runtimeis the one the docs recommend. For tools,ToolRuntime.storeand theInjectedStoreannotation do the same job. contextis per run and is not saved in checkpoints (08F.10, Part 9). Pass it again when you resume a thread, otherwiseruntime.contextisNoneandruntime.context.user_idraisesAttributeError. This is the usual "it worked, then it crashed after the approval" bug.
With create_agent the same objects exist as parameters: create_agent(model, tools, checkpointer=..., store=..., context_schema=...). Tools reach the store through ToolRuntime, as the next sample shows with a scripted model. It uses fakes.py from 08F.8, Part 1.3.
# a01_agent_memory.py: create_agent with a checkpointer and a store, and tools that write and read long-term memory
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.messages import AIMessage
from langchain.tools import ToolRuntime, tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from fakes import FakeToolCallingModel # the scripted model from 08F.8, Part 1.3
@dataclass
class Context:
user_id: str
@tool
def save_preference(key: str, value: str, runtime: ToolRuntime[Context]) -> str:
"""Remember a user preference for future conversations."""
runtime.store.put((runtime.context.user_id, "prefs"), key, {"value": value})
return f"saved {key}"
@tool
def get_preference(key: str, runtime: ToolRuntime[Context]) -> str:
"""Look up a saved user preference."""
item = runtime.store.get((runtime.context.user_id, "prefs"), key)
return item.value["value"] if item else "no such preference"
model = FakeToolCallingModel(messages=iter([
AIMessage("", tool_calls=[{"name": "save_preference", "args": {"key": "tone", "value": "formal"}, "id": "c1"}]),
AIMessage("Noted, I will stay formal."),
AIMessage("", tool_calls=[{"name": "get_preference", "args": {"key": "tone"}, "id": "c2"}]),
AIMessage("You asked for a formal tone."),
]))
store, checkpointer = InMemoryStore(), InMemorySaver()
agent = create_agent(model, [save_preference, get_preference], checkpointer=checkpointer, store=store,
context_schema=Context)
ctx = Context(user_id="ada")
r1 = agent.invoke({"messages": [("user", "Please always be formal.")]}, {"configurable": {"thread_id": "mon"}}, context=ctx)
print("thread mon:", r1["messages"][-1].content)
print("store now holds:", [(i.namespace, i.key, i.value) for i in store.search(("ada",))])
# a different thread (a different day): short-term memory is empty, long-term memory is not
r2 = agent.invoke({"messages": [("user", "What tone did I ask for?")]}, {"configurable": {"thread_id": "tue"}}, context=ctx)
print("thread tue:", r2["messages"][-1].content)
print("messages in thread tue:", [m.type for m in r2["messages"]])
print("what the tool read from the store on thread tue:", [m.content for m in r2["messages"] if m.type == "tool"])
print("messages in thread mon:", len(agent.get_state({"configurable": {"thread_id": "mon"}}).values["messages"]))thread mon: Noted, I will stay formal.
store now holds: [(('ada', 'prefs'), 'tone', {'value': 'formal'})]
thread tue: You asked for a formal tone.
messages in thread tue: ['human', 'ai', 'tool', 'ai']
what the tool read from the store on thread tue: ['formal']
messages in thread mon: 4The scripted model decided which tools to call, so what it says proves nothing. What proves the mechanism is the line what the tool read from the store on thread tue: ['formal']: a tool on a brand-new thread read, from the store, a value another thread had written. The thread mon kept four messages in its own checkpoint history and tue kept four of its own; only the preference crossed. With a real model, the model writes the key and value, so a precise tool description ("save only stable preferences the user states, never secrets") matters as much here as anywhere (08A.6).
7.8 Concurrency: read-modify-write is racy#
Two requests that read the same profile, change different fields and write back will lose one change: the last put wins and replaces the document. Three defences:
- Collection, not profile: store each fact as its own item with a unique key, so writers never touch the same key. Merge at read time.
- One writer per user: serialize memory writes for a user through a queue or a per-user lock in your application, which also helps the background-writer pattern (Part 9).
- Move the contended field to its own key. If one field is updated by many writers (a counter, a "last seen" time), give it a separate item so it does not share a document with slow-changing data. The store API has no compare-and-set, and this lesson did not verify transactional updates for any backend, so check the docs for the one you use before you assume atomicity.
7.9 The store on the Agent Server#
On the LangSmith Agent Server and in Studio (Part 11), the platform provides a base store automatically. Semantic search is switched on in langgraph.json:
{
"store": {
"index": {
"embed": "openai:text-embedding-3-small",
"dims": 1536,
"fields": ["$"]
}
}
}This is a configuration file, not Python. The docs print the model name as text-embeddings-3-small (with an extra "s") in one place, which is a typo: the model is text-embedding-3-small. Verify the current embedding model names on the provider's page before you copy any.
Part 8: Semantic search over memories#
Deep-dive
Exact keys are fine when you know what you are looking for (get(ns, "preferred_language")). An agent usually does not: it has the user's current message ("I'm hungry, any ideas for dinner?") and wants the memories that are relevant, which might say "likes pizza" or "vegetarian". That is semantic search: embed each memory when it is written, embed the query when it is read, and rank by vector similarity. Module 06 owns embeddings and similarity (02.3 is the concept lesson); this part is only how the store plugs in.
8.1 Turning it on: the index configuration#
A store does semantic search only if you give it an index configuration when you create it. The configuration (an IndexConfig typed dict) has three fields:
| Field | Meaning |
|---|---|
embed |
How to embed text. An Embeddings object (for example from init_embeddings), a function list[str] -> list[list[float]], an async version of it, or a "provider:model" string |
dims |
The vector length the model produces. It must match: the store does not detect a mismatch for you |
fields |
Which parts of each value to embed, as JSON paths. Default ["$"] (the whole document). Supports nesting: "metadata.title", "chapters[*].content", "authors[0].name" |
For real models the usual call is below. It is illustrative, because it needs an embedding provider and a key.
# illustrative: needs an embedding provider key (OPENAI_API_KEY) and the langchain-openai package
from langchain.embeddings import init_embeddings
from langgraph.store.memory import InMemoryStore
embeddings = init_embeddings("openai:text-embedding-3-small")
store = InMemoryStore(index={"embed": embeddings, "dims": 1536, "fields": ["text"]})
store.put(("user_123", "memories"), "1", {"text": "I love pizza"})
items = store.search(("user_123", "memories"), query="I'm hungry", limit=1)This sample is illustrative: it makes network calls to an embedding API, and what ranks first depends on the model. Dimensions for common models, from the source docstring: openai:text-embedding-3-small 1536, text-embedding-3-large 3072, text-embedding-ada-002 1536, Cohere embed-english-v3.0 1024 and its light variant 384. Embedding model names and prices change, so verify the current model on the provider's page (Module 06 lists how), and always copy dims from the model's documentation, not from this lesson.
8.2 A runnable demonstration with a hand-made embedding#
You can see every mechanic with no network. The embedding below is not a learned model: it is four hand-chosen "concept axes" (food, UI, travel, money), each with a small vocabulary, and a text's vector counts how many words it has on each axis, then normalizes to unit length so the dot product is the cosine similarity. A real embedding model has hundreds or thousands of learned axes and handles synonyms you never listed, but the store mechanics are identical.
# s04_semantic.py: semantic search over memories with a hand-made concept embedding (no network)
import math
from langchain_core.embeddings import DeterministicFakeEmbedding
from langgraph.store.memory import InMemoryStore
# Four "concept" axes. A real embedding model has hundreds or thousands of learned axes; the mechanics are identical.
AXES = {
"food": {"pizza", "hungry", "eat", "dinner", "restaurant", "pasta", "lunch", "olives"},
"ui": {"dark", "mode", "theme", "font", "screen", "interface", "light"},
"travel": {"flight", "hotel", "trip", "paris", "airport", "visa", "train"},
"money": {"refund", "invoice", "card", "payment", "charge", "price", "bill"},
}
def embed(texts: list[str]) -> list[list[float]]:
vectors = []
for text in texts:
words = set(text.lower().replace("'", " ").replace(".", " ").split())
v = [float(len(words & vocab)) for vocab in AXES.values()]
norm = math.sqrt(sum(x * x for x in v)) or 1.0
vectors.append([x / norm for x in v]) # unit length, so the score is cosine similarity
return vectors
store = InMemoryStore(index={"embed": embed, "dims": 4, "fields": ["text"]})
ns = ("user_1", "memories")
store.put(ns, "m1", {"text": "likes pizza and pasta for dinner", "source": "chat"})
store.put(ns, "m2", {"text": "prefers dark mode and a bigger font", "source": "chat"})
store.put(ns, "m3", {"text": "flew to Paris, needs a visa next trip", "source": "chat"})
store.put(ns, "m4", {"text": "asked for a refund on an invoice", "source": "ticket"})
for query in ("I'm hungry", "change the screen theme", "plan a trip", "billing problem with my card"):
hits = store.search(ns, query=query, limit=2)
print(f"{query!r:34} ->", [(h.key, round(h.score, 2)) for h in hits])
print("with a filter (source=ticket):", [(h.key, round(h.score, 2)) for h in store.search(ns, query="I'm hungry", filter={"source": "ticket"})])
print("no query -> score:", store.search(ns)[0].score, "| items listed:", len(store.search(ns)))
# per-item control: which fields are embedded, or none at all
store.put(ns, "m5", {"text": "loves pizza", "note": "dark mode"}, index=["note"]) # embed only 'note'
store.put(ns, "m6", {"text": "pizza pizza pizza"}, index=False) # never embedded
print("hungry again:", [(h.key, None if h.score is None else round(h.score, 2)) for h in store.search(ns, query="I'm hungry", limit=6)])
print("m6 is still reachable by key:", store.get(ns, "m6").value)
# without an index config, put(index=...) is ignored and query does not rank
plain = InMemoryStore()
plain.put(ns, "a", {"text": "likes pizza"}, index=["text"])
plain.put(ns, "b", {"text": "likes tea"})
print("no index config, query given:", [(h.key, h.score) for h in plain.search(ns, query="pizza")])
# an Embeddings object works too (this one is a deterministic hash, so it is NOT semantic)
hashed = InMemoryStore(index={"embed": DeterministicFakeEmbedding(size=8), "dims": 8})
hashed.put(ns, "x", {"text": "likes pizza"})
hashed.put(ns, "y", {"text": "likes tea"})
print("same text, same vector -> top hit for 'likes pizza':", hashed.search(ns, query="likes pizza", limit=1)[0].key)"I'm hungry" -> [('m1', 1.0), ('m2', 0.0)]
'change the screen theme' -> [('m2', 1.0), ('m1', 0.0)]
'plan a trip' -> [('m3', 1.0), ('m1', 0.0)]
'billing problem with my card' -> [('m4', 1.0), ('m1', 0.0)]
with a filter (source=ticket): [('m4', 0.0)]
no query -> score: None | items listed: 4
hungry again: [('m1', 1.0), ('m2', 0.0), ('m3', 0.0), ('m4', 0.0), ('m5', 0.0), ('m6', None)]
m6 is still reachable by key: {'text': 'pizza pizza pizza'}
no index config, query given: [('a', None), ('b', None)]
same text, same vector -> top hit for 'likes pizza': xRead the output as a list of rules.
- Ranking. "I'm hungry" ranked the pizza memory first (
m1, score 1.0); "change the screen theme" rankedm2; each query found its topic. The scores are cosine similarities in a unit-vector space, higher is better. - A query returns everything, ranked, up to
limit. The second result in each line had score0.0: the store does not drop irrelevant memories. A low-relevance memory injected into a prompt is noise at best and a wrong fact at worst, so apply a score threshold in your code (the docs' example usesitem.score > 0.2; choose yours from your embedding model and your own data, because score scales differ between models) and keeplimitsmall. - Filter plus query.
filter={"source": "ticket"}restricted the candidates before ranking: onlym4was eligible, and it scored0.0for the hunger query. Use filters for hard constraints (type, owner, status) and the query for relevance. - No query means no scores.
search(ns)listed items withscoreNone. - Per-item control.
put(..., index=["note"])embeds only thenotefield of that item (the textloves pizzawas therefore invisible to the hunger query, andm5scored0.0).put(..., index=False)stores the item without an embedding: it is reachable by key and by filter, and a query returns it last withscore None(them6entry), so it will look like a low-ranked result in a similarity search. TreatNoneas "not ranked". - No index config means no semantic search. On a store created without
index,put(index=[...])is ignored and aquerydoes not rank: both items came back withscore None. A missingindexis silent, which makes it a classic "semantic search returns random items" bug. Printstore.index_configwhen results look unsorted: it isNoneon a store with no index and a dict (embed,dims, and so on) on one with an index. - An
Embeddingsobject works too. The last line usesDeterministicFakeEmbeddingfromlangchain_core, a hash-based fake that needsnumpyand is not semantic: identical text gets an identical vector, so the exact-match query finds its item, and nothing else is meaningful. Use it in tests to check the plumbing, never to judge relevance.
8.3 What a write costs#
Semantic search moves cost to write time: every put of an indexed item calls the embedding function, which for a hosted model is a network call with a price and a latency. Consequences:
- Writing is no longer cheap. A node that stores ten memories per turn makes ten embedding calls (batched by the store where it can). Do bulk writes in the background (Part 9) and keep the embedded field short.
- Updating a memory re-embeds it. Prefer unique keys for new facts to repeated rewrites of one big document.
- Search embeds the query, one call per search.
- Changing the embedding model invalidates the index. Old vectors came from another model and have another meaning (and perhaps another
dims). Plan a re-embedding job: read every item, delete it, write it again under the new config. InMemoryStoreholds everything in RAM and uses numpy for similarity if it is installed (otherwise pure Python and a warning). It is for development and tests, and the vectors vanish on restart.- Which fields to embed matters. The default
["$"]embeds the whole JSON, including field names and metadata, which dilutes the meaning. Name the text field(s) infields.
8.4 Semantic search is retrieval: reuse what you know#
Memory retrieval is the same problem as RAG, at a smaller scale: chunk size (here, the size of one memory), embedding choice, thresholding, hybrid keyword and vector search, reranking, and evaluation all apply. Module 07 and 08F.9 teach them. Two differences are specific to memory:
- Memories are short and written by you, so the quality lever is how you write them: one atomic fact per item, in plain, self-contained wording ("Ada prefers formal replies"), not "she said that one thing". Poorly written memories cannot be rescued by a better embedding model.
- Memories go stale and contradict each other. A vector search will happily return both "lives in Chennai" and "moved to Pune". Deduplication, update and deletion policies are write-side work (08B.2, 4.3).
Part 9: Designing what an agent remembers#
Deep-dive
The store is a database, and a database does not decide what to put in it. That decision is the memory design, and 08B.2 teaches it in depth (write policies in 4.1, extraction in 4.2, forgetting in 4.4, memory safety in Part 6, evaluation in Part 7). 08B.4 is the compact version (the kinds, the ADD, UPDATE, DELETE and NOOP decisions, retrieval scoring), and 08B.5 covers how memory goes wrong. This part maps those ideas to the LangGraph store and gives the shapes the LangGraph docs use.
9.1 Three kinds of long-term memory#
The LangGraph memory concepts page borrows a three-way split from cognitive science: semantic, episodic and procedural memory. The full treatment is in 08B.2, 1.2 (the taxonomy) and 08B.4, Part 1 (the update rule each kind needs). In LangGraph all three are JSON documents in namespaces. What differs is how each one reaches the prompt:
- Semantic (facts about the user or the world, for personalization such as "prefers formal replies, lives in Chennai"): a short "what I know about you" block.
- Episodic (past experiences: what was tried and what happened): a few retrieved examples used as few-shot, or a LangSmith dataset.
- Procedural (rules and instructions): the agent's own system prompt, refined from feedback.
For semantic memory the docs describe two shapes, and the choice drives everything else. The profile shape is 08B.4's profile memory (one value per key, overwritten), and the collection shape is how you hold many episodic or semantic records:
| Profile | Collection | |
|---|---|---|
| Shape | One JSON document per user, updated in place | Many small documents, one per fact |
| Key | Fixed ("main") |
Unique per item (uuid7, or a hash of the text) |
| Read | get: simple, always the full picture |
search: needs relevance (semantic search, filters) |
| Write | Read, merge, write back (racy with several writers, 7.8) | Insert; update and delete need item ids |
| Strengths | Compact, easy to show the model, easy to audit | Higher recall, no size limit on what you can keep |
| Weaknesses | Grows without bound if you keep adding; the model must merge | Duplicates, contradictions, retrieval noise |
The sample below builds both shapes, an episodic store replayed as few-shot examples, and a procedural rules document, on a plain InMemoryStore. Everything is deterministic.
# m03_memory_kinds.py: the three memory types and the two semantic shapes, on a plain InMemoryStore
import hashlib
from langchain_core.utils.uuid import uuid7
from langgraph.store.memory import InMemoryStore
store = InMemoryStore()
user = "ada"
# --- semantic memory, PROFILE shape: one document, updated in place (fixed key) -----------------
def update_profile(**changes):
item = store.get((user, "profile"), "main")
profile = dict(item.value) if item else {}
profile.update(changes) # read-modify-write: fine with one writer per user
store.put((user, "profile"), "main", profile)
update_profile(language="English", tone="formal")
update_profile(city="Chennai")
print("profile:", store.get((user, "profile"), "main").value)
# --- semantic memory, COLLECTION shape: one small item per fact ---------------------------------
def remember_fact(text: str, *, dedupe: bool) -> str:
# a key from the normalized text makes repeats overwrite each other; a uuid7 key never collides
key = hashlib.sha1(text.lower().strip().encode()).hexdigest()[:12] if dedupe else str(uuid7())
store.put((user, "facts"), key, {"text": text})
return key
for text in ["Likes green tea", "likes green tea ", "Allergic to peanuts"]:
remember_fact(text, dedupe=True)
print("with dedupe keys :", [i.value["text"] for i in store.search((user, "facts"), limit=50)])
for text in ["Likes green tea", "likes green tea "]:
remember_fact(text, dedupe=False)
print("after uuid keys too:", len(store.search((user, "facts"), limit=50)), "items (the duplicates are back)")
# --- episodic memory: past experiences, stored as examples and replayed as few-shot -------------
store.put(("support", "episodes"), str(uuid7()), {"problem": "refund for a duplicate charge", "resolution": "refunded one charge, sent receipt"})
store.put(("support", "episodes"), str(uuid7()), {"problem": "cannot reset password", "resolution": "sent reset link, asked to check spam"})
episodes = store.search(("support", "episodes"), filter={"problem": "cannot reset password"}, limit=3)
shots = "\n".join(f"Problem: {e.value['problem']}\nResolution: {e.value['resolution']}" for e in episodes)
print("few-shot block built from episodes:\n" + shots)
# --- procedural memory: instructions the agent may rewrite after feedback ------------------------
store.put(("agent", "instructions"), "reply_style", {"rules": ["Be concise.", "Use the customer's name."]})
rules = store.get(("agent", "instructions"), "reply_style").value["rules"]
rules.append("Never promise refund dates.") # a reflection step would propose this after a bad review
store.put(("agent", "instructions"), "reply_style", {"rules": rules})
print("system prompt rules now:", store.get(("agent", "instructions"), "reply_style").value["rules"])profile: {'language': 'English', 'tone': 'formal', 'city': 'Chennai'}
with dedupe keys : ['likes green tea ', 'Allergic to peanuts']
after uuid keys too: 4 items (the duplicates are back)
few-shot block built from episodes:
Problem: cannot reset password
Resolution: sent reset link, asked to check spam
system prompt rules now: ['Be concise.', "Use the customer's name.", 'Never promise refund dates.']- Profile. Three
update_profilecalls merged into one document. The read-modify-write is a function of its own so that the "one writer per user" assumption sits in one place. - Collection and duplicates. With hash keys from the normalized text, "Likes green tea" and "likes green tea " collapsed into one item (the second overwrote the first; the trailing space shows which text won). With uuid keys, the same two facts became two items, and the duplicates came back. Which one you want depends on whether repeats mean the same fact (use a content key) or two separate events (use a unique key).
- Episodic. Past cases stored as
problemandresolutionpairs, retrieved with a filter (a semantic query would do the same by meaning) and formatted as a few-shot block for the prompt. Module 04 owns how to write few-shot prompts. - Procedural. The agent's instruction list lives in the store, so it can change without a deploy. The docs describe agents that rewrite their own prompt through reflection or meta-prompting: after negative feedback, a model proposes a new rule and the node appends it. Treat this one with care: a prompt that edits itself is a persistent prompt-injection target (08B.2, 6.1). Keep a human review or a validation step between a proposed rule and the saved one.
9.2 When to write: in the hot path or in the background#
The extraction step is taught in 08B.2, 4.2 and the write decisions in 08B.4, Part 3. This section adds the question those lessons leave open for a LangGraph app: where to run them.
| Hot path | Background | |
|---|---|---|
| What happens | The agent decides to save a memory while answering, usually by calling a tool | A separate process reads finished conversations and writes memories afterwards |
| Pros | Real time; the user can see and correct what was saved; transparent | No added latency or tool noise; can look at the whole conversation; can batch and deduplicate |
| Cons | Adds latency and tokens to the reply; the model may forget to call the tool, or save too much | Needs a trigger (time, a cron, a thread going idle, a manual button); memories are not available until it runs |
| Use when | The user expects "remember that" to take effect now | Quality and cost matter more than immediacy |
Many systems do both: a save_memory tool for explicit requests, and a nightly job for extraction. The docs point to two reference implementations, the langchain-ai/memory-agent and langchain-ai/memory-template repositories (listed in Further resources), and mention Trustcall (hinthornw/trustcall), a library for updating JSON documents with a model by patching instead of regenerating them, which suits the profile shape.
Hot path is the pattern of the save_preference tool in 7.7: a tool that calls runtime.store.put with a namespace from trusted context. Everything in 08A.6 about tool descriptions applies, and so does 08B.2, 4.6.
Background needs an extractor. The sketch below uses a real model to turn a finished conversation into atomic facts. It is illustrative: it needs a provider key and the output depends on the model.
# illustrative: needs a provider key; the extracted facts depend on the model
import os
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
from langchain_core.utils.uuid import uuid7
from langgraph.store.base import BaseStore
class Facts(BaseModel):
facts: list[str] = Field(description="Stable facts about the user, one per item, each self-contained. Empty if none.")
extractor = init_chat_model(os.environ.get("MEMORY_MODEL", "openai:gpt-6-luna")).with_structured_output(Facts)
def consolidate(store: BaseStore, user_id: str, transcript: str) -> int:
"""Run after a thread goes idle (a cron job or a queue worker), never inside the user's request."""
result = extractor.invoke(
"Extract stable facts about the user from this conversation. Skip passwords, card numbers and one-off requests.\n\n"
+ transcript
)
for fact in result.facts:
store.put((user_id, "facts"), str(uuid7()), {"text": fact, "source": "background"})
return len(result.facts)This sample is illustrative: it needs a key for the model named in the environment, and the model name comes from the course's table of IDs (change it freely). A production version adds the steps 08B.2 describes: skip memories that duplicate existing ones (search first), validate what is written (08B.2, 6.2), record where each memory came from, and let the user see and delete them (08B.2, 6.3).
9.3 Reading memories into the prompt#
Two ways to use what you stored, and they pair with the two shapes:
- Always-on: read the profile (or the top few memories for the user) at the start of each turn and put them in the system prompt. Simple and predictable; costs tokens on every turn.
- On demand: give the model a
search_memorytool, or search by the user's latest message inside a node, and include only what ranks above a threshold. Cheaper, but only as good as retrieval.
With create_agent, the always-on read is a @dynamic_prompt middleware that reads request.runtime.store (08F.8, 9.1). In a hand-built graph it is the answer node of the sample in 7.7. 08B.2, 4.5 to 4.8 covers the trade-offs, injection formatting and size budgets. A principle from there that is worth repeating: memory enters the prompt as untrusted data, because a memory can contain text written by an attacker earlier, so fence it and never let it override your instructions.
9.4 Memory is a feature with risks#
Long-term memory persists mistakes, creepiness and attacks as faithfully as facts. Before shipping it, decide and write down: what is not stored (secrets, health-style details, anything the user did not intend as a lasting preference), how long things live (TTL, 7.6, and the retention rule of 5.5), who can see and delete them, and how you will test that the agent uses them correctly and not excessively (08B.2, Part 7). Treat the namespace rule of 7.3 (trusted context, never the model) as non-negotiable, and the erasure path (delete thread and store items) as part of the definition of done. The failure modes (stale, conflicting and poisoned memories) are in 08B.5, Part 1, and the retention, encryption and deletion rules are in 08B.5, 2.5.
Part 10: Managing the short-term memory of a long thread#
Deep-dive
A checkpointer keeps the whole messages list forever and loads it on every turn. That is exactly what you want for continuity and exactly what you do not want after two hundred messages: the model is slow, the bill grows, quality falls ("lost in the middle", 02.7), and eventually the context window overflows. The docs say it plainly: persisting state does not automatically send all of it to the model. Deciding what the model sees is your job, and there are four tools. Module 04 owns context management as a discipline (selection, ordering and budgeting), and 08B.2, Part 2 covers working memory inside an agent run. The concepts behind the four tools below (what each one risks, what to keep word for word, how to probe for loss) are in 08B.3; this part is the LangGraph mechanics.
| Tool | Changes the state? | What it does | Cost |
|---|---|---|---|
| Trim | No: only what you send | Keep the last N tokens or messages for this model call | Free; loses old context for the model (but the state keeps it) |
| Delete | Yes | Remove messages from the saved state with RemoveMessage |
Free; irreversible for the live state |
| Summarize | Yes | Replace old messages with a model-written summary | One extra model call every so often |
| Filter or select | No | Custom logic: drop tool outputs, keep pinned messages, retrieve relevant ones | Whatever your logic costs |
10.1 Trimming with trim_messages#
trim_messages (from langchain_core.messages.utils import trim_messages, count_tokens_approximately) returns a shorter copy of a message list. The state is not touched: a node that trims before calling the model sends fewer messages but the thread still holds all of them. Its signature:
trim_messages(messages, *, max_tokens, token_counter, strategy="last", allow_partial=False,
end_on=None, start_on=None, include_system=False, text_splitter=None)strategy="last"keeps the most recent messages;"first"keeps the oldest.token_countersays how to measure:count_tokens_approximately(about four characters per token, no provider needed), a chat model (uses its tokenizer, where it has one), the string"approximate", or any function from a message list to an int.token_counter=lenmakesmax_tokensmean "number of messages".start_onandend_onforce the first or last kept message to be of a given type ("human",("human", "tool")). They exist to keep the history valid (below).include_system=Truekeeps the leading system message regardless of the budget.allow_partial=Truelets the trim cut inside a message's content blocks, which you rarely want.
The sample trims a ten-message support conversation, with a tool call and its result in each of two earlier turns, in seven different ways. It needs no model.
# m01_trim.py: trim_messages on a hand-built conversation (no model needed): strategy, start_on, end_on, tool pairs
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
from langchain_core.messages.utils import count_tokens_approximately, trim_messages
history = [
SystemMessage("You are a support agent.", id="s"),
HumanMessage("Where is order 17?", id="h1"),
AIMessage("", tool_calls=[{"name": "get_order", "args": {"id": 17}, "id": "c1"}], id="a1"),
ToolMessage("shipped yesterday", tool_call_id="c1", id="t1"),
AIMessage("Order 17 shipped yesterday.", id="a2"),
HumanMessage("And order 18?", id="h2"),
AIMessage("", tool_calls=[{"name": "get_order", "args": {"id": 18}, "id": "c2"}], id="a3"),
ToolMessage("packing", tool_call_id="c2", id="t2"),
AIMessage("Order 18 is being packed.", id="a4"),
HumanMessage("Thanks! Can I change the address?", id="h3"),
]
def show(label, msgs):
print(f"{label:<44}", [m.id for m in msgs], "~tokens:", count_tokens_approximately(msgs))
show("full history", history)
show("last, max_tokens=60", trim_messages(history, strategy="last", max_tokens=60, token_counter=count_tokens_approximately))
show("last, 60, start_on human", trim_messages(history, strategy="last", max_tokens=60, token_counter=count_tokens_approximately, start_on="human"))
show("last, 60, start_on human, include_system", trim_messages(history, strategy="last", max_tokens=60, token_counter=count_tokens_approximately, start_on="human", include_system=True))
show("last, 40, start_on human, end_on human/tool", trim_messages(history, strategy="last", max_tokens=40, token_counter=count_tokens_approximately, start_on="human", end_on=("human", "tool"), include_system=True))
show("first, max_tokens=40", trim_messages(history, strategy="first", max_tokens=40, token_counter=count_tokens_approximately))
# a counter that counts MESSAGES: max_tokens=4 then means "keep four messages"
show("last 4 messages (len as counter)", trim_messages(history, strategy="last", max_tokens=4, token_counter=len, start_on="human", include_system=True))
show("last 4 messages, NO start_on (broken pair?)", trim_messages(history, strategy="last", max_tokens=4, token_counter=len))
print("the original list is untouched:", len(history), "messages")
# the danger: a cut that separates a tool call from its result (an orphan ToolMessage is rejected by providers)
orphan = trim_messages(history, strategy="last", max_tokens=3, token_counter=len)
print("last 3 messages, no rules:", [(m.id, m.type) for m in orphan], "<- starts with a tool result")full history ['s', 'h1', 'a1', 't1', 'a2', 'h2', 'a3', 't2', 'a4', 'h3'] ~tokens: 131
last, max_tokens=60 ['a3', 't2', 'a4', 'h3'] ~tokens: 57
last, 60, start_on human ['h3'] ~tokens: 13
last, 60, start_on human, include_system ['s', 'h3'] ~tokens: 24
last, 40, start_on human, end_on human/tool ['s', 'h3'] ~tokens: 24
first, max_tokens=40 ['s', 'h1'] ~tokens: 20
last 4 messages (len as counter) ['s', 'h3'] ~tokens: 24
last 4 messages, NO start_on (broken pair?) ['a3', 't2', 'a4', 'h3'] ~tokens: 57
the original list is untouched: 10 messages
last 3 messages, no rules: [('t2', 'tool'), ('a4', 'ai'), ('h3', 'human')] <- starts with a tool resultThe lines to study:
last, max_tokens=60kepta3, t2, a4, h3: the tool-call message with its result, the answer and the user's last message. It begins with an assistant message, which some providers reject (they require the history to start with a user message). Pair this withstart_on="human".start_on="human"then dropped everything before the last human message that fits: onlyh3survived at 60 tokens, because the human message before it did not fit together with the tool turn. A hardstart_oncan shrink the context far more than the budget suggests. Choose the budget with that in mind.include_system=Trueput the system prompt back (s, h3). You almost always want it.end_on=("human", "tool")guarantees the list ends where a model call can follow.strategy="first"kept the oldest messages: occasionally useful (keep the original task statement), rarely a good default.token_counter=lencounted messages instead of tokens.- The last line shows the danger. Trimming to three messages with no rules produced
[t2, a4, h3]: it starts with a tool result whose originating tool call (ina3) was cut off. Providers reject an orphan tool result (the tool call and its result must stay together, 08A.2). Always trim withstart_on="human"(a human message is a safe boundary, since tool turns happen after it), and test your trim on a conversation that contains tool calls.
A node that trims before the model call looks like this (illustrative, because it calls a model):
# illustrative: needs a provider key; shows where trim_messages sits in a node
from langchain.chat_models import init_chat_model
from langchain_core.messages.utils import count_tokens_approximately, trim_messages
from langgraph.graph import MessagesState
model = init_chat_model("openai:gpt-6-luna") # or "anthropic:claude-haiku-5-5" or "google_genai:gemini-3.8-flash" (optional)
def call_model(state: MessagesState):
recent = trim_messages(
state["messages"],
strategy="last",
token_counter=count_tokens_approximately,
max_tokens=4000,
start_on="human",
end_on=("human", "tool"),
include_system=True,
)
return {"messages": [model.invoke(recent)]}This sample is illustrative: it needs a provider key (the prefixes are from 08F.5). Because the node returns only the new reply, the thread keeps its full history while each call sends a bounded window. That is "trim without deleting".
10.2 Deleting messages from the state#
To shrink the saved state, return RemoveMessage objects from a node. They work only on a key whose reducer is add_messages (so MessagesState or your own key declared that way), they delete by id, and REMOVE_ALL_MESSAGES clears the list (08F.10, 3.4).
from langchain.messages import RemoveMessage
from langgraph.graph.message import REMOVE_ALL_MESSAGES
def delete_old(state):
if len(state["messages"]) > 2:
return {"messages": [RemoveMessage(id=m.id) for m in state["messages"][:2]]}
def clear(state):
return {"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)]}These are fragments for reading. Rules:
- Messages need ids.
add_messagesassigns an id to any message that lacks one, so messages that went through the graph have them. Messages you build by hand and never added haveid=None. - Keep the history valid. Some providers need it to start with a user message, and an assistant message with tool calls must be followed by its tool results. Deleting
[:2]in a conversation that starts with a tool call and its result leaves an orphan. Delete whole turns, not arbitrary slices. - Deleting from state does not delete from history (10.5).
10.3 Summarizing: a manual node#
Trimming loses information; deleting loses it permanently. Summarizing compresses it: replace the old messages with a short summary and keep the last few verbatim (how summaries fail is in 08B.3, 3.3). The docs' manual recipe extends the state with a summary string, has a node call a model with a prompt such as "This is a summary of the conversation to date: ... Extend the summary ...", and returns the summary plus RemoveMessages for the old messages. The sample runs that logic with a stand-in summarizer (it lists the first words of each message), so you can see the state change turn by turn.
# m02_remove_summarize.py: shrinking STATE (not just the prompt): RemoveMessage, and a summarizing node
from langchain_core.messages import AIMessage, HumanMessage, RemoveMessage, SystemMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.graph.message import REMOVE_ALL_MESSAGES
class State(MessagesState):
summary: str # the running summary lives next to the messages
class FakeSummarizer:
"""Stands in for a chat model: 'summarizes' by listing the first words of each message."""
def invoke(self, messages):
return AIMessage(content="Summary: " + " | ".join(str(m.content)[:18] for m in messages if m.type != "system"))
summarizer = FakeSummarizer()
def chat(state: State):
summary = state.get("summary", "")
prefix = [SystemMessage(f"Earlier conversation: {summary}")] if summary else []
seen = prefix + state["messages"]
return {"messages": [AIMessage(content=f"(model saw {len(seen)} messages)")]}
def maybe_summarize(state: State):
if len(state["messages"]) <= 6:
return {} # nothing to do yet
old = state["messages"][:-2] # keep the last two, fold the rest into the summary
new_summary = summarizer.invoke([SystemMessage(state.get("summary", "")), *old]).content
return {"summary": new_summary, "messages": [RemoveMessage(id=m.id) for m in old]}
graph = (StateGraph(State).add_node("chat", chat).add_node("maybe_summarize", maybe_summarize)
.add_edge(START, "chat").add_edge("chat", "maybe_summarize").add_edge("maybe_summarize", END)
.compile(checkpointer=InMemorySaver()))
cfg = {"configurable": {"thread_id": "long-chat"}}
for i in range(1, 6):
out = graph.invoke({"messages": [HumanMessage(f"question number {i}")]}, cfg)
print(f"turn {i}: {out['messages'][-1].content:<26} messages kept in state: {len(out['messages'])} summary: {bool(out.get('summary'))}")
print("final messages:", [m.content for m in out["messages"]])
print("summary:", out["summary"][:110], "...")
# the checkpoints still hold the OLD states: history is not rewritten
sizes = [len(s.values.get("messages", [])) for s in graph.get_state_history(cfg)]
print("message count across checkpoints (newest first):", sizes[:8], "...")
# clearing everything
graph2 = (StateGraph(MessagesState).add_node("clear", lambda s: {"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)]})
.add_edge(START, "clear").add_edge("clear", END).compile())
print("after REMOVE_ALL_MESSAGES:", graph2.invoke({"messages": [HumanMessage("a"), HumanMessage("b")]})["messages"])turn 1: (model saw 1 messages) messages kept in state: 2 summary: False
turn 2: (model saw 3 messages) messages kept in state: 4 summary: False
turn 3: (model saw 5 messages) messages kept in state: 6 summary: False
turn 4: (model saw 7 messages) messages kept in state: 2 summary: True
turn 5: (model saw 4 messages) messages kept in state: 4 summary: True
final messages: ['question number 4', '(model saw 7 messages)', 'question number 5', '(model saw 4 messages)']
summary: Summary: question number 1 | (model saw 1 messa | question number 2 | (model saw 3 messa | question number 3 | ...
message count across checkpoints (newest first): [4, 4, 3, 2, 2, 8, 7, 6] ...
after REMOVE_ALL_MESSAGES: []- Turns 1 to 3 grew the state to two, four and six messages. At turn 4 the state exceeded six, so
maybe_summarizefolded all but the last two messages intosummaryand removed them:messages kept in state: 2,summary: True. - From then on the model sees
1 summary + recent messages(model saw 4 messagesat turn 5: the summary as a system message, plus the three kept). The conversation can run indefinitely at bounded size. - The history rows tell the other half. The last output line shows the number of messages in each saved checkpoint, newest first:
[4, 4, 3, 2, 2, 8, 7, 6]. The older checkpoints still hold 8, 7 and 6 messages. Deleting messages shrinks the live state, not the history (10.5). REMOVE_ALL_MESSAGESemptied the list in one step.
With a real model the summarizer is one call, and the choices are where quality lives: which model (a cheap one is usually enough), what the prompt asks to preserve (names, decisions, open questions, identifiers, not prose), how often to run (a threshold, not every turn), and whether summaries of summaries drift (they do; keep identifiers and decisions explicit). 08B.2, 2.4 discusses compression and its risks. The illustrative replacement for the stand-in:
# illustrative: needs a provider key; replaces FakeSummarizer in the sample above
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage
summarizer_model = init_chat_model("openai:gpt-6-luna")
def summarize(existing_summary: str, old_messages: list) -> str:
prompt = (
f"This is a summary of the conversation so far:\n{existing_summary}\n\n" if existing_summary else ""
) + "Extend or create the summary using the messages below. Keep names, decisions, ids and open questions.\n\n" + "\n".join(
f"{m.type}: {m.content}" for m in old_messages
)
return summarizer_model.invoke([HumanMessage(prompt)]).contentThis sample is illustrative: it calls a model, and what the summary says depends on the model.
The docs also show langmem's SummarizationNode and RunningSummary (pip install langmem). The package's latest release at the time of writing is dated 25 October 2025, much older than the current langgraph, so treat it as optional and check compatibility before adopting it. The manual node above, or SummarizationMiddleware below, has no extra dependency.
10.4 create_agent: trimming and summarizing as middleware#
In a hand-built graph you wrote the node. In create_agent (08F.8) the same ideas are middleware: a @before_model hook that trims, or the built-in SummarizationMiddleware. 08F.8, 8.8 teaches the middleware and its gotchas (above all: with the default trigger=None it never summarizes). This sample runs both against a scripted model and shows what each leaves in the saved thread after five turns.
It uses fakes.py from 08F.8, Part 1.3.
# a02_agent_trim_summarize.py: two ways to keep an agent's thread short: a before_model trim and SummarizationMiddleware
from langchain.agents import create_agent
from langchain.agents.middleware import SummarizationMiddleware, before_model
from langchain.messages import AIMessage, RemoveMessage
from langchain_core.messages.utils import trim_messages
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from fakes import FakeToolCallingModel
def run(middleware, summary_script=None, label=""):
chat = FakeToolCallingModel(messages=iter(AIMessage(f"answer {i}") for i in range(1, 20)))
agent = create_agent(chat, [], checkpointer=InMemorySaver(), middleware=middleware)
cfg = {"configurable": {"thread_id": label}}
for i in range(1, 6):
out = agent.invoke({"messages": [("user", f"question {i}")]}, cfg)
stored = agent.get_state(cfg).values["messages"]
print(f"{label}: {len(stored)} messages stored ->", [(m.type, str(m.content)[:28]) for m in stored])
@before_model
def keep_last_four(state, runtime):
kept = trim_messages(state["messages"], strategy="last", max_tokens=4, token_counter=len, start_on="human")
if len(kept) == len(state["messages"]):
return None
return {"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), *kept]}
run([], label="no middleware")
run([keep_last_four], label="before_model trim")
summarizer = FakeToolCallingModel(messages=iter(AIMessage(f"SUMMARY #{i}: the user asked several questions") for i in range(1, 9)))
run([SummarizationMiddleware(model=summarizer, trigger=("messages", 6), keep=("messages", 2))], label="SummarizationMiddleware")no middleware: 10 messages stored -> [('human', 'question 1'), ('ai', 'answer 1'), ('human', 'question 2'), ('ai', 'answer 2'), ('human', 'question 3'), ('ai', 'answer 3'), ('human', 'question 4'), ('ai', 'answer 4'), ('human', 'question 5'), ('ai', 'answer 5')]
before_model trim: 4 messages stored -> [('human', 'question 4'), ('ai', 'answer 4'), ('human', 'question 5'), ('ai', 'answer 5')]
SummarizationMiddleware: 6 messages stored -> [('human', 'Here is a summary of the con'), ('ai', 'answer 3'), ('human', 'question 4'), ('ai', 'answer 4'), ('human', 'question 5'), ('ai', 'answer 5')]- No middleware: ten messages saved, all of them, in order.
before_modeltrim: the hook replaced the whole history (RemoveMessage(id=REMOVE_ALL_MESSAGES)followed by the kept messages), so the state itself shrank to four. This is the pattern forcreate_agent: returning{"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), *kept]}replaces the list.SummarizationMiddleware: withtrigger=("messages", 6)andkeep=("messages", 2)the early turns became one human message that begins "Here is a summary of the conversation to date:" followed by the summary text, and the recent messages stayed. In the runs here the summary message carriedadditional_kwargs={'lc_source': 'summarization'}, which is how you can recognize it in a UI.- Facts about the middleware from the package signature (1.5.0):
SummarizationMiddleware(model, *, trigger=None, keep=("messages", 20), token_counter=count_tokens_approximately, summary_prompt=..., trim_tokens_to_summarize=4000, summarizer=None).triggerandkeepaccept("messages", n),("tokens", n)or("fraction", f), andtriggeralso accepts a list of conditions. The default summary prompt asks for session intent, a summary, artifacts and next steps. Read the 08F.8 section before you rely on it.
10.5 Deleted is not erased#
The history table in 10.3 contained a fact that matters for privacy and for security: old checkpoints keep the messages you removed from the live state. RemoveMessage, trimming and summarizing change the current state. Every earlier checkpoint is a snapshot of the state as it was, and it is still in the database, and still readable with get_state_history or with SQL, and still restorable by replay.
| You want to... | Do this |
|---|---|
| Keep the model's context small | Trim, delete or summarize (this part) |
| Erase a user's data | delete_thread for every thread of that user, and delete their store namespaces (5.5, 7.3). Also purge backups according to your policy |
| Reduce database size but keep threads usable | prune(..., strategy="keep_latest") on a saver that implements it, or DeltaChannel (5.6) |
| Remove one sensitive message from history | There is no per-checkpoint redaction API in this lesson's sources. Treat the thread as contaminated: delete it or keep it under the same protection as the data (encryption, 6.4) |
10.6 Choosing a strategy#
The order that works in general (clear tool results, then summarize, then truncate as a last resort) and the fresh-window-or-compaction choice are in 08B.3, 1.2 and 08B.3, 7.3. The table maps those choices to LangGraph's tools.
| Situation | Use |
|---|---|
| A support chat of 10 to 30 turns; the model must see the full recent exchange | Nothing, or a generous trim in the model call |
| Long threads; old details seldom matter | Trim the model's view (last, start_on="human", include_system=True), keep the state |
| Long threads; old decisions matter (a research session, a coding agent) | Summarize, with the summary written to preserve ids and decisions, or move durable facts to the store (Part 9) |
| You must bound storage and not only context | Delete plus pruning (5.5), or a new thread with a summary as its first message |
| Tool outputs dominate the size | Filter: replace old tool results with a placeholder in a before_model hook (08F.8 lists context-editing middleware; check the docs for its current behaviour) |
| Facts that must outlive the thread | The store, not the thread |
Part 11: Agents, subgraphs, deployment and legacy names#
Reference
11.1 create_agent and persistence#
create_agent returns a compiled graph (08F.8, 1.1), so everything in Parts 1 to 10 applies to it unchanged. The mapping:
| You want | Pass to create_agent |
Notes |
|---|---|---|
| Conversation continuity | checkpointer=InMemorySaver() (dev) or a Postgres saver (prod), and thread_id in the config |
Same rules as Part 1 |
| Human approval to survive a restart | A durable checkpointer | HumanInTheLoopMiddleware needs one (08F.8, 8.9) |
| Long-term memory | store=..., and context_schema for the user id |
Tools and middleware read it through ToolRuntime.store and request.runtime.store (7.7) |
| Shorter threads | SummarizationMiddleware or a before_model trim |
10.4 |
| Per-run identity | invoke(..., context=Context(user_id=...)) |
Not saved in checkpoints, pass it again on resume |
| A loop budget so a crash-and-retry cycle cannot run away | ModelCallLimitMiddleware |
The default recursion limit is 10,007 (08F.8, 7.5) |
The LangChain docs have their own pages on this, "short-term memory" and "long-term memory" for create_agent (Further resources), which describe the same machinery in LangChain terms. If you only ever use create_agent, you need a checkpointer and a store and almost nothing else from this lesson, plus the idempotency rules of Part 4 for your tools, because a tool that has a side effect is a node that may run twice.
11.2 Subgraphs and their persistence modes#
A subgraph is a graph used as a node inside another graph (08F.13). Only the parent needs a checkpointer. LangGraph propagates it to the child subgraphs automatically. What differs is how the child uses it, set by the checkpointer argument to the child's compile():
checkpointer= on the subgraph |
Name | Behaviour |
|---|---|---|
None (default) |
Per-invocation | Inherits the parent's checkpointer; interrupts and durable execution work within one call, but state does not accumulate between calls |
True |
Per-thread | The subgraph keeps its own history on the thread; state accumulates across calls. No parallel calls to the same per-thread subgraph (use ToolCallLimitMiddleware or disable parallel tool calls) |
False |
Stateless | No checkpointing. The docs say no interrupts and no durable execution; 08F.13, 2.6 ran it and the interrupt still paused and resumed, but earlier work re-ran. Do not rely on it |
This is a summary of the docs, from the persistence material in the LangGraph memory page. Two consequences for this lesson: time travel into a subgraph needs True (3.3), and get_state(config, subgraphs=True) is how you read the child's snapshot. 08F.13 owns the details and the multi-agent patterns.
11.3 Deployment: the server provides both#
On the LangSmith Agent Server (managed LangSmith Deployment, or self-hosted, 11A.5) you do not configure a checkpointer or a store: the server provides both, backed by its own database. The docs repeat this note on the persistence, checkpointers and stores pages. What you still do:
- Use
thread_idas before; on the server a thread is a first-class object with a status (idle,busy,interrupted,error) you can search. - Enable semantic search in
langgraph.json(7.9). - Set
LANGGRAPH_AES_KEYto encrypt checkpoints (6.4). - Keep your nodes idempotent: the server resumes after failures by the same replay rules.
If you self-host a graph in your own FastAPI or worker process, you choose and operate the saver and store (Postgres, 5.3 and 7.5), run setup() as a deployment step, and own pruning and retention (5.5).
11.4 The Functional API and persistence#
The Functional API (08F.14) uses the same checkpointer. @entrypoint(checkpointer=...) makes a function resumable, @task results are the saved units (4.4), and the entrypoint's previous argument and entrypoint.final give a short-term memory between calls on the same thread. The determinism rules of 4.5 apply to every entrypoint, because an entrypoint always replays from its beginning on resume.
11.5 Legacy: how to read old tutorials#
Older tutorials and answers use names that predate the checkpointer and store. They still appear in search results and in AI-generated code. Read them with this table, and do not start new code with them.
| You will see | What it was | What replaced it |
|---|---|---|
ConversationBufferMemory, ConversationBufferWindowMemory, ConversationSummaryMemory, ConversationSummaryBufferMemory (LangChain classic chains) |
Memory objects attached to LLMChain and ConversationChain, holding the whole history, a window, or a summary |
A checkpointer keyed by thread_id for the history, with trimming or summarizing (Part 10); the store for long-term facts |
RunnableWithMessageHistory and InMemoryChatMessageHistory |
A Runnable wrapper that loaded and saved a message list per session id | LangGraph's built-in persistence: the class emits a deprecation warning ("Use LangGraph's built-in persistence instead"), verified in langchain-core 1.8.0 (08F.7) |
MemorySaver |
The old name of the in-memory checkpointer | InMemorySaver. MemorySaver is kept as an alias, so old code still runs |
stream(..., checkpoint_during=True/False) |
Whether to save checkpoints during a run | durability="async" or "exit" (4.1); it emits LangGraphDeprecatedSinceV10 |
Interrupt.interrupt_id |
The id of an interrupt | Interrupt.id (source of 1.2.22) |
config["configurable"]["user_id"] (and any custom key) for per-run data |
Passing application data through the run config | context= and Runtime.context (thread_id stays in configurable) |
langmem's SummarizationNode |
An add-on package for summarization | The manual node (10.3) or SummarizationMiddleware (10.4). The package is still in the docs but was last released in October 2025 |
langgraph-checkpoint-duckdb |
A DuckDB saver | Not in the current integration table; last release January 2025. Use SQLite or Postgres |
MemorySaver() left in a deployed app |
Demos that become production | PostgresSaver or the managed server |
08F.15 collects the migration paths for the package-level changes (0.x to 1.x, create_react_agent to create_agent), and 08F.4 explains the package history.
Part 12: A production checklist and the failure gallery#
Reference
12.1 Decision table: what to use for what#
| Need | Use | Where |
|---|---|---|
| The chatbot should continue a conversation | Checkpointer plus a stable thread_id |
Parts 1, 2 |
| A run must survive a restart or pause for days | A durable checkpointer (Postgres), durability="sync" for steps you cannot repeat |
4.1, 5.3 |
| A human approves something before it happens | Checkpointer plus interrupt |
08F.12 |
| Let the user go back and try again | get_state_history, update_state, replay or fork |
Part 3 |
| An action must never run twice | Idempotency key from saved state, its own node after the decision | 4.3 |
| Several costly steps inside one node | @task for each |
4.4 |
| Tests and notebooks | InMemorySaver, InMemoryStore |
5.1 |
| A local tool or a single-process prototype | SqliteSaver (and AsyncSqliteSaver for async) |
5.2 |
| Multi-process production | PostgresSaver or AsyncPostgresSaver, and PostgresStore |
5.3, 7.5 |
| Customer data in state | Encrypt (EncryptedSerializer), keep secrets out of state |
Part 6 |
| Facts across conversations | The store, namespace from trusted context | Parts 7, 9 |
| Find memories by meaning | Store index config, score threshold, small limit |
Part 8 |
| The thread is too long for the model | Trim, summarize, or move facts to the store | Part 10 |
| Checkpoint storage is growing | Smaller state, retention job, prune, DeltaChannel |
5.5, 5.6 |
| Deploy on the managed platform | No saver or store to configure; langgraph.json for the index |
11.3 |
12.2 Pre-flight checklist#
- Thread ids come from something stable, are generated once, and carry no personal data.
- The saver is durable in production, created once per process, and swapped in at exactly one place. Postgres:
setup()is a deployment step, connections are hand-made withautocommit=Trueanddict_rowor come fromfrom_conn_string. durabilityis chosen deliberately for each kind of run, and a crash test (kill the process mid-run, 4.1) has been done once.- Every node is safe to run twice. External writes carry keys derived from saved state. Irreversible effects have their own nodes.
- Tasks and interrupts are not added, removed or reordered under threads in flight. Non-deterministic values are inside tasks.
- Everything in state serializes, the test suite runs once with
LANGGRAPH_STRICT_MSGPACK=true,pickle_fallbackis off, and sensitive state is encrypted. - Store access derives namespaces from trusted context.
searchalways has an explicitlimitand, for semantic search, a score threshold. - Retention: a job deletes or prunes old threads, and the erasure path deletes threads and store items.
- Context (
context=) is passed on every call, including resumes. - A migration plan exists:
NotRequiredkeys,flow_version, no renames of nodes that threads can be paused in. - Tests use
InMemorySaverandupdate_state(..., as_node=...)orbulk_update_stateto start in the middle of a flow (11A.5).
12.3 The failure gallery#
Messages quoted in code font were produced by the runs in this lesson on 14 November 2026 (long ones are shortened). The other rows are symptoms described from the behaviour shown earlier, not literal messages.
| Symptom or message | Cause | Fix |
|---|---|---|
| The bot "forgets" on every message | No checkpointer, or a new thread_id per request |
1.2: compile with a saver, generate the id once |
ValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, checkpoint_ns, checkpoint_id |
A checkpointer is set and the run config has no configurable |
Pass {"configurable": {"thread_id": ...}} |
KeyError: 'thread_id' |
configurable exists but has no thread_id (a typo) |
Spell the key exactly |
EmptyInputError: Received no input for __start__ |
invoke(None, config) on a thread with no durable checkpoint |
Start with real input; if a first run may have crashed, keep your own admission record (2.6) |
invoke(Command(...)) on a finished thread does nothing |
Command and None resume the latest checkpoint |
Pass a plain input dict to start a new turn |
TypeError: Invalid checkpointer provided. Expected an instance of BaseCheckpointSaver, True, False, or None ... |
A string or dict was passed as the checkpointer | Construct a saver object (Part 5) |
NotImplementedError: The SqliteSaver does not support async methods. Consider using AsyncSqliteSaver instead. |
An async graph with the sync saver | AsyncSqliteSaver or AsyncPostgresSaver |
NotImplementedError from prune or copy_thread |
The saver does not implement the optional method | Check the saver's docs; use delete_thread or your own job (5.5) |
The program hangs at exit after using AsyncSqliteSaver |
The connection was not closed | async with AsyncSqliteSaver.from_conn_string(...) |
| Postgres tables missing, or writes do not persist | setup() never ran, or a hand-made connection lacks autocommit=True and dict_row |
5.3 |
AttributeError: 'SyncPregelLoop' object has no attribute '_put_checkpoint_fut' |
durability="sync" passed to a graph with no checkpointer (1.2.22) |
Do not pass durability without a checkpointer |
| After a crash the thread is empty or missing | A crash before the first checkpoint was durable (exit or async) |
Use sync, or record admission yourself (4.1) |
| The charge or email happened twice | A node re-ran from its first line after a retry or resume | Idempotency keys from saved state (4.3), @task (4.4) |
lookup("bob") returned Ada's data after a resume, with no error |
The same task was called at the same position with different arguments (new order or new data); results match by task name and position, never by arguments | Never reorder tasks or interrupts under in-flight threads (4.5) |
| After a deploy, paused threads fail with "node not found" or lose a value | A node or state key was renamed | 4.6 and 08F.10, 14.1 |
TypeError: Type is not msgpack serializable: Plain |
State holds an object the serializer does not know | Store data, not objects; reference clients from context or module scope (6.1) |
| A value compares unequal after a resume (a tuple is now a list) | The serializer encodes tuples as lists | Use lists in state or convert on read |
| An object came back as a dict | Strict msgpack blocked the unregistered type | Register it in allowed_msgpack_modules, or let compile() derive the list from your schemas (6.3) |
InvalidNamespaceError: Invalid namespace label 'user.42' ... |
A . in a namespace label (an email as user id) |
Use an opaque id |
search returns only 10 items |
The default limit is 10, truncation is silent |
Pass limit, page with offset (7.2) |
Semantic search returns items in no useful order, scores are None |
The store has no index config, so query does not rank |
Create the store with index={"embed", "dims", ...} (8.1) |
| Irrelevant memories injected into the prompt | A query returns the top limit regardless of score |
Score threshold, small limit (8.2) |
NotImplementedError: TTL is not supported by InMemoryStore |
put(..., ttl=...) on a store without TTL |
Use SqliteStore or PostgresStore (7.6) |
| Expired items still returned | Expiry is cleanup until the sweeper or sweep_ttl() runs, even with omit_expired=True on SqliteStore 3.1.3 |
Run the sweeper and check age in code (7.6) |
| A summary was added but old messages are still in the database | Deleting changes state, not history | delete_thread, retention jobs (10.5) |
| An orphan tool result is rejected by the provider after trimming | The cut separated a tool call from its result | start_on="human" (10.1) |
runtime.context.user_id raises after a resume |
context is not saved in checkpoints |
Pass context= on resume (7.7) |
| Checkpoint storage grows fast | Full channel values per step, long messages lists |
5.5, 5.6 |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Adding a checkpointer gives my chatbot memory." | Only if you also pass the same thread_id on every turn. A new id per request is a new empty thread (1.2) |
| "The checkpointer and the store are two names for memory." | The checkpointer saves graph state per thread; the store saves application documents across threads. Different data, scope, lifecycle and API (1.1) |
"A new invoke on a thread starts fresh." |
Input is applied on top of the saved state through the reducers. Use a new thread_id to start fresh (2.2) |
"get_state_history lists the thread's checkpoints oldest first." |
Newest first, across all branches (2.3, 3.1) |
"update_state restores an old checkpoint." |
It creates a new checkpoint on a branch, and values pass through reducers. Nothing is rolled back (2.8, 3.1) |
| "Replay reads cached results." | Replay and fork re-execute every node after the checkpoint, including model calls, API calls and interrupts (Part 3) |
| "A checkpoint is saved inside a node." | Only at super-step boundaries. A node that fails re-runs from its first line (4.2) |
| "LangGraph gives me exactly-once execution." | It gives at-least-once. You get exactly-once effects with idempotency keys derived from saved state (4.3) |
"@task makes a node safe to repeat." |
A finished task is restored; a task that started but did not finish may run again. And results are matched by task name plus call position, never by arguments, so a task called at the same position with different arguments returns the old call's result silently (4.4, 4.5) |
| "The default saves every step safely." | The default async mode can lose the last checkpoint on a crash; exit loses the whole run's intermediate state; only sync commits before the next step (4.1) |
"InMemorySaver is fine for production if I run one server." |
It loses everything on every restart and deploy. Use Postgres (5.1, 5.3) |
"SqliteSaver works in an async graph." |
It raises NotImplementedError. Use AsyncSqliteSaver (5.2) |
"I can call prune on any saver." |
It is optional. SqliteSaver and InMemorySaver raise NotImplementedError (5.5) |
| "State is just my data, so any Python object can go in it." | It must serialize. An ordinary class raises TypeError, and a tuple comes back as a list (6.1) |
| "Pickle fallback is a convenient default." | Pickle executes code on load. Keep it off unless you control every writer (6.1) |
| "Removing messages removes them from the database." | The live state shrinks; old checkpoints keep them. Erase with delete_thread (10.5) |
"store.search returns everything matching." |
It returns at most limit items (default 10), silently (7.2) |
| "Semantic search returns only relevant memories." | It returns the top limit by score, however low. Apply a threshold (8.2) |
"Setting index on put turns on semantic search." |
Without an index config on the store, put(index=...) is ignored and queries do not rank (8.2) |
| "TTL means expired memories are never returned." | On SqliteStore 3.1.3 expired items stay visible until a sweep runs (7.6) |
Key takeaways#
- LangGraph has two memories: the checkpointer (graph state snapshots, scoped to a thread) and the store (namespaced key-value documents, shared across threads). Compile with either or both; on the managed server you configure neither.
- Memory exists only with a checkpointer and a stable
thread_idpassed every time. Input is applied on top of saved state through reducers. - A checkpoint is saved at each super-step boundary: a two-node graph saves four (input, step 0, after each node). Pending writes keep the work of nodes that succeeded when a sibling failed.
invoke(input)is a new turn,invoke(None)retries,invoke(Command(resume=...))answers an interrupt,invoke(None, snapshot.config)replays.get_state_historyis newest first and shows a tree.- Time travel re-executes the future: replay re-runs nodes after a checkpoint (including interrupts), fork changes state first with
update_state, which branches and never rolls back. durabilityisexit,async(default) orsync. A killed process lost everything inexit, most inasyncand nothing committed insync.- Nodes re-run from their first line. Make every effect idempotent with a key derived from saved state; put irreversible effects in their own node; use
@taskto save results of work inside a node; never reorder tasks or interrupts, or change the arguments of a repeated task, under in-flight threads. - Use
InMemorySaverfor tests,SqliteSaverfor local single-process use, Postgres for production. Run Postgressetup()once as a deployment step.delete_threadalways works;pruneandcopy_threadare optional. - Checkpoints store full state in every step. Keep state small, prune, and consider
DeltaChannel(beta; about 12 times smaller in the run here). - The serializer handles messages, dataclasses and Pydantic but turns tuples into lists and rejects arbitrary objects. Keep
pickle_fallbackoff, tryLANGGRAPH_STRICT_MSGPACK=true, and encrypt sensitive state withEncryptedSerializer. - The store is namespaced key-value with prefix search, filters, a silent
limitof 10, TTL on SQLite and Postgres, andRuntime.store,ToolRuntime.storeandget_store()for access. Derive namespaces from trusted context. - Semantic search needs an
indexconfig (embed,dims,fields), embeds on write, ranks without dropping low scores, and silently does nothing without the config. - Design memory deliberately: semantic, episodic and procedural; profile or collection; hot path or background; always as untrusted data in the prompt.
- Long threads: trim the model's view with
start_on="human", delete withRemoveMessage, summarize with a node orSummarizationMiddleware. Deleted from state is not erased from history.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Checkpointer | An object (a BaseCheckpointSaver) that saves graph state after every super-step, keyed by thread |
| Checkpoint | A saved snapshot of a thread's state at a super-step boundary |
| Thread | A sequence of runs that share accumulated state, identified by thread_id |
thread_id |
The key in config["configurable"] that selects a thread, the checkpointer's primary key |
StateSnapshot |
The named tuple returned by get_state: values, next, config, metadata, created_at, parent_config, tasks, interrupts |
get_state_history |
The method that yields a thread's checkpoints, newest first, across all branches |
update_state |
The method that writes values into a thread as a new checkpoint (through reducers), optionally as a named node |
as_node |
The update_state argument naming which node the update stands in for, which decides what runs next |
bulk_update_state |
Applies several StateUpdate super-steps in one call |
| Pending writes | The writes of tasks that finished in a super-step that did not complete, saved so a resume does not re-run them |
| Checkpoint namespace | The checkpoint_ns identifying which graph or subgraph a checkpoint belongs to ("" for the parent) |
| Time travel | Resuming from an earlier checkpoint, by replay or fork |
| Replay | Re-running the nodes after an old checkpoint with unchanged state |
| Fork | Changing state at an old checkpoint with update_state and resuming on a new branch |
| Durability mode | The durability argument (exit, async, sync) that sets when checkpoints are written |
| Durable execution | Running so that a stop at any moment can be continued without losing finished work or repeating effects |
| At-least-once execution | The guarantee that a step is attempted until it succeeds, possibly more than once |
| Idempotent | Safe to run more than once with the same effect as once |
| Idempotency key | A value, derived from saved state, that lets a service recognize and ignore a repeated request |
@task |
A Functional API decorator whose result is saved when it finishes and returned instead of re-running on replay |
| Determinism (in replay) | The requirement that a replayed node makes the same task and interrupt calls in the same order |
InMemorySaver |
The in-memory checkpointer for tests and demos (MemorySaver is the old alias) |
SqliteSaver / AsyncSqliteSaver |
SQLite-file checkpointers from langgraph-checkpoint-sqlite, sync and async |
PostgresSaver / AsyncPostgresSaver |
Production checkpointers from langgraph-checkpoint-postgres; setup() creates the tables |
JsonPlusSerializer |
The default serializer (msgpack plus JSON) with an optional pickle fallback and strict mode |
| Strict msgpack | The LANGGRAPH_STRICT_MSGPACK=true mode that blocks unregistered types when loading a checkpoint |
EncryptedSerializer |
A serializer wrapper that encrypts checkpoints at rest (AES via from_pycryptodome_aes) |
DeltaChannel |
A beta channel that stores per-step writes and periodic snapshots instead of the full value at every checkpoint |
Store (BaseStore) |
The cross-thread key-value memory interface with put, get, search, delete and list_namespaces |
| Namespace | The tuple of strings that addresses a group of store items, such as (user_id, "memories") |
Item and SearchItem |
The store's returned document (value, key, namespace, timestamps) and the same plus a score |
InMemoryStore / SqliteStore / PostgresStore |
Store backends: RAM, a SQLite file, and Postgres (with pgvector for semantic search) |
| Store TTL | A time to live in minutes on a store item, supported by the SQLite and Postgres stores and enforced by a sweep |
| Index configuration | The index={"embed", "dims", "fields"} argument that turns on semantic search in a store |
| Semantic, episodic and procedural memory | Facts, past experiences and rules: the three kinds of long-term memory |
| Profile and collection | One updated document per user, versus many small documents, the two shapes of semantic memory |
| Hot-path and background memory writes | Saving memories while answering (usually through a tool) versus afterwards in a separate job |
trim_messages |
A function that returns a shorter copy of a message list by token or message budget without changing state |
RemoveMessage |
A state update that deletes a message by id (or all, with REMOVE_ALL_MESSAGES) from an add_messages key |
| Summarization (of a thread) | Replacing old messages with a model-written summary, by a node or SummarizationMiddleware |
Exercises#
All of these run without an API key except Exercise 8. Use uv run python file.py.
- Why no memory? Take the sample in 1.2 and change the last four calls so that each generates a fresh
thread_idwithuuid4(). Predict what the third turn prints, run it, then fix it by generating the id once. Write one sentence on where a web app should keep that id. - Predict the counters. Build
START -> (fast, flaky) -> join -> ENDas in 2.1, with aflakynode that fails twice and then succeeds. Before running, write down how many times each node will have executed after the first call and twoinvoke(None, config)calls (the first fails, the second fails, the third run succeeds). A furtherinvoke(None, config)is a no-op that leaves the counters unchanged. Then run and check, and printsnapshot.tasksafter each failure. - Fork an answer. Build a three-node chain
plan -> draft -> reviewwith a counter indraft. Run it, then (a) replay from beforedraft, (b) fork beforedraftchanging the plan, (c) printsourceandparent_configfor every checkpoint. How many checkpoints are on each branch? Which branch doesget_state(config)return, and how do you get back to the first? - A charge that happens once. Write an in-memory "payment provider" (a dict keyed by idempotency key, counting real charges). Write a
chargenode that crashes once after calling the provider. Make two versions: the key isuuid4()created inside the node, and the key isf"charge:{state['order_id']}". Resume each withinvoke(None, config)and compare the real charge counts. Then add a node that generates and saves the key first, and explain when you would use it. - Break and fix determinism. Reproduce the
lookup("bob")result of 4.5 (one task called twice, so the same task function sits at each position). Then fix it so the code is safe to reorder: make the task arguments come from state (saved before the node ran) instead of from code that can change. Show the resume prints the right customers. - Serializer audit. Round-trip a dict, a tuple, a set, a
datetime, a dataclass, a Pydantic model and a plain class throughJsonPlusSerializer. Make a table of which survive unchanged. Then run again withLANGGRAPH_STRICT_MSGPACK=trueand withallowed_msgpack_modulesfor your dataclass. What changes for the unregistered ones? - Namespace safety. Build a graph with a
save_notetool whose namespace is(runtime.context.user_id, "notes"). Write tests that (a) two users cannot read each other's notes withsearch, (b) an email address asuser_idfails withInvalidNamespaceError, and fix it with an opaque id map, (c)searchwith 15 notes stored returns all 15 only when you passlimit. Then add a second version where the model supplies the user id, and show the cross-user read. - Semantic memory with a real model (needs a key). Replace the hand-made
embedin 8.2 withinit_embeddingsand a real provider model. Write 12 memories and 10 queries (some with no relevant memory). Record the score of the best hit for every query, choose a threshold that separates relevant from irrelevant hits, and report where it fails. Do the scores from one embedding model carry over to another? - Shrink and erase. Using the sample in 10.3 on a
SqliteSaverfile: run six turns, then print the message count of every checkpoint. Delete the thread withdelete_threadand confirm thatlistfinds no checkpoints. Then store a preference in aSqliteStorefor the same user and write the erasure function that removes both, with a test.
Answers
- With
uuid4()per call every turn is a new thread, so the third turn printsI have seen 1 user message(s): ['Thanks']. Generate the id once when the conversation starts and keep it where the client keeps conversation state: a conversation record in your database, or a value the UI stores and sends back with every message (1.2). fastruns once (its pending write is saved on the first attempt and reused),flakyruns three times (two failures and the success),joinonce. After each failuresnapshot.tasksshowsfastwith aresultandflakywith anerror, andnextis('flaky',)(2.1, 2.5).- (a) Replay re-runs
draftandreview; (b) the fork re-runs them on the new plan. Each branch gets a newforkorupdatecheckpoint whoseparent_configpoints at the checkpoint you started from, then one checkpoint per node.get_state(config)returns the checkpoint written last (the second branch). To return to the first branch, address its last checkpoint bycheckpoint_idthroughget_state_history, or fork again from its checkpoint (3.1). - With a
uuid4()key created inside the node, the retry generates a different key and the provider charges twice (two real charges). With the key from state, the second call finds the first key and returns its result: one real charge. A separate "generate and save the key" node is for cases with no business identity to derive a key from; the checkpoint after it protects the key, anddurability="sync"makes it survive a process crash (4.3). - Because the same task was called twice and results are matched by task name and position (not arguments), reordering the two
lookupcalls attached the first saved result to the first new call, sobob's call returnedada's data. The fix is to read the names from state (state["names"][0],state["names"][1]), written before the node ran, so every replay makes the same calls in the same order, and to add new tasks only after the existing ones (4.5). - Survive unchanged: dict, set,
datetime, dataclass, Pydantic model. Tuple comes back as a list. The plain class raisesTypeErrorunlesspickle_fallback=True. With strict mode on, the unregistered dataclass and Pydantic model come back as plain dicts until you add(module, "ClassName")toallowed_msgpack_modules(6.1, 6.3). - (a) Different first namespace labels mean
search((user, "notes"))never crosses; (b)ada@example.comcontains a., so use an opaque id such as a UUID mapped to the user; (c) the default limit of 10 silently truncates, solimit=100(or paging withoffset) returns all 15. If the model supplies the user id, it can name another user's namespace and read it. Isolation comes from deriving the namespace from trusted context only (7.2, 7.3). - Typical findings: relevant hits score clearly higher than irrelevant ones but the ranges overlap for vague queries, so a single threshold trades missed memories against noise; scales differ between embedding models, so a threshold tuned on one does not transfer; short, atomic, self-contained memories score better than long ones. Re-tune the threshold whenever the model changes (8.2, 8.3).
- The message counts per checkpoint grow, then drop at the turn where the summary replaced messages, and older checkpoints keep the larger counts. After
delete_thread,list(None)yields none of the thread's checkpoints. The erasure function must callcheckpointer.delete_thread(thread_id)for every thread of the user andstore.delete(...)for each item (or a search-and-delete over the user's namespaces); the test should assert both stores are empty for that user (10.5, 5.5).
Check yourself#
- What does a checkpointer save, what does the store save, and which one is scoped to a thread?The checkpointer saves snapshots of graph state after each super-step; the store saves application documents (key-value items in namespaces). The checkpointer is scoped to a thread, the store is shared across threads (1.1).
- A user says the bot has no memory. Name the two most likely causes.No checkpointer was compiled in, or the
thread_iddiffers between calls (typically a new id per request) (1.2). - What are the four ways to call
invokeon an existing thread, and what does each do?invoke(input, config)starts a new turn on the saved state;invoke(None, config)retries unfinished work from the latest checkpoint;invoke(Command(resume=...), config)answers an interrupt;invoke(None, snapshot.config)replays from that checkpoint (2.2). - Two nodes run in parallel and one raises. After the fix,
invoke(None, config)re-runs only the failed node. Why?The finished task's writes were saved as pending writes the moment it completed, so the resume loads them and runs only the unfinished task (2.5). - In which order does
get_state_historyreturn checkpoints, and why does it return more checkpoints than a single run produced after a fork?Newest first. History is a tree of all branches: every replay or fork adds checkpoints under a new branch, and none are deleted (2.3, 3.1). - What does
update_statedo to the history, how do reducers affect it, and what isas_nodefor?It creates a new checkpoint (sourceupdate) without rolling anything back. The values pass through reducers, so reduced keys accumulate.as_nodenames which node the update stands in for, which decides what runs next, and is needed on fresh threads and parallel ambiguities (2.8). - Why do replay and fork cost money, and what do they do to interrupts?They re-execute every node after the checkpoint, including LLM and API calls. Interrupts fire again and wait for a new
Command(resume=...)(Part 3). - Name the three durability modes. What does each lose when the process is killed?
exitwrites only when the run exits, so a killed process loses all intermediate state;async(default) writes in the background, so it can lose the most recent checkpoints;syncwrites before the next step, so what was committed survives (4.1). - What does "a node re-runs from its first line" mean for a node that charges a card, and what are two ways to make it safe?The node is run again from its first line after a retry or resume, so a charge made before the stop is made again. Fix it with an idempotency key derived from saved state, and by putting the charge in its own node after the decision (and a
@taskfor work inside a node) (4.2, 4.3, 4.4). - What does
@taskprotect, what does it not protect, and what silent failure does reordering task calls cause?A finished task's result is restored on replay, so its work is not repeated; a task that started but did not finish may run again, and plain code outside tasks always re-runs. Results match by task name plus call position, never by arguments, so a task called again at the same position with different arguments gets the old call's saved result with no error; a different task at that position simply runs again (4.4, 4.5). - Which saver would you use for tests, for a local desktop tool, and for production, and what must you do on first use of the production one?
InMemorySaverfor tests,SqliteSaver(orAsyncSqliteSaverin async code) for a local tool,PostgresSaverorAsyncPostgresSaverfor production, where you must callsetup()once (as a deployment step) and use a hand-made connection withautocommit=Trueanddict_roworfrom_conn_string(5.1 to 5.3). - Which three problems does the serializer section warn about, and what is strict msgpack mode?Tuples come back as lists; arbitrary objects raise
TypeErrorunlesspickle_fallback=True, which is a code-execution risk; unregistered custom types are loaded with a warning today. Strict mode (LANGGRAPH_STRICT_MSGPACK=true) blocks unregistered types, which then come back as dicts (Part 6). - What is a store namespace, why must it come from trusted context, and what are three things that surprise people about
search?A tuple of strings addressing a group of items, like a folder path. It must come from trusted context (for exampleruntime.context.user_id) because the store has no access control, and a model-chosen namespace can read another user's data. Surprises: silent truncation atlimit=10, prefix matching on the namespace, and backend-dependent ordering (7.2, 7.3). - What does a store need before semantic search works, and what does a query return when nothing is relevant?An
indexconfiguration (embed,dims,fields) on the store. A query returns the toplimititems regardless of score, so low-relevance items come back unless you apply a threshold (8.1, 8.2). - A thread has 300 messages and the model is slow. Name three options, and say what none of them does to old checkpoints.Trim the model's view (
trim_messages, withstart_on="human"), delete old messages withRemoveMessage, or summarize with a node orSummarizationMiddleware(or move facts to the store). None of them removes the messages from older checkpoints (Part 10, 10.5).
Further resources#
Official sources only. The LangGraph documentation is larger and moves faster than this lesson; where the docs are more complete (they are, for every backend integration and every store option), read them. 08F.17 is the closing lesson that says how.
- Persistence and durable execution: Persistence (also served at the old
durable-executionaddress), Checkpointers, Use time-travel, Fault tolerance (retries, timeouts, graceful shutdown), Backward compatibility (changing graphs under in-flight threads), LangGraph runtime (channels,DeltaChannel) - Memory: Stores, Add memory (short-term and long-term), Memory concepts, Context concepts
- LangChain pages for
create_agent: Short-term memory, Long-term memory - Backend integrations: Checkpointer integrations, long-term memory and store integrations
- API reference: checkpoints,
InMemorySaver,SqliteSaver,PostgresSaver,AsyncPostgresSaver,BaseCheckpointSaver,BaseStore,InMemoryStore,PostgresStore,Item,StateSnapshot,DeltaChannel - Packages:
langgraph-checkpoint,langgraph-checkpoint-sqlite,langgraph-checkpoint-postgres, and the source in thelibs/checkpoint,checkpoint-sqliteandcheckpoint-postgresfolders - Reference templates named by the docs:
langchain-ai/memory-agent,langchain-ai/memory-template - JavaScript: the same ideas exist in the JavaScript package (
@langchain/langgraph), with the same names for the checkpointer and store concepts; the JavaScript API details were not verified for this lesson - In this course: 08B.2 for memory design and a hand-built
MemoryStore, 08A.9, 6.2 for the durability checklist, 08F.8 forcreate_agentand its middleware, 08F.10 for state, reducers and super-steps, 08F.12 forinterrupt, retries and timeouts, 08F.13 for subgraph persistence, 08F.14 for@taskand@entrypoint, 11A.5 for testing and deployment, and Module 06 and Module 07 for the retrieval side of semantic search
← 08F.10: LangGraph Fundamentals | Module 08F overview | 08F.12: Human-in-the-Loop and Control Flow →