Persistence, checkpoints and threads
Overview
In the previous lesson, you learned how to build robust tools that interact with APIs, databases, and external services while handling failures and selecting tools dynamically.
However, even an agent with excellent tools has a fundamental limitation if its execution state disappears whenever an invocation finishes or a server crashes.
Imagine a customer support agent handling the following conversation:
- Customer: My order number is 7821.
- Agent: I found your order. How can I help?
- Customer: When will it arrive?
The third message assumes that the agent remembers the order number. Without conversation persistence, your application must reconstruct and supply the earlier information manually.
Now imagine that the agent has already retrieved the order, checked its shipping status, and prepared a refund request when the application crashes.
Should it repeat the entire workflow? Should it execute the refund operation again? How does it determine which operations have already completed?
These problems introduce one of LangGraph’s most important capabilities: persistence.
Persistence allows graph state and execution progress to remain available beyond an individual invocation.
LangGraph implements thread-scoped persistence through checkpointers. A checkpointer saves recoverable representations of graph execution called checkpoints, organized into independent threads.
Together, these concepts provide the foundation for conversational memory, failure recovery, human approval workflows, and historical execution inspection.
Persistence versus ordinary graph state
Graph state and persistent state are related but not identical.
During execution, state carries information between nodes. A graph can operate entirely in memory without retaining that information for future invocations.
A checkpointer extends the lifetime of that state by saving it outside the temporary execution context.
| Capability | Without a checkpointer | With a checkpointer |
|---|---|---|
| Sharing state between nodes | Supported | Supported |
| Automatic state restoration | No | Yes |
| Conversation continuity | Managed manually | Thread-based |
| Recovering unfinished execution | No built-in checkpoint recovery | Supported |
| Historical state inspection | Unavailable through checkpoints | Supported |
| Surviving process restarts | No | Depends on storage backend |
Persistence is not limited to messages. Any appropriate serializable information included in your graph state can be checkpointed, including extracted entities, workflow decisions, tool results, document references, and intermediate calculations.
Adding a checkpointer
Persistence is configured when compiling a graph.
For local development, LangGraph provides InMemorySaver, which requires no database or additional infrastructure.
Install the core packages:
pip install -U "langgraph>=1,<2" "langchain>=1,<2"The following examples target the LangGraph and LangChain 1.x APIs. The deterministic examples require no model API key. API usage has been checked against the official documentation, but the examples have not been executed in this lesson’s authoring environment.
Your first persistent graph
Consider a graph that maintains a running total. Each invocation supplies an amount, and the graph adds that amount to its existing total.
This example demonstrates how a checkpointer changes behavior across invocations.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
class CounterState(TypedDict):
amount: int
total: int
def accumulate(state: CounterState):
previous_total = state.get("total", 0)
return {
"total": previous_total + state["amount"]
}
builder = StateGraph(CounterState)
builder.add_node("accumulate", accumulate)
builder.add_edge(START, "accumulate")
builder.add_edge("accumulate", END)
stateless_graph = builder.compile()
print(stateless_graph.invoke({"amount": 10})["total"])
print(stateless_graph.invoke({"amount": 5})["total"])
checkpointer = InMemorySaver()
graph = builder.compile(checkpointer=checkpointer)
config = {
"configurable": {
"thread_id": "counter-001"
}
}
print(graph.invoke({"amount": 10}, config)["total"])
print(graph.invoke({"amount": 5}, config)["total"])
print(graph.invoke({"amount": 3}, config)["total"])Expected output:
10
5
10
15
18Without persistence, the second invocation starts without the previous total.
With persistence, LangGraph retrieves the existing thread state before processing each new input.
Understanding the execution sequence
When the persistent graph receives its second invocation, the runtime performs the following operations conceptually:
- Reads the supplied thread identifier.
- Retrieves the latest saved checkpoint for that thread.
- Restores the saved state and applies the new input.
- Executes the scheduled nodes.
- Applies node updates to the state.
- Saves execution progress through the checkpointer.
- Returns the resulting state.
You do not need to write database queries inside accumulate() or manually load the previous total.
The checkpointer integrates with the graph runtime and manages these operations automatically.
The following diagram illustrates the relationship between incoming requests, graph execution, and checkpoint storage.
Note: Compiling a graph with a checkpointer does not automatically make its storage durable across process restarts. That guarantee depends on the selected checkpointer backend.
Threads and thread_id
A thread is a logical container for related graph executions.
A chatbot conversation is a natural example of a thread. Each message sent by the user creates additional work within the same conversation.
The thread identifier tells LangGraph which previously saved execution state belongs to that conversation.
config = {
"configurable": {
"thread_id": "conversation-001"
}
}The thread_id is reserved execution configuration used by the persistence mechanism.
It is not a Python execution thread, an operating system thread, or an asynchronous task.
It also does not automatically identify or authenticate a user.
Understanding threads, runs, and checkpoints
These three concepts operate at different levels.
| Concept | Meaning | Example |
|---|---|---|
| Thread | A persistent sequence of related executions | Customer support conversation |
| Run | One execution of a graph | Processing a new customer message |
| Checkpoint | Saved state at an execution boundary | State after retrieving order details |
| Thread ID | Identifier used to locate a thread | chat-7821 |
| Checkpoint ID | Identifier for a particular saved checkpoint | Generated checkpoint identifier |
A conversation can contain many runs, and each run can produce multiple checkpoints.
For example, one customer message might cause an agent to execute a model node, an order lookup tool, and another model node. Those execution steps belong to the same run and thread.
The next customer message starts a new run on that existing thread.
Isolating multiple conversations
A single compiled graph and checkpointer can manage multiple conversations.
The following example maintains independent task lists using different thread IDs.
from operator import add
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
class TaskState(TypedDict):
new_task: str
tasks: Annotated[list[str], add]
def add_task(state: TaskState):
return {"tasks": [state["new_task"]]}
builder = StateGraph(TaskState)
builder.add_node("add_task", add_task)
builder.add_edge(START, "add_task")
builder.add_edge("add_task", END)
graph = builder.compile(checkpointer=InMemorySaver())
work = {"configurable": {"thread_id": "work"}}
personal = {"configurable": {"thread_id": "personal"}}
print(graph.invoke({"new_task": "Review API"}, work)["tasks"])
print(graph.invoke({"new_task": "Buy groceries"}, personal)["tasks"])
print(graph.invoke({"new_task": "Deploy service"}, work)["tasks"])
print(graph.invoke({"new_task": "Read a book"}, personal)["tasks"])Expected output:
['Review API']
['Buy groceries']
['Review API', 'Deploy service']
['Buy groceries', 'Read a book']Both conversations use the same graph definition, node implementation, and storage object. Their saved states remain separate because their thread identifiers differ.
Notice the reducer:
tasks: Annotated[list[str], add]The reducer accumulates new tasks instead of replacing the existing list.
Checkpointing restores previous values, but reducers determine how those values combine with new updates. Persistence does not automatically turn every state field into an append-only collection.
Choosing thread identifiers in production
Hardcoded identifiers are convenient for demonstrations but inappropriate for multi-user applications.
A practical approach is to generate an opaque identifier whenever a new conversation is created.
from uuid import uuid4
def create_conversation_id() -> str:
return str(uuid4())
thread_id = create_conversation_id()
config = {
"configurable": {
"thread_id": thread_id
}
}
print(config)The output contains a newly generated UUID that your application can use for subsequent requests.
Your application should maintain a durable association between the conversation ID and its authorized owner.
For example, an application database might contain:
| User ID | Thread ID | Conversation title |
|---|---|---|
| user-101 | UUID-A | Python questions |
| user-101 | UUID-B | Database design |
| user-202 | UUID-C | Technical support |
A single user may have many threads.
Using the user ID as the thread ID would incorrectly combine all conversations belonging to that user into one state history.
Before reading or invoking an existing thread, authenticate the caller and verify conversation ownership. A UUID makes accidental collisions unlikely, but possession of a UUID is not authorization.
Business-specific runtime data, such as user identity, tenant information, and permissions, belongs in validated application logic and runtime context, not arbitrary fields inside config["configurable"].
Building a chatbot with persistent conversation memory
LangGraph provides MessagesState, a predefined state schema that contains a message collection using the add_messages reducer.
This reducer supports accumulating new messages and replacing existing messages when matching message IDs are supplied.
Combining MessagesState with a checkpointer allows an ordinary chat model to participate in a multi-turn conversation without your frontend resending the entire history.
Installing the model integration
Install the OpenAI integration:
pip install -U "langgraph>=1,<2" "langchain[openai]>=1,<2"Configure your OpenAI API key in your environment:
export OPENAI_API_KEY="your-api-key"Use the equivalent environment-variable configuration for your operating system if necessary.
Implementing the chatbot
This example builds a real model-powered chatbot with two independent conversations.
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
model = init_chat_model("openai:gpt-5.4-mini")
def chatbot(state: MessagesState):
response = model.invoke([
SystemMessage(
content=(
"You are a helpful assistant. "
"Answer using the conversation history. "
"Do not invent personal details."
)
),
*state["messages"],
])
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("chatbot", chatbot)
builder.add_edge(START, "chatbot")
builder.add_edge("chatbot", END)
checkpointer = InMemorySaver()
graph = builder.compile(checkpointer=checkpointer)
def chat(thread_id: str, text: str):
config = {"configurable": {"thread_id": thread_id}}
result = graph.invoke(
{"messages": [HumanMessage(content=text)]},
config,
durability="sync",
)
print(f"User: {text}")
print(f"Assistant: {result['messages'][-1].content}\n")
chat("conversation-a", "My name is Maya.")
chat("conversation-a", "I am learning LangGraph.")
chat("conversation-b", "What is my name?")
chat("conversation-a", "What is my name and what am I learning?")Illustrative output:
User: My name is Maya.
Assistant: Nice to meet you, Maya!
User: I am learning LangGraph.
Assistant: Great! I can help you learn LangGraph.
User: What is my name?
Assistant: You haven't told me your name yet.
User: What is my name and what am I learning?
Assistant: Your name is Maya, and you are learning LangGraph.Model-generated wording will vary. The example requires valid credentials and access to the configured model.
Why the chatbot remembers previous messages
During the second invocation on conversation-a, the graph restores the previously saved human and assistant messages.
The incoming HumanMessage is merged into the existing message collection. Consequently, the chatbot node receives the accumulated conversation rather than only the newest message.
The model itself does not need to retain information between API requests. LangGraph reconstructs the context and supplies it to the model.
The system message is constructed inside the node on every invocation rather than appended to persistent state repeatedly.
Two important implementation details follow:
- Send only the new message when continuing an existing thread.
- Return only newly generated messages from the chatbot node.
Repeatedly submitting the complete transcript can create duplicates, especially when previously stored messages are reconstructed with different IDs.
Checkpoint architecture
To understand reliable recovery, you need to understand when checkpoints are created and what they contain.
Super-steps and execution boundaries
LangGraph executes graphs using a step-based scheduling model inspired by Pregel.
A super-step is an execution cycle in which scheduled nodes read available state, perform their work, and produce updates.
Nodes scheduled within the same super-step may execute concurrently. Their updates are applied at the step boundary according to the graph’s state channels and reducers.
In a sequential graph, individual nodes typically occupy separate super-steps.
In a parallel graph, multiple nodes can belong to the same super-step.
Therefore, saying that LangGraph saves state after every node is a useful introductory approximation, but it is not universally accurate.
Full checkpoints correspond to super-step boundaries.
The following diagram shows two parallel nodes contributing to one checkpoint before another node executes.
What a checkpoint contains
A checkpoint represents more than a dictionary of application values.
The persistence system retains information needed to reconstruct graph execution, including channel values, channel versions, execution tracking, and checkpoint identity.
When inspecting this information through graph.get_state(), LangGraph exposes a higher-level StateSnapshot.
Important snapshot fields include:
| Field | Purpose |
|---|---|
values |
Application state at the snapshot |
next |
Nodes scheduled to execute next |
config |
Configuration identifying the checkpoint |
metadata |
Execution information such as step and source |
created_at |
Snapshot creation timestamp |
parent_config |
Reference to the preceding checkpoint |
tasks |
Scheduled task information, errors, and interrupts |
These fields allow LangGraph to determine not only what information exists but also what work remains.
Observing checkpoints
The following example shows how a two-node workflow produces multiple snapshots during a single invocation.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
class OrderState(TypedDict):
order_id: str
status: str
def validate(state: OrderState):
return {"status": "validated"}
def process(state: OrderState):
return {"status": "processed"}
builder = StateGraph(OrderState)
builder.add_node("validate", validate)
builder.add_node("process", process)
builder.add_edge(START, "validate")
builder.add_edge("validate", "process")
builder.add_edge("process", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "order-7821"}}
graph.invoke(
{"order_id": "7821", "status": "received"},
config,
durability="sync",
)
snapshot = graph.get_state(config)
print("Latest state:", snapshot.values)
print("Next nodes:", snapshot.next)
history = list(graph.get_state_history(config))
print("\nCheckpoint timeline:")
for item in reversed(history):
print(
item.metadata["step"],
item.values.get("status", "<not initialized>"),
item.next,
)Expected output:
Latest state: {'order_id': '7821', 'status': 'processed'}
Next nodes: ()
Checkpoint timeline:
-1 <not initialized> ('__start__',)
0 received ('validate',)
1 validated ('process',)
2 processed ()The initial snapshots capture execution setup and input application. Subsequent snapshots capture progress through the workflow.
An empty next tuple indicates that no nodes remain scheduled in the completed execution.
We will explore snapshot inspection, filtering, and historical state management in a later lesson.
The checkpointer interface
Different storage backends integrate with LangGraph through a common checkpointer abstraction, BaseCheckpointSaver.
Its important low-level operations include:
put()to save checkpoint information.put_writes()to record individual task writes.get_tuple()to retrieve checkpoint records.list()to retrieve matching historical checkpoints.
Asynchronous implementations provide corresponding asynchronous operations.
Normally, application developers interact with compiled graphs rather than implementing these operations directly.
The checkpointer also handles serialization. LangChain message objects and ordinary structured Python data are supported by the default serialization machinery.
Avoid storing database connections, open files, network clients, or other live resources in graph state. Store identifiers and serializable results instead, and recreate or inject operational resources when nodes need them.
For additional architectural details, consult the official checkpointer documentation.
Pending writes and partial failures
Suppose two parallel nodes execute during the same super-step:
- The order lookup succeeds.
- The customer lookup fails.
Restarting both operations would waste the completed lookup.
LangGraph can retain individual successful task writes separately from the completed super-step snapshot. During ordinary recovery, successfully recorded work can be reused while unfinished work is retried.
These intermediate writes are not independent historical checkpoints.
Recovery still depends on which records reached storage before the failure and whether the underlying storage remains available.
Durability modes
Checkpointing introduces a trade-off between execution latency and recoverability.
LangGraph 1.x exposes three durability modes through graph execution methods.
| Mode | Persistence behavior | Relative latency | Crash recovery |
|---|---|---|---|
"exit" |
Flushes persistence when execution exits | Lowest overhead | No guaranteed intermediate recovery |
"async" |
Overlaps checkpoint writes with execution | Balanced | Recent progress may be lost |
"sync" |
Waits for checkpoint writes before advancing | Higher overhead | Strongest checkpoint guarantees |
The normal default is "async".
Exit durability
With durability="exit", state is persisted when execution terminates normally, exits with a handled execution error, or pauses for human input.
An abrupt process crash before persistence occurs can lose the entire current run’s progress.
This mode is suitable for inexpensive, reproducible workflows where intermediate recovery is unnecessary.
Asynchronous durability
With durability="async", checkpoint storage operations can overlap with subsequent computation.
This reduces waiting time between steps, particularly when storage involves network requests.
However, a process can fail while recent checkpoint writes are still outstanding. Recovery then depends on the last successfully persisted information.
Asynchronous durability is often a reasonable starting point for conversational workloads.
Synchronous durability
With durability="sync", the runtime waits for checkpoint persistence before proceeding to subsequent execution steps.
This improves recoverability for workflows involving expensive computation, long-running processing, or important business decisions.
The additional storage latency should be measured under realistic workloads.
Importantly, synchronous durability with InMemorySaver still cannot survive process termination. Synchronous writes to volatile memory remain volatile.
Recovering unfinished execution
This example simulates a temporary failure after an earlier node has completed. It uses synchronous durability to make the recovery boundary explicit.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
class ReportState(TypedDict):
report_id: str
status: str
attempts = {"prepare": 0, "publish": 0}
def prepare(state: ReportState):
attempts["prepare"] += 1
print("Preparing report")
return {"status": "prepared"}
def publish(state: ReportState):
attempts["publish"] += 1
print("Publishing report")
if attempts["publish"] == 1:
raise ConnectionError("Temporary service failure")
return {"status": "published"}
builder = StateGraph(ReportState)
builder.add_node("prepare", prepare)
builder.add_node("publish", publish)
builder.add_edge(START, "prepare")
builder.add_edge("prepare", "publish")
builder.add_edge("publish", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "report-001"}}
try:
graph.invoke(
{"report_id": "R001", "status": "received"},
config,
durability="sync",
)
except ConnectionError as error:
print("Execution failed:", error)
print("Saved status:", graph.get_state(config).values["status"])
result = graph.invoke(None, config, durability="sync")
print("Final status:", result["status"])
print("Execution counts:", attempts)
assert attempts["prepare"] == 1
assert attempts["publish"] == 2Expected output:
Preparing report
Publishing report
Execution failed: Temporary service failure
Saved status: prepared
Publishing report
Final status: published
Execution counts: {'prepare': 1, 'publish': 2}The prepare node does not need to run again because its completed state was saved.
The counters simulate an external dependency that fails temporarily. They are deliberately process-local test instrumentation, not persistent application state.
New input versus resuming execution
Reusing a thread ID does not necessarily mean resuming unfinished work.
The invocation input determines the intended behavior.
| Invocation | Purpose |
|---|---|
graph.invoke(new_input, config) |
Submit new work using existing state |
graph.invoke(None, config) |
Continue unfinished execution after a recoverable failure or static breakpoint |
graph.invoke(Command(resume=value), config) |
Supply a response to a dynamic interrupt |
graph.get_state(config) |
Inspect saved state without executing nodes |
Always distinguish a new conversational turn from a recovery operation.
Tip: Checkpointing does not guarantee exactly-once execution of external side effects. If a payment succeeds but its node crashes before recording completion, recovery may attempt the payment again.
Use stable idempotency keys, database uniqueness constraints, transactional outboxes, and reconciliation procedures for important external operations.
InMemorySaver: development only
InMemorySaver stores checkpoint information inside the Python process.
It is particularly useful for unit tests, tutorials, debugging, and experimenting with graph behavior because it requires no database setup.
Its principal limitation is the lifetime of its storage.
The following example demonstrates the difference between rebuilding a graph and replacing its checkpointer.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict):
count: int
def increment(state: State):
return {"count": state.get("count", 0) + 1}
def build_graph(saver):
builder = StateGraph(State)
builder.add_node("increment", increment)
builder.add_edge(START, "increment")
builder.add_edge("increment", END)
return builder.compile(checkpointer=saver)
config = {"configurable": {"thread_id": "demo"}}
saver = InMemorySaver()
graph = build_graph(saver)
print(graph.invoke({"count": 0}, config)["count"])
restored_graph = build_graph(saver)
print(restored_graph.invoke({}, config)["count"])
fresh_graph = build_graph(InMemorySaver())
print(fresh_graph.invoke({"count": 0}, config)["count"])Expected output:
1
2
1Rebuilding the compiled graph does not erase information when the original checkpointer is retained.
Replacing the checkpointer creates an independent, empty storage instance.
A process restart similarly destroys process-local checkpoint storage. Multiple server workers also maintain separate memory spaces unless they use a shared persistence backend.
| Backend | Storage | Survives restart | Typical use |
|---|---|---|---|
InMemorySaver |
Process memory | No | Testing and development |
SqliteSaver |
SQLite database | Yes, with file storage | Local persistent applications |
PostgresSaver |
PostgreSQL database | Yes, with durable database configuration | Production services |
The next lesson will implement SQLite and PostgreSQL checkpointing in detail.
Checkpointing versus long-term memory
Thread-scoped persistence is not the same as cross-conversation memory.
Consider a user who tells an assistant that they prefer concise answers in one conversation. A newly created thread does not automatically inherit that preference.
LangGraph provides a separate persistence abstraction called a store for application-defined information shared across threads.
| Checkpointer | Store |
|---|---|
| Preserves graph execution | Preserves application-defined records |
| Organized by thread | Organized by namespaces and keys |
| Supports workflow recovery | Supports cross-thread retrieval |
| Suitable for conversation history | Suitable for reusable user preferences |
A production assistant can use both systems simultaneously. For example, checkpoints preserve a particular support conversation while a store maintains authorized customer preferences across conversations.
See the LangGraph persistence documentation for the distinction between these abstractions.
A note on subgraphs and deployment
Persistence in subgraphs
When graphs contain nested workflows, checkpoint configuration determines how a child graph retains its internal state.
Subgraphs support three important compilation settings:
| Subgraph configuration | Behavior |
|---|---|
compile() or compile(checkpointer=None) |
Inherits persistence for each individual invocation |
compile(checkpointer=True) |
Retains internal state across calls within the thread |
compile(checkpointer=False) |
Disables checkpointing inside the subgraph |
The parent graph must have checkpointing enabled for inherited persistence to function.
Per-invocation persistence is appropriate for independent specialist tasks. Per-thread persistence is appropriate when a specialist must remember earlier interactions.
LangGraph uses checkpoint namespaces to distinguish nested execution state. The root graph uses an empty checkpoint_ns, while nested workflows receive their own namespaces.
Avoid concurrent invocations of the same per-thread subgraph when they would write to the same namespace.
Further details are available in the official subgraph documentation.
Persistence in deployed applications
When deploying through LangSmith Agent Server, persistence infrastructure is managed by the server. You generally export the graph without manually creating an in-memory checkpointer.
For independently hosted Python applications, your service must configure and maintain its selected storage backend.
Production architecture must also address concerns beyond checkpoint configuration:
- Thread ownership and tenant isolation.
- Concurrent requests targeting the same conversation.
- Database availability, backups, and recovery.
- Encryption and protection of sensitive state.
- Checkpoint retention and deletion policies.
- State schema compatibility between application releases.
Do not assume that multiple simultaneous invocations against one thread will automatically behave like sequential chat messages. Serialize or coordinate conflicting operations using an appropriate server strategy.
Common mistakes and production best practices
Creating a new checkpointer for every request
This prevents in-memory conversations from continuing and can introduce unnecessary database connection overhead with persistent backends.
Create storage resources according to the application lifecycle and reuse them appropriately.
Generating a new thread ID for every message
A new thread starts a separate state history. Generate an identifier when creating a conversation, then reuse it for subsequent turns.
Sending previously accumulated state repeatedly
Graph input is merged into saved state using the configured reducers. Resubmitting historical messages or accumulated lists can duplicate information.
Prefer incremental updates.
Storing excessive data in checkpoints
Large documents, binary files, and lengthy tool responses can substantially increase serialization overhead and storage consumption.
Persist references to large artifacts where possible, and keep only information necessary for continuing execution.
Ignoring conversation growth
A persistent message history grows over time. Persistence does not automatically summarize conversations or ensure that their contents fit the model’s context window.
Introduce deliberate context management and checkpoint retention policies.
Remember that removing messages from the latest state does not necessarily remove them from historical checkpoints.
Changing graph structure without considering saved execution
Checkpoints can refer to existing node names and state schemas. Renaming nodes or introducing incompatible state changes may affect unfinished threads.
Treat graph evolution as a production compatibility and migration concern.
Preparing for the next lesson
The chapter project is a chatbot that can restore previous conversations.
The chatbot implemented here establishes its first architectural requirement: independent conversation state that can be retrieved through a stable thread identifier.
However, its conversations remain available only while the in-memory checkpointer survives.
In the next lesson, SQLite and PostgreSQL checkpointers, you will replace volatile storage with database-backed persistence and learn how to retain conversations across application restarts.
The subsequent lessons will build on this foundation by inspecting and updating saved state, navigating checkpoint history, and using replay and forking to explore alternative execution paths.
Build a conversation-restoring chatbot
Build a chatbot that remembers conversation history using InMemorySaver and a unique thread ID for each conversation. Create two independent conversations, switch between them, and verify that each retains only its own messages. Rebuild the compiled graph using the same checkpointer and demonstrate that an existing conversation can still be restored.
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
def respond(state: MessagesState):
# TODO: Find the user's previous messages.
# Return an AIMessage containing the number of user messages.
raise NotImplementedError
def build_graph(checkpointer):
# TODO: Create the graph, register the node,
# connect the edges and compile with the checkpointer.
raise NotImplementedError
def send_message(graph, thread_id: str, message: str):
# TODO: Invoke the graph using the correct thread configuration.
# Return the latest assistant response.
raise NotImplementedError
checkpointer = InMemorySaver()
graph = build_graph(checkpointer)
# TODO: Send two messages to conversation-a.
# TODO: Send one message to conversation-b.
# TODO: Rebuild the graph using the original checkpointer.
# TODO: Restore conversation-a and send another message.
# TODO: Verify that the conversations remain independent.from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
def respond(state: MessagesState):
user_messages = [
message
for message in state["messages"]
if isinstance(message, HumanMessage)
]
return {
"messages": [
AIMessage(
content=f"User messages received: {len(user_messages)}"
)
]
}
def build_graph(checkpointer):
builder = StateGraph(MessagesState)
builder.add_node("respond", respond)
builder.add_edge(START, "respond")
builder.add_edge("respond", END)
return builder.compile(checkpointer=checkpointer)
def send_message(graph, thread_id: str, message: str):
config = {"configurable": {"thread_id": thread_id}}
result = graph.invoke(
{"messages": [HumanMessage(content=message)]},
config,
durability="sync",
)
return result["messages"][-1].content
def restore_conversation(graph, thread_id: str):
config = {"configurable": {"thread_id": thread_id}}
snapshot = graph.get_state(config)
return snapshot.values.get("messages", [])
checkpointer = InMemorySaver()
graph = build_graph(checkpointer)
response = send_message(graph, "conversation-a", "Hello!")
print(response)
assert response == "User messages received: 1"
response = send_message(graph, "conversation-a", "I am learning Python.")
print(response)
assert response == "User messages received: 2"
response = send_message(graph, "conversation-b", "Hello from another chat.")
print(response)
assert response == "User messages received: 1"
# Recreate the compiled graph without replacing the checkpointer.
restored_graph = build_graph(checkpointer)
history = restore_conversation(restored_graph, "conversation-a")
assert len(history) == 4
print("\nRestored conversation:")
for message in history:
print(f"{message.type}: {message.content}")
response = send_message(
restored_graph,
"conversation-a",
"Continue our conversation.",
)
print(response)
assert response == "User messages received: 3"
assert len(restore_conversation(restored_graph, "conversation-a")) == 6
assert len(restore_conversation(restored_graph, "conversation-b")) == 2
print("All persistence and thread isolation checks passed.")Summary
- A checkpointer preserves graph state and execution information across invocations.
- LangGraph creates logical checkpoints at super-step boundaries rather than after every Python statement.
- A thread ID identifies an independent sequence of graph executions and their accumulated state.
- State reducers determine how incoming updates combine with previously checkpointed values.
- InMemorySaver supports local experimentation but cannot survive a process restart.
- Durability modes control when checkpoint writes occur and how much progress can be recovered after failures.
- Production persistence requires durable storage, secure thread ownership, and idempotent external operations.