Module 3 · Persistence & memory

Store and cross-session long-term memory

5 min read

The checkpointer gives each conversation its memory. But some information must survive from one conversation to the next: the customer's preferred language, their habits, what they reported last week. Storing it in a thread makes no sense — the next contact will open a new thread. LangGraph provides a second persistence component for this: the store, a long-term memory organized in namespaces.

Thread memory and long-term memory

CheckpointerStore
ScopeOne thread (one conversation)Cross-cutting: all threads, all runs
ContentThe graph's complete state, at every stepJSON documents that you choose to write
WritingAutomaticExplicit, in your nodes
OrganizationBy thread_idBy namespace and key
SearchBy thread and checkpointBy namespace, filter, and semantic search

Both are plugged in at compile time and coexist without problems:

graph = builder.compile(checkpointer=checkpointer, store=store)

The store API

The store keeps documents (JSON dictionaries) under a namespace — a tuple of strings, like a folder path — and a key:

from langgraph.store.memory import InMemoryStore

store = InMemoryStore()
namespace = ("customers", "cus_lea")

store.put(namespace, "profile", {"language": "fr", "contacts": 3})
item = store.get(namespace, "profile")       # Item: .value, .key, .namespace, .created_at, .updated_at
item.value["language"]                        # "fr"
store.search(("customers",), filter={"language": "fr"})   # search by namespace prefix
store.delete(namespace, "profile")

Every method has an async version (aput, aget, asearch, adelete). The namespace is the isolation tool: by prefixing with the customer id, you guarantee that a node only reads that customer's memory. It is also what makes it possible to erase everything for a given customer.

Using the store in a node

A node accesses the store via the runtime, next to the context:

async def load_profile(state: SupportState, runtime: Runtime[Context]) -> dict:
    update: dict = {"agent_turns": 0, "status": "open"}
    if runtime.store is not None:
        profile = await runtime.store.aget(("customers", runtime.context.customer_id), "profile")
        if profile is not None:
            update["language"] = profile.value.get("language", "fr")
    return update

And at the end of the conversation, finish updates the profile:

async def finish(state: SupportState, runtime: Runtime[Context]) -> dict:
    if runtime.store is not None:
        namespace = ("customers", runtime.context.customer_id)
        previous = await runtime.store.aget(namespace, "profile")
        contacts = (previous.value.get("contacts", 0) if previous else 0) + 1
        await runtime.store.aput(
            namespace, "profile",
            {"language": state.get("language", "fr"), "contacts": contacts,
             "last_intent": state.get("intent")},
        )
    ...

Note the combination: identity comes from the context (not modifiable by the model), memory from the store, and the namespace is built from the identity. The test_long_term_memory_across_threads test checks that after two conversations on two different threads, the customer's profile counts two contacts.

The store is also available in tools, via ToolRuntime (runtime.store): a remember_preference tool can thus let the model itself record useful information.

A profile with fixed keys suits structured data. For natural-language memories ("prefers to be contacted in the morning", "had a damaged parcel in March"), you want to retrieve the most relevant ones by meaning. The store allows it if you give it an embeddings function:

store = InMemoryStore(index={"embed": embed_texts, "dims": 1024, "fields": ["text"]})

facts = ("customers", "cus_lea", "facts")
store.put(facts, "f1", {"text": "Likes green tea, often buys gift boxes"})
store.put(facts, "f2", {"text": "Prefers express delivery"})

hits = store.search(facts, query="gift idea?", limit=3)

embed accepts a function that turns a list of texts into a list of vectors, or a LangChain embeddings model; fields says which document fields to index. With the Postgres store, search relies on the pgvector extension.

Which memories to keep?

Long-term memory raises more design questions than technical ones.

Who writes? Two approaches:

  • On the hot path: a tool or node writes during the conversation. Simple, immediate, but adds latency and lets the model decide what is worth remembering.
  • In the background: after the conversation, a separate process rereads the exchange and extracts durable facts. More perspective, no latency for the customer, but a delay before the memory is up to date.

What? Prefer useful, stable facts (preferences, constraints, significant history) to the raw transcript. A memory that retains everything becomes noisy and costly to inject into the context.

How to stay accurate? Preferences change. Write under stable keys (profile, preferences) that you update, rather than accumulating contradictory facts.

And privacy? Long-term memory is a personal-data database. Inform users, limit retention (the Postgres store supports automatic expiration, configurable per item with the ttl parameter; the in-memory store doesn't support it), and plan complete erasure of a customer — easy if everything is stored under ("customers", customer_id, …).

Implementations

StoreUse
InMemoryStoreTests and prototypes
PostgresStore / AsyncPostgresStoreProduction; semantic search with pgvector; expiration (TTL)
RedisStoreProduction, via the langgraph-checkpoint-redis package

Relay's server creates an AsyncPostgresStore on the same database as the checkpointer when RELAY_DATABASE_URL is set, and calls its setup() at startup.

Key takeaways

  • Checkpointer = memory of a thread; store = cross-cutting memory, explicit, organized in namespaces.
  • A node accesses the store via runtime.store; a tool via ToolRuntime.
  • Build the namespace from the context's identity: isolation and erasure guaranteed.
  • Semantic search is enabled by giving the store's index an embeddings function.
  • Keep useful, stable facts, updated under stable keys; think about retention and erasure.

Practice

  1. Run two English conversations for cus_lea, then a third in French: which language does the profile keep? Is that the desired behavior?
  2. Add a remember_preference(fact: str) tool that writes to ("customers", customer_id, "facts"), and show the three most relevant memories in the agent's prompt.
  3. Write a forget_customer(store, customer_id) function that deletes all of a customer's long-term memory, with its test.

Resources