AI AgentsLangChain

How do you persist agent state across conversations?

Question 312 of 324 · Updated

On this page

Direct answer#

Use a LangGraph Store for explicitly approved records that need to be accessible across conversation threads, and use a checkpointer for each thread's execution state. In a modern LangChain agent, supply the store through create_agent(store=...) and access it through ToolRuntime.store or trusted application code. InMemoryStore is useful for development; use a compatible durable store implementation when records must survive process restarts.

Do not copy the complete AgentState from one conversation into another. Promote only validated, purpose-specific fields under an authorized user or project namespace. Maintain a stable record key, schema version, record revision, provenance, expiry policy and a safe update protocol. Retrieve the record in the next conversation and use it as scoped data, not as a new system instruction or permission grant.

Source #15 (AI Agents #295) introduces the tool runtime's state and store APIs, and #31 (#311) explains thread-local task memory. This lesson focuses on the cross-conversation promotion, persistence and hydration contract, including commit receipts and recovery. General memory selection is discussed in #79; long-term memory architecture and retrieval are reserved for LangChain #34–36. User isolation and the detailed LangGraph store APIs also have dedicated upcoming lessons.

1. Distinguish a saved conversation from shared records#

Consider an assistant that helps a fictional customer understand orders. In conversation T1 the customer asks for brief answers in future conversations, selects order O-1 and obtains evidence E-1. In conversation T2 the customer asks about another order.

The application may reuse the confirmed answer-style preference. It should not silently reuse the selected order, the previous task phase, an approval or the status observation as evidence about the new order.

DataPersistence boundaryAvailable in a fresh conversation?
Conversation messages and current task phaseThread checkpointerNot automatically
Pending tool calls and interrupt stateThread execution stateNo; resume the original thread using the supported runtime
Confirmed answer styleUser-scoped store recordYes, if authorized, unexpired and relevant
Draft preference inferred from a model responseTemporary proposalNo, until approved under application policy
Order status or external transactionAuthoritative domain serviceOnly after appropriate retrieval and validation
Shared project configurationAuthorized project configuration service or scoped recordOnly for authorized participants
API clients and credentialsTrusted runtime dependenciesReconstruct from approved configuration, never copy from memory

The checkpointer and store are complementary. A durable checkpointer can preserve a thread for later resumption but does not automatically share its custom state with every new thread. A durable store can make approved records accessible across threads, but it does not itself preserve the graph execution cursor, pending messages or interrupt state.

Loading diagram…

The diagram describes an application architecture. The promotion and hydration steps are not implicit LangChain behavior. The host must implement the policy that connects them.

2. Configure a LangGraph Store alongside the checkpointer#

Modern LangChain create_agent accepts both a checkpointer and a store in supported versions. The following illustrative setup separates thread-local execution from cross-thread records.

PYTHON
from dataclasses import dataclass from langchain.agents import create_agent from langgraph.checkpoint.memory import InMemorySaver from langgraph.store.memory import InMemoryStore @dataclass(frozen=True) class RequestContext: tenant_id: str subject_id: str def preference_namespace(context: RequestContext) -> tuple[str, ...]: return ("tenant", context.tenant_id, "user", context.subject_id, "preferences") store = InMemoryStore() agent = create_agent( model="openai:gpt-4o-mini", tools=[], context_schema=RequestContext, checkpointer=InMemorySaver(), store=store, system_prompt="Provide read-only fictional support.", ) # Server-created context, not identity asserted by the client or model. context = RequestContext("demo-tenant", "demo-subject") ns = preference_namespace(context)

The model identifier is illustrative. This SDK example is unexecuted: Python 3.13.5 is installed locally, but langchain, langchain_core and langgraph are absent. Confirm the imports, context_schema interface, store initialization and runtime behavior in the pinned deployment.

InMemoryStore stores its data in process memory. Sharing the same store instance can make records visible to multiple authorized threads within that process. Starting a fresh instance, restarting the process or distributing invocations across unrelated workers does not automatically preserve or share those records.

A production service can use a compatible persistent store, such as a supported LangGraph PostgreSQL store integration. Verify its package, connection lifecycle, setup/migration requirements, synchronous and asynchronous interfaces and supported operations. Do not assume a checkpointer backend automatically provides a store or that a database-backed store implements every application-level concurrency requirement.

A typical synchronous store interface in compatible releases includes put(namespace, key, value), get(namespace, key), search(namespace, ...) and delete(namespace, key). Async variants and optional indexing or TTL behavior vary by implementation. This lesson uses exact-key retrieval for a known preference, not semantic memory search.

3. Design a stable namespace and key#

A namespace is a tuple of strings that organizes records. A key identifies one record within the namespace. The namespace should be constructed from trusted authorization context, not from a model-generated user ID.

For the fictional preference record:

DimensionExample
Tenantdemo-tenant
Subjectdemo-subject
Purposepreferences
Namespace("tenant", "demo-tenant", "user", "demo-subject", "preferences")
Keyanswer_style

A tuple avoids ambiguous string concatenation. For example, tenant "ab" and subject "c" must not collide with tenant "a" and subject "bc". Treat identifiers as opaque values with an established normalization policy. Do not blindly lowercase or split identifiers if their authority system treats them as case-sensitive.

The namespace does not enforce authorization by itself. A service with a store handle may technically be able to read other namespaces. Ensure all access flows through trusted scope construction and appropriately restricted application or database access. The next lesson examines isolation enforcement in depth.

A thread ID identifies the execution thread. It is not the preferred namespace key for a record intended to survive new conversations. Conversely, a user namespace should not be used as the checkpoint thread ID: that would merge unrelated task executions.

Exact record versus collection#

For a single answer-style preference, use a stable key rather than appending a new record for every confirmation. For historical observations that must retain multiple versions, use a domain-specific append-only record design or separate audit history. Do not overwrite an independently required source record merely because the latest preference has changed.

4. Selective state promotion: validate before saving#

Suppose the user says, "Please use brief answers in future conversations." The application can interpret this as a proposed cross-conversation preference if the product permits that purpose. It should validate the explicit choice, scope and retention policy before committing it.

A conversation might contain all of the following:

Candidate fieldDecision
answer_style = briefEligible under the confirmed preference policy
current_order = O-1Keep in the current task; not a permanent default
current_evidence = E-1Retain as a source reference only where legitimately required
temporary approval to change an orderNever promote to standing permission
model-generated statement about customer statusDo not persist as verified fact without evidence
raw tool payloadAvoid copying into a user preference record
authentication tokenNever persist as agent memory

Choose a whitelist with explicit value constraints. A model-generated field named "approved" cannot establish approval. Trusted application logic must determine whether the required confirmation exists. The promotion operation should bind the approved value, source thread, record key, expected revision and policy context.

Loading diagram…

The promotion boundary may be a trusted host endpoint or a tool that invokes a scoped domain service. It is not an unconditional after-model hook that copies all state into a shared store.

A fixed, narrow preference model can use an enum or literal vocabulary such as brief and detailed. Do not allow unrestricted prose to become privileged instruction text in a later conversation. If arbitrary descriptive user memory is supported, preserve its untrusted-data status and validate downstream use.

5. Read and write a user-scoped record#

A basic store record can be a dictionary containing JSON-compatible values. The following illustrative code shows the interface for a simple prototype. It deliberately assumes trusted host validation and single-writer execution; it is not a transaction-safe production write.

PYTHON
# Uses store, context and preference_namespace from section 2. def save_confirmed_style(context, style, source_thread, *, confirmed): if confirmed is not True or style not in ("brief", "detailed"): raise ValueError("Unsupported or unconfirmed preference") # The host has already authenticated context and authorized # source_thread. This prototype has a single authorized writer. store.put(preference_namespace(context), "answer_style", { "schema_version": 1, "value": style, "source_thread": source_thread, }) save_confirmed_style(context, "brief", "demo-t1", confirmed=True) item = store.get(preference_namespace(context), "answer_style") assert item is not None and item.value["value"] == "brief"

This code illustrates the store interface, not proof of durable storage or secure authorization. It omits record revisions, atomic conditional updates, expiry and operation receipts. Section 8 implements those ideas in a separate, actually tested repository. Do not implement a read-then-put revision check and call it atomic when concurrent writers can interleave.

A compatible tool can access the store from runtime.store, with scope derived from runtime.context.

PYTHON
from langchain.tools import tool, ToolRuntime @tool def get_answer_style(runtime: ToolRuntime[RequestContext]) -> str: """Read the confirmed answer style for the current authorized subject.""" if runtime.store is None: return "Preference unavailable." item = runtime.store.get( preference_namespace(runtime.context), "answer_style", ) if item is None: return "No confirmed preference." record = item.value if (record.get("schema_version") != 1 or record.get("value") not in ("brief", "detailed")): return "Preference unavailable." return record["value"]

The SDK example is unexecuted and assumes a valid dictionary from the store and a prototype record without expiry. A production reader must validate the exact record shape, eligibility, expiry, current scope and provenance, and handle backend errors appropriately. The read-only tool does not expose a target-user argument or let the model choose a namespace.

Register the tool with an agent using the corresponding context schema and store. On a fresh authorized thread, pass the trusted context again. The agent can use the preference if the registered tool is invoked; the store does not automatically insert all user records into the model's prompt.

An alternative is trusted host hydration before invocation. For a stable preference needed on every request, fetching a known key once and converting it into a validated application-owned style setting can be simpler than letting the model decide when to call a tool. For example, map brief to a reviewed static instruction about concision and detailed to another reviewed instruction. Do not concatenate arbitrary stored text into the system prompt.

6. Define the persisted record contract#

An application may choose a record envelope like the following. This is an illustrative application format, not a required LangGraph Store schema.

JSON
{ "schema_version": 1, "record_version": 7, "value": "brief", "source": { "thread_id": "demo-t1", "confirmation_ref": "demo-confirmation-42" }, "updated_at": "2026-01-01T10:00:00Z", "expires_at": "2026-04-01T10:00:00Z", "purpose": "answer_style" }

A real host should assign timestamps and revision values, rather than ask the model to invent them. A stable source reference identifies where the approved change originated; it does not provide unrestricted access to that conversation.

Distinguish three different types of version:

VersionPurpose
Schema versionIdentifies the shape and interpretation of the serialized record
Record versionTracks accepted changes to one logical record
Policy versionIdentifies the promotion, retention and usage rules under which the record was accepted

A record version of seven does not mean its schema version is seven. Do not silently load an unknown schema as though it were the latest. Validate known older representations and use a reviewed migration. If the old value cannot be faithfully mapped, return a controlled unavailable state.

Serialize using supported JSON-compatible types and explicit representations for dates, identifiers, decimals and enums. Keep credentials, live clients and arbitrary Python objects out of the store. Size-bound records, avoid embedding whole conversations, and test the serialization format across application upgrades.

Expiry and freshness#

A record can remain persisted yet become ineligible to use. Store an expiration deadline where appropriate, and evaluate it using trusted current time. Distinguish expiry from physical deletion, and distinguish expiry from a source fact becoming stale before its deadline.

Some store implementations may support TTL or refresh behavior. Do not assume every implementation supports the same TTL semantics, automatic cleanup or access-triggered refresh. Define whether a read is permitted to extend retention, and implement explicit application-level checks if necessary.

When a preference expires, the application can use a default or ask for a new confirmation if appropriate. Do not silently fall back to an expired historical preference. When an authorized deletion or revocation is requested, consider derived projections and receipts as well as the current record; retention and deletion obligations are not satisfied merely by hiding the value from the next model request.

7. Design consistency and recovery across conversations#

Two conversations can attempt to update the same record. Suppose T1 reads answer_style at revision 4 and T2 also reads revision 4. T1 commits revision 5. T2's old proposal may no longer reflect the current preference.

A conservative policy requires the expected revision to match the current record version before writing. If it does not, reload and determine whether the operation remains appropriate. Do not silently retry a stale proposal against a new revision: that can overwrite a more recent explicit preference.

The standard store put method is not necessarily a conditional compare-and-set operation. Its exact atomicity depends on the implementation. Use an application-owned transactional record service or a verified backend-specific conditional-write mechanism when strong consistency is required.

Loading diagram…

A second problem occurs when the store commits successfully but the response is lost before the original thread records success. Blindly replaying the promotion could increment the version twice or overwrite a newer change. Use a stable logical promotion identity, bind it to the confirmed payload and persist a receipt in the same transaction as the authoritative record update. A replay with the same identity and payload can return the original commit version without reapplying it. A replay with a different payload is a conflict.

A historical receipt establishes what was committed for that operation. It does not establish the current preference value. If a later operation superseded the old one, report the earlier operation's historical outcome and independently load the latest eligible record.

If the graph checkpoint and the cross-thread record use separate transactions, the two may become temporarily inconsistent. A trusted recovery worker or the next authorized invocation can consult the operation receipt and reconcile the graph state. An outbox or durable operation ledger is useful when additional projections need to be updated. Do not claim the graph and store are atomically committed unless the deployed integration actually establishes that transaction boundary.

8. Tested Python: selective promotion, idempotent receipts and durable reopening#

This standalone standard-library example implements a narrow cross-conversation preference repository using SQLite. It models an authorized promotion service, not a LangGraph Store implementation. The exact program below was executed locally on Python 3.13.5 with SQLite 3.46.1.

It accepts one approved field, validates source scope and confirmation, commits a record and its operation receipt in a single transaction, and supports expiry-aware exact-key reads.

PYTHON
import sqlite3, json, tempfile, pathlib, sys, importlib.util from dataclasses import dataclass class Denied(Exception): pass class Conflict(Exception): pass class Invalid(Exception): pass @dataclass(frozen=True) class Scope: tenant: str user: str class Preferences: def __init__(self, path): self.db=sqlite3.connect(path) self.db.executescript('''CREATE TABLE IF NOT EXISTS prefs( tenant TEXT, subject TEXT, key TEXT, version INTEGER, value TEXT, expiry INTEGER, source TEXT, PRIMARY KEY(tenant,subject,key)); CREATE TABLE IF NOT EXISTS receipts( tenant TEXT, subject TEXT, op TEXT, payload TEXT, version INTEGER, PRIMARY KEY(tenant,subject,op));''') def promote(self, scope, thread_owner, thread, op, proposal, *, confirmed, expected, now, expiry): if scope != thread_owner or not confirmed: raise Denied('promotion denied') if set(proposal) != {'answer_style'} or proposal['answer_style'] not in ('brief','detailed') or expiry <= now: raise Invalid('unsupported promotion') key='answer_style'; value=proposal[key] identity=(scope.tenant,scope.user) payload=json.dumps([thread,key,value,expected,expiry],separators=(',',':')) with self.db: self.db.execute('BEGIN IMMEDIATE') receipt=self.db.execute('SELECT payload,version FROM receipts WHERE tenant=? AND subject=? AND op=?',(*identity,op)).fetchone() if receipt: if receipt[0]!=payload: raise Conflict('operation changed') return receipt[1] old=self.db.execute('SELECT version FROM prefs WHERE tenant=? AND subject=? AND key=?',(*identity,key)).fetchone() version=old[0] if old else 0 if version!=expected: raise Conflict('stale version') version+=1 self.db.execute('INSERT INTO prefs VALUES(?,?,?,?,?,?,?) ON CONFLICT(tenant,subject,key) DO UPDATE SET version=excluded.version,value=excluded.value,expiry=excluded.expiry,source=excluded.source',(*identity,key,version,value,expiry,thread)) self.db.execute('INSERT INTO receipts VALUES(?,?,?,?,?)',(*identity,op,payload,version)) return version def load(self, scope, now): row=self.db.execute('SELECT value,version,source FROM prefs WHERE tenant=? AND subject=? AND key=? AND expiry>?',(scope.tenant,scope.user,'answer_style',now)).fetchone() return row def rejects(exc, fn): try: fn() except exc: return raise AssertionError('expected rejection') with tempfile.TemporaryDirectory() as d: path=pathlib.Path(d)/'prefs.db'; r=Preferences(path) a=Scope('A','u'); b=Scope('B','u'); c=Scope('A','v') def promote(repo=r,scope=a,owner=a,thread='t1',op='p1',style='brief',confirmed=True,expected=0,expiry=100,now=1): return repo.promote(scope,owner,thread,op,{'answer_style':style},confirmed=confirmed,expected=expected,now=now,expiry=expiry) assert r.load(a,0) is None rejects(Denied,lambda:promote(confirmed=False)) rejects(Denied,lambda:promote(owner=b)) rejects(Invalid,lambda:r.promote(a,a,'t1','bad',{'order_ref':'O-1'},confirmed=True,expected=0,now=1,expiry=100)) rejects(Invalid,lambda:promote(style='arbitrary instruction')) assert promote()==1 assert r.load(a,2)==('brief',1,'t1') assert r.load(b,2) is None and r.load(c,2) is None assert promote()==1 rejects(Conflict,lambda:promote(style='detailed')) other=Preferences(path) assert promote(repo=other,thread='t2',op='p2',style='detailed',expected=1)==2 rejects(Conflict,lambda:promote(op='p3',expected=1)) assert promote()==1 and r.load(a,3)==('detailed',2,'t2') r.db.close(); other.db.close(); r=Preferences(path) assert r.load(a,99)==('detailed',2,'t2') assert r.load(a,100) is None assert promote(repo=r,thread='t3',op='p4',expected=2,now=101,expiry=200)==3 assert r.load(a,101)==('brief',3,'t3') r.db.close() print('17 checks passed') print(sys.version.split()[0], sqlite3.sqlite_version) print({p:importlib.util.find_spec(p) is not None for p in ['langchain','langchain_core','langgraph']})

Actual local execution output:

17 checks passed
3.13.5 3.46.1
{'langchain': False, 'langchain_core': False, 'langgraph': False}
TestObserved result
No previous preferenceNo record returned
Missing confirmationPromotion denied
Mismatched thread-owner scopePromotion denied
Attempt to promote order referenceRejected
Unsupported style textRejected
First approved promotionRevision 1 committed
Cross-thread-readable recordBrief style, version 1, source t1
Other tenant and other subjectNo record returned for either
Exact promotion replayOriginal revision returned
Same operation ID with changed payloadConflict
Update from separate connection and threadDetailed style at revision 2
Stale expected versionConflict
Replay of older successful operationReturns old receipt without reverting current revision
Close and reopen databaseLatest committed record available
Read at expiryNo eligible record
New confirmed promotion after expiryVersion increments rather than restarting
Read renewed preferenceBrief style at revision 3 with source t3

What this implementation proves and what it does not#

The record and receipt are written within the same SQLite transaction. The second connection tests sequential stale-version behavior, not simultaneous lock contention or distributed failover. The operation payload uses a fixed list with JSON serialization; an actual service must specify canonical types and include all authorization-relevant fields in the operation binding. The repository assumes trusted caller-supplied scopes, actual ownership verification, a confirmed choice, and a trusted synthetic clock. It is not an authentication system and does not resolve thread ownership from the provided thread string. The fixture checks only the approved preference vocabulary and cross-scope read behavior.

The operation receipt is returned only after the input policy checks, including the proposed expiry check. An old replay after the original expiry can therefore be rejected by this narrow implementation; a production reconciliation endpoint may need a separately authorized historical receipt lookup even when a current promotion is no longer eligible. It must not renew the old operation as a side effect. The expired row remains in the database to retain its version; the example is not a deletion or revocation service.

The code does not include database-level schema version fields, an actual LangGraph checkpointer, actual store adapters, real conversation messages, a provider, semantic retrieval, retention cleanup or general concurrency performance tests. The fixed SQLite schema represents a single teaching version. Use a versioned migration procedure and stronger schema validation in production. The example deliberately favors a small auditable promotion service over pretending that a generic store supports atomic conditional writes.

9. Hydrate a fresh thread without restoring stale execution state#

At the beginning of an authorized conversation, select the required cross-thread keys by the current task and policy. A useful hydration sequence is:

  1. Authenticate the subject and authorize the new thread.
  2. Resolve the allowed namespaces from trusted context.
  3. Retrieve only the required keys.
  4. Validate schema version, record version, value, purpose, expiry and current access.
  5. Construct a minimal model-facing representation or trusted application setting.
  6. Initialize new task state independently of the record.
  7. Recheck sensitive facts through the appropriate authoritative service when necessary.
Loading diagram…

For the answer-style example, the user may still explicitly ask for a detailed explanation in a particular conversation. Define whether that current request overrides the stored default for this turn and whether it changes the stored preference. A local exception should not become a permanent change without the required promotion decision.

If the store is unavailable, distinguish unavailable from absent. An optional display preference can often degrade to a neutral default. A record required to satisfy an important task constraint may require a controlled failure or clarification. Never guess that the missing record was an approval.

For a very long task, the record might change after it was loaded. Decide whether the task uses a pinned revision for consistency or refreshes the record at a defined boundary. For permissions and revocations, consult current authorization rather than rely on a pinned old preference or state snapshot.

10. Production verification plan#

The following tests should run against the actual pinned LangChain/LangGraph SDK and the intended persistent backend, separately from the standalone repository test.

Test areaRequired outcome
Same-thread checkpointExisting task state resumes correctly
New thread, same authorized subjectApproved shared preference available; old task phase absent
Different subject or tenantNo unauthorized shared record
InMemoryStore lifecycleExpected process-local behavior demonstrated
Durable backend restartApproved record and version restored after restart
ToolRuntime.storeCorrect store and trusted context available
Namespace constructionNo ambiguous or caller-controlled scope substitution
Promotion whitelistTemporary order, approvals and secrets not copied
Schema evolutionKnown older version migrated or unknown version rejected
Concurrent writersActual atomic conflict policy verified
Duplicate promotionSame payload not applied twice
Lost acknowledgementReceipt reconciliation reports historical commit correctly
Expired recordNot used; renewal requires approved promotion
Deletion and revocationDerived views handled under documented policy
Backend unavailableControlled fallback, no invented memory
Model context projectionOnly required approved data supplied
End-to-end task successCross-thread preference helpful without stale task contamination

For deployment, verify the persistent store's connection management, setup and migration procedure, transaction behavior, backup and restore, quotas and failure recovery. Test multiple worker processes and actual simultaneous contention using the intended backend. Review whether receipt retention meets retry and reconciliation requirements without unnecessarily retaining private payloads.

Observe promotion acceptance and rejection rates, stale-version conflicts, duplicate operations, expiry misses, store read/write errors, hydration latency and downstream task success. Use safe scope aliases, record keys, versions and operation references; avoid logging full conversation payloads or personal records by default.

Measure effectiveness against a baseline without cross-conversation promotion. The main question is whether users avoid repeatedly supplying stable approved information while new tasks remain independently correct. A larger store or higher memory retrieval rate is not proof of better agent behavior.

Interview-ready answer#

I keep graph execution state in a thread-scoped checkpointer and store only explicitly approved cross-conversation records through a LangGraph Store. I pass the store into create_agent and construct namespaces from trusted tenant and user identity. I promote fields using a narrow policy with provenance, validation, schema and record versions and expiry. I retrieve those fields by purpose in a fresh conversation, rather than copy the original AgentState. InMemoryStore is suitable for development, while a verified durable backend is needed for restart persistence. For competing updates I use a transactional conditional-write service and idempotent receipts, reconcile ambiguous commits and test actual multi-worker behavior. Memory is contextual data, not proof of authorization or external success.

Official documentation research leads and verification status#

Authorized offline research exception applied. These documentation URLs are research leads, not live-accessed citations. The exact standalone Python program was executed locally and printed 17 checks passed on Python 3.13.5 and SQLite 3.46.1. Package inspection confirmed langchain, langchain_core and langgraph were absent. The SDK snippets, actual durable LangGraph store, checkpointer integration, current documentation, simultaneous database contention, provider behavior, distributed recovery and public website display were not verified. The tests use synthetic scopes, operations and times. Mermaid diagrams use standard triple-backtick fences; actual rendering was not tested.

References

  1. 1.
    LangChain long-term memorydocs.langchain.com
  2. 2.
    LangChain short-term memorydocs.langchain.com
  3. 3.
    LangChain runtimedocs.langchain.com
  4. 4.
    LangChain toolsdocs.langchain.com
  5. 5.
    LangChain agentsdocs.langchain.com
  6. 6.
    LangGraph persistencedocs.langchain.com
  7. 7.
    LangChain API referencereference.langchain.com
  8. 8.
    Python sqlite3docs.python.org

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.