Short-Term, Long-Term Memory and the Store
LangGraph has two memory layers. Short-term memory is thread-scoped graph state (usually `messages`) saved by a checkpointer and keyed by `thread_id`. Long-term memory is JSON documents in a `BaseStore` under namespaces you choose, readable from any thread. Know the store API (`put`/`get`/`search`/`delete`/`list_namespaces`) and its sharp edges, how to configure semantic search, how nodes reach the store, how to keep history inside the context window (trim, delete, summarise), the semantic/episodic/procedural split, hot-path versus background writes, and how to isolate tenants. Targets langgraph 1.2 / langgraph-checkpoint 4.x / langchain 1.4.
Key points
- 1
Attach memory at compile time with
builder.compile(checkpointer=..., store=...). Nodes reach the store throughruntime: Runtime[Context]asruntime.store(recommended), through an injectedstore: BaseStoreparameter, or throughlanggraph.config.get_store(). If no store was compiled in,runtime.storeisNone. Agent Server and Studio provide a store automatically. - 2
A namespace is a tuple of non-empty strings, such as
(tenant_id, user_id, "memories"). Labels may not contain.(so raw emails fail withInvalidNamespaceError), andputrejects the root label"langgraph". The key is unique inside the namespace, and the value is a JSON-serialisable dict. - 3
put(namespace, key, value, index=None, *, ttl=...)stores or overwrites the whole value. There is no merge and no compare-and-set.get(namespace, key)returns anItem(value,key,namespace,created_at,updated_at) orNone.delete(namespace, key)removes one item; there is no delete-by-namespace. - 4
search(namespace_prefix, *, query=None, filter=None, limit=10, offset=0)matches namespaces by prefix, label by label:("u1",)covers("u1", "prefs")but not("u12", ...). Results pastlimitare cut off without warning, so page withoffset. Filters use equality or$eq/$ne/$gt/$gte/$lt/$lte, combined with AND. - 5
Default result order depends on the backend:
InMemoryStoreuses insertion order (newest last), whilePostgresStore/AsyncPostgresStoreuseupdated_atdescending. Sort onupdated_atyourself when order matters.list_namespaces(prefix=, suffix=, max_depth=, limit=100)lists namespaces and truncates them tomax_depthlabels. - 6
Semantic search needs an index config when the store is created:
index={"embed": <Embeddings | function | "provider:model">, "dims": N, "fields": ["$"]}.fieldstakes JSON paths ("text","a.b","msgs[*].content").put(..., index=False)skips embedding one item, andindex=[...]overrides the fields for one item. Search results then carry ascore. - 7
Without an index config there is no vector search. With one,
InMemoryStorefills leftoverlimitplaces with unembedded items that havescore=None. Each item appears once, scored by its best-matching field. - 8
Production:
PostgresStore.from_conn_string(DB_URI)(orAsyncPostgresStore) fromlanggraph-checkpoint-postgres, withstore.setup()called once.InMemoryStoreis a process-local dict for tests and development. TTL is in minutes (TTLConfig:default_ttl,refresh_on_readdefaulting toTrue,sweep_interval_minutes). Only stores withsupports_ttlaccept it;InMemoryStoreraisesNotImplementedErrorforttl=, whileSqliteStoresupports it. - 9
Short-term history management:
trim_messagesinside the model node limits only what the model sees, so the checkpoint keeps growing.RemoveMessageupdates shrink the current state. Summarising (asummarykey plus deleting all but the last few messages, orSummarizationMiddlewareincreate_agent) keeps the gist at the cost of an extra model call. Keep histories valid: start on a user turn and never orphan aToolMessage. - 10
SummarizationMiddleware(model, trigger=..., keep=("messages", 20))runs inbefore_model. When the trigger is met, it chooses a cutoff that never splits an AI tool call from its result and returnsRemoveMessage(id=REMOVE_ALL_MESSAGES), a summaryHumanMessageand the preserved messages, which rewrites the saved history. - 11
Memory types in the LangGraph guide: semantic (facts, stored as one profile document or as a collection of small documents), episodic (experiences, often used as few-shot examples), and procedural (instructions, such as a prompt refined through reflection and stored under a namespace like
("agent_instructions",)). Semantic memory is not the same thing as semantic search. - 12
Writing memories: in the hot path, memories are available immediately and visible to the user, but writing adds latency and the agent multitasks. In the background, the main app keeps its latency and memory logic is separate, but you must choose triggers (after a quiet period with rescheduling, a cron schedule, or manual) and accept that other threads see new memories late.
Common traps
Keying long-term memory by
thread_idmakes it disappear in every new conversation. Key it by the user's (and tenant's) identity from runtime context.Letting the model supply
user_idas a tool argument lets a prompt injection read or write another user's memories. Build namespaces from authenticated server-side context.Searching too short a prefix, such as
(tenant_id,), returns every user's memories in that tenant. Prefix matching is by label, so"u1"never matches"u12".Assuming
trim_messagesshrinks stored history. It only changes the list passed to the model, so the checkpoint keeps every message.Treating
RemoveMessageas erasure. Earlier checkpoints still hold the content until you call the checkpointer'sdelete_thread, and store items must be deleted separately.Using read-modify-write on one shared profile document from concurrent threads.
putoverwrites the whole value, so updates are lost.Relying on
items[-1]oritems[0]as "latest": the order differs betweenInMemoryStoreandPostgresStore, andlimit(default 10) truncates silently.Using emails or dotted ids as namespace labels: a
.in any label raisesInvalidNamespaceError.
Read the source
Further reading
Suggest a resourceNo extra reading for Short-Term, Long-Term Memory and the Store yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Short-Term, Long-Term Memory and the Store
Ten questions, with the answer and explanation after each one.