Module 3 · Persistence & memory

Threads and conversation memory

5 min read

With a checkpointer, each run is attached to a thread. The thread is LangGraph's unit of memory: everything that happens in a thread accumulates in its state, and each new run on that thread starts where the previous one stopped. That is how a chatbot "remembers" the conversation.

The thread_id

The thread is specified in each call's configuration:

config = {"configurable": {"thread_id": "conversation-42"}}

await graph.ainvoke({"messages": [("user", "Where is my order ORD-1002?")]}, config, context=ctx)
await graph.ainvoke({"messages": [("user", "And when will it arrive?")]}, config, context=ctx)

On the second call, LangGraph loads the thread's last checkpoint for conversation-42, applies the input as an update of that state, then runs the graph. Thanks to the add_messages reducer, the new message is appended to the history: the model sees the whole conversation, and the already known order number (order_id in the state) is reused even if the customer doesn't repeat it.

This is important to understand: the input doesn't overwrite the state, it goes through the reducers. A key without a reducer is replaced; a key with a reducer is combined.

Choosing thread ids

The thread_id is a free-form string. Choosing it is an architectural decision:

StrategyExampleConsequence
One conversation = one threadchat-<uuid>The standard chatbot case
One ticket = one threadticket-8812All exchanges on a ticket share memory, whatever the channel
One customer = one threadcustomer-cus_leaInfinite memory… and a history that grows forever: avoid
One task = one threadrefund-ORD-1003A long business workflow, with its approvals

For Relay, a support conversation is a thread. Memory that must survive from one conversation to the next (the customer's language, their preferences) belongs to another mechanism, the store, presented in the next lesson.

Two security rules:

  • Never trust a thread_id supplied by the client without checking that it belongs to them. Otherwise anyone can read or continue someone else's conversation by guessing its id. Use random ids and associate them with the authenticated user.
  • Don't encode personal data in the thread_id (no email address): it shows up in logs and traces.

Reading a thread's state

snapshot = await graph.aget_state(config)
snapshot.values      # current state: messages, intent, status…
snapshot.next        # nodes left to run: () if the run is complete
snapshot.tasks       # pending tasks, with any interrupts
snapshot.metadata    # step, origin…
snapshot.config      # the configuration that points to exactly THIS checkpoint

Relay's server exposes this read on GET /threads/{id}: status, messages, pending approvals, audit log. It is the basis of any supervision interface.

The context window problem

Conversation memory has a downside: the history grows every turn, and the whole history is sent to the model on every call. A long conversation becomes slow, expensive, and eventually exceeds the context window. Three strategies, which can be combined:

1. Trim at call time. Keep the full history in the state, but send only the last N messages to the model. LangChain provides trim_messages, which cuts by token count while respecting structure (never separating a tool call from its result):

from langchain_core.messages import trim_messages

recent = trim_messages(
    state["messages"], max_tokens=8000, strategy="last", token_counter="approximate",
    start_on="human", include_system=False,
)
response = await model.ainvoke([system, *recent])

token_counter="approximate" estimates the token count locally, with no network call: the right choice on an agent's critical path. Passing the model itself (token_counter=model) gives an exact count, but may cost an API call each turn.

2. Prune the state. Actually delete old messages with RemoveMessage:

from langchain_core.messages import RemoveMessage


def prune(state: SupportState) -> dict:
    old = state["messages"][:-20]
    return {"messages": [RemoveMessage(id=m.id) for m in old]}

3. Summarize. A dedicated node replaces old messages with a summary produced by a fast model, stored in a summary key and injected into the system prompt. It is the most faithful strategy for long conversations, at the cost of an extra call from time to time.

On the API side, some providers also offer automatic server-side context compaction; it doesn't remove the need to control the size of the state, which is saved at every step.

The thread as the unit of concurrency

A thread has a single state. Two simultaneous runs on the same thread would read the same starting checkpoint and each write their own continuation: one would be lost, or the history would become inconsistent. You must therefore guarantee only one run at a time per thread. This is the double-texting problem (a customer sending a second message before the answer to the first), covered in lesson 5.3.

Key takeaways

  • The thread_id names the unit of memory; each run resumes from the thread's last checkpoint.
  • The input is applied through the reducers: messages are appended, other keys are replaced.
  • One thread per conversation (or per ticket); cross-conversation memory belongs to the store.
  • Check that a thread belongs to the user; no personal data in the id.
  • Control context size: trim at call time, prune with RemoveMessage, or summarize.

Practice

  1. In a test, send two successive messages on the same thread ("Where is ORD-1002?" then "And when will it arrive?") and check that order_id is kept.
  2. Add trimming to 20 messages with trim_messages to Relay's agent node, and check that the tests still pass.
  3. Write a summarize_history node that triggers when the history exceeds 30 messages, and wire it before agent.

Resources