AI AgentsLangChain
How do you isolate conversation state between users?
Question 313 of 324 · Updated
On this page
- Direct answer
- 1. Thread identity is not authorization
- 2. Authorize every checkpoint operation
- 3. Separate tenant scope, participant identity and thread membership
- 4. Scope store retrieval to the authenticated requester
- 5. Protect the full data path, not just the checkpoint
- 6. Shared conversations and revocation
- 7. Tested Python: object-level access and revision fencing
- Important limitations of the teaching model
- 8. Apply defense in depth in production storage
- 9. Adversarial production verification
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
Authenticate the caller and authorize the requested conversation before passing its thread_id to a LangChain agent or accessing its checkpoint. Construct trusted runtime context and store namespaces from the verified principal, not from model-generated or client-selected identities. Apply the same ownership and membership checks to invocation, inspection, history, resume, update, deletion, export and streaming endpoints.
A checkpointer separates execution threads by its configured identity. It is not an authorization service. Similarly, a LangGraph Store namespace organizes records but does not itself guarantee that an arbitrary caller holding the store handle can access only its own records. Protect the entire application path, including shared conversations, retrieval, caches, tool execution and output delivery.
Earlier AI Agents #76 and #77 explain general memory scoping and leakage prevention. LangChain #25 (#305), #31 (#311) and #32 (#312) explain history, thread-local state and cross-thread persistence respectively. This lesson focuses on enforcing the authenticated conversation-access boundary in a LangChain application, including shared-thread capabilities, revocation and adversarial verification. Detailed store namespace mechanics and concurrent deployment scheduling are reserved for the respective LangGraph and later LangChain lessons.
1. Thread identity is not authorization#
Consider two fictional tenants. Tenant A has Alice and Bob, while tenant B has another user whose local username is also Alice. Each user can have several conversations. A thread identifier selects a conversation; it does not prove ownership.
| Identifier | Responsibility |
|---|---|
| Authenticated principal | Verified subject and relevant tenant membership |
| Public conversation ID | Opaque locator accepted by an application endpoint |
| Internal thread_id | Server-managed checkpoint routing identity |
| Store namespace | Scope for a category of persistent records |
| Session or request identity | Correlation of a particular authenticated interaction |
| Access-policy revision | Version of membership or authorization state used to reject stale decisions |
Do not use a user ID as the only thread ID: one user may have separate tasks, each with different history and state. Do not use a single shared thread for every request. Do not treat a UUID as a secret that grants access. Even unguessable identifiers may become available through logs, URLs, screenshots, exports or accidental disclosure.
A public route such as GET /conversations/t1 is safe only when the authenticated caller is authorized for that conversation. It is not enough to authenticate the caller and then query the conversation by ID. That is an insecure direct object reference (IDOR), also commonly described as broken object-level authorization (BOLA).
The graph is an application architecture, not automatic enforcement by the LangChain agent. The ownership registry and current access checks must be implemented and tested by the host.
2. Authorize every checkpoint operation#
In modern LangChain, a graph-backed agent with a checkpointer uses a configurable thread_id to associate state with a conversation. A safe application resolves that value after checking ownership or a current collaboration grant.
The following example is illustrative. It assumes the host has an authenticated principal and a repository that actually performs object-level authorization. No live authentication system or SDK call is tested in this example.
PYTHONfrom dataclasses import dataclass from langchain.agents import create_agent from langgraph.checkpoint.memory import InMemorySaver @dataclass(frozen=True) class AccessContext: tenant_id: str subject_id: str internal_thread_id: str access_revision: int agent = create_agent( model="openai:gpt-4o-mini", tools=[], context_schema=AccessContext, checkpointer=InMemorySaver(), system_prompt="Answer authorized fictional conversation requests.", ) def invoke_conversation(principal, public_id, validated_text, registry): # principal comes from verified authentication, not request JSON. # registry.require must verify current membership and write capability. access = registry.require(principal, public_id, action="invoke") context = AccessContext( access.tenant_id, principal.subject_id, access.internal_thread_id, access.policy_revision, ) config = {"configurable": {"thread_id": access.internal_thread_id}} return agent.invoke( {"messages": [{"role": "user", "content": validated_text}]}, config=config, context=context, )
SDK limitation: Local inspection on Python 3.13.5 confirmed langchain, langchain_core and langgraph were absent. Framework examples are illustrative and unexecuted. Section 7 contains genuinely executed tests of a separate application authorization model. Confirm the actual imports, invocation context, checkpoint API and runtime behavior in the pinned release.
The registry is a required application dependency, not a LangChain API. The example assumes trusted, validated inputs and an admitted invocation; it is not a complete web endpoint, revocation system or streaming implementation. An actual deployment should recheck permissions at appropriate sensitive action and output boundaries, as discussed below.
Never merge an untrusted client-provided configurable dictionary into the approved configuration after the authorization check. A malicious client could override thread_id, checkpoint selectors or other execution settings. Construct the permitted configuration from scratch.
The same rule applies to all operations, not only invoke.
| Operation | Authorization question |
|---|---|
| Read current state | Is the caller allowed to inspect this conversation and these fields? |
| Read checkpoint history | May they inspect historical state, including older sensitive context? |
| Invoke or resume | May they submit a new action or continue this particular execution? |
| Update state | Is this operation and field update allowed for the caller? |
| Fork checkpoint | May they copy this source into the intended destination scope? |
| Delete or reset | Do they have the specific destructive capability? |
| Export or stream | Are they permitted to receive the selected output and attachments? |
A supported graph API such as get_state or get_state_history must only be called through a trusted service boundary. Listing conversations and searching checkpoint history also need scope enforcement: otherwise an attacker can discover another user's identifiers or metadata without opening the conversation itself.
A graph snapshot may contain private tool payloads, intermediate state and execution metadata. An authorized reader of a conversation transcript is not automatically authorized to receive every raw checkpoint field. Return an explicit projection, not the full state object.
3. Separate tenant scope, participant identity and thread membership#
A common tenant boundary mistake is to use only the local username or subject label. Two tenants can have the same local identifier. Prefer the identity provider's stable subject identifier and an independently authorized tenant context. Do not assume that a tenant claim from an arbitrary request body is trustworthy.
For fictional identities A/alice, A/bob and B/alice:
| Requested access | Default decision |
|---|---|
| A/alice reads her T1 | Allow under current owner policy |
| A/alice reads her independent T2 | Allow, but do not merge history |
| A/bob reads A/alice's private T1 | Deny |
| B/alice reads A/alice's T1 | Deny despite identical local username |
| A/bob reads T1 after explicit read sharing | Allow only the authorized shared projection |
| A/bob invokes or mutates a read-only shared T1 | Deny |
| Former collaborator after revocation | Deny subsequent protected access |
In an actual product, team or project conversations may have several authorized participants. The access model should describe whether participants can read, send messages, invoke tools, edit state, share further, export or delete. A single broad "member" role is often insufficient.
A collaborator's tool access must be evaluated against the collaborator's own current domain permissions. Sharing a conversation must not grant the recipient the conversation owner's privileged service credentials, personal memory or standing approvals.
This is a conceptual separation. If private information was previously copied into the shared transcript, granting access to that transcript could expose it. Before sharing an existing private thread, apply a product policy that reviews historical content and derived artifacts, or create a new sanitized shared conversation. Do not automatically share every historical checkpoint.
4. Scope store retrieval to the authenticated requester#
The prior lesson describes approved records persisted across threads. The security question here is which participant's record can be loaded into a particular invocation.
In a compatible modern agent, a tool can read the store through runtime.store and derive a namespace from trusted runtime.context. It should not take a target tenant or user ID as a model-controlled parameter for an ordinary self-service read.
PYTHONfrom langchain.tools import tool, ToolRuntime @tool def read_my_answer_style(runtime: ToolRuntime[AccessContext]) -> str: """Read only the current authenticated participant's approved style.""" context = runtime.context namespace = ("tenant", context.tenant_id, "user", context.subject_id, "preferences") if runtime.store is None: return "Preference unavailable." record = runtime.store.get(namespace, "answer_style") if record is None: return "No confirmed preference." value = record.value.get("value") if value not in ("brief", "detailed"): return "Preference unavailable." return value
This unexecuted SDK illustration assumes the agent was configured with the approved store and validated context. In production, also validate schema version, expiry, current authorization, provenance and backend error behavior. Register the tool only where this access is allowed. The example intentionally does not implement search or a complete memory lifecycle.
The trusted context is an invocation snapshot, not permanent authority. If membership can change during a long-running execution, consult current policy before sensitive retrieval or actions. A store namespace is a routing convention, not a database access-control mechanism. A trusted store handle may be capable of querying other namespaces. Restrict the service's access paths and apply storage-level controls where supported.
For retrieval from a shared knowledge system, enforce the authorized candidate scope before selecting results. Do not retrieve across tenants, send the results to the model and try to remove private data afterward. Use authorization-compatible metadata filtering, indexes or separate collections, and verify their actual filtering semantics. A result identifier must be reauthorized when fetching the underlying object. Relevance scores never grant access.
5. Protect the full data path, not just the checkpoint#
Conversation state can leak through components outside the graph.
| Component | Common failure | Design requirement |
|---|---|---|
| Public endpoint | Accepts arbitrary internal thread_id | Resolve authorized public locator server-side |
| Cache | Keyed only by question or thread label | Scope by relevant identity, resource, policy and data revisions |
| Retrieval | Global search followed by display filtering | Enforce allowed scope before model exposure |
| Tool execution | Uses original thread owner's permissions for a guest | Use current principal and operation authorization |
| Streaming | Subscription keyed by guessable conversation ID | Authorize subscription and recheck delivery as required |
| Background job | Reuses mutable global current-user context | Pass immutable request identity and scoped job reference |
| Logs and tracing | Full private prompts readable across tenants | Protected access, minimization and redaction |
| Attachments and exports | Download URL bypasses thread checks | Authorize object access and limit capability lifetime |
| Checkpoint administration | Broad raw-state API exposed to clients | Restrict to audited privileged service paths |
A shared model client or connection pool is not inherently unsafe. The important rule is that per-request state and identity must not be stored in shared mutable variables. A request's principal should be carried explicitly through trusted function arguments or an appropriate request-local context. Test cleanup, asynchronous task propagation and worker reuse in the deployed runtime.
For cache reuse, identical prompt text does not establish identical authorization. Even two users in the same tenant may have different access to documents or conversation content. Cache keys must include the scope and revision components required by the result's policy, or the cache must be restricted to content explicitly approved for sharing. A permission downgrade may require invalidating cached results or checking eligibility before delivery.
The application cannot retract a response already delivered to a user or bytes already sent to an external provider merely by revoking thread membership. Minimize external disclosure up front and state the actual revocation guarantee.
6. Shared conversations and revocation#
A useful collaboration model grants distinct read and contribution capabilities and records changes in a membership revision. When membership changes, previously issued access decisions may be stale.
The example assumes a policy that rechecks access before protected delivery. It does not claim revocation can recall bytes already delivered. For streaming, decide where reauthorization occurs, how revocation signals reach running workers and what maximum delay is acceptable. A stronger guarantee may require serialized admission and delivery, short-lived leases, cancellation and carefully coordinated distributed fencing.
An epoch or revision can invalidate access decisions made before a membership change. It is not authentication by itself. Tokens or tickets must be issued by a trusted component, bound to the principal, scope and action, protected against tampering, and checked for current eligibility. Do not accept a model-generated ticket or revision.
For an already-running agent, separately protect each business action. Revoking conversation access does not automatically cancel an external service operation that is in progress. Define whether to stop new operations, cancel safely where supported, reconcile committed outcomes, and prevent unauthorized output disclosure. Never assume deleting a checkpoint rolls back a transaction.
7. Tested Python: object-level access and revision fencing#
The following standalone application model tests conversation ownership, sharing capabilities, revision invalidation, private preference scoping and concurrent requests. It uses an in-process lock to make each modeled policy check and local state operation coherent. It is not a LangGraph checkpointer, database ACL, production authentication service or distributed session manager.
The exact program was executed locally with Python 3.13.5.
PYTHONfrom dataclasses import dataclass from threading import RLock, Barrier from concurrent.futures import ThreadPoolExecutor import sys, importlib.util class Denied(Exception): pass @dataclass(frozen=True) class Principal: tenant: str user: str @dataclass(frozen=True) class Ticket: principal: Principal thread: str epoch: int action: str class Gate: def __init__(self): self.lock = RLock() self.threads = {} self.private = {} def create(self, p, thread, text): with self.lock: if thread in self.threads: raise ValueError('duplicate thread') self.threads[thread] = (p, 0, {}, text) def share(self, p, thread, guest, role): with self.lock: owner, epoch, acl, text = self.threads[thread] if p != owner or guest.tenant != owner.tenant or role not in ('read','write',None): raise Denied('unavailable') acl = dict(acl) if role is None: acl.pop(guest, None) else: acl[guest] = role self.threads[thread] = (owner, epoch+1, acl, text) def issue(self, p, thread, action): with self.lock: row = self.threads.get(thread) if row is None or action not in ('read','write'): raise Denied('unavailable') owner, epoch, acl, _ = row role = 'write' if p == owner else acl.get(p) if p.tenant != owner.tenant or role is None or (action == 'write' and role != 'write'): raise Denied('unavailable') return Ticket(p, thread, epoch, action) def read(self, ticket): with self.lock: current = self.issue(ticket.principal,ticket.thread,ticket.action) if current != ticket: raise Denied('stale access') return self.threads[ticket.thread][3] def write(self, ticket, text): with self.lock: if ticket.action != 'write': raise Denied('unavailable') self.read(ticket) owner, epoch, acl, _ = self.threads[ticket.thread] self.threads[ticket.thread] = (owner,epoch,acl,text) def preference(self, p): with self.lock: return self.private.get((p.tenant,p.user,'style')) def rejects(fn): try: fn() except Denied: return raise AssertionError('expected denial') a=Principal('A','alice'); b=Principal('A','bob'); c=Principal('B','alice') g=Gate(); g.create(a,'t1','A-SECRET'); g.create(a,'t2','A-OTHER'); g.create(c,'t3','B-SECRET') g.private[('A','alice','style')]='brief'; g.private[('B','alice','style')]='detailed' assert g.read(g.issue(a,'t1','read'))=='A-SECRET' assert g.read(g.issue(a,'t2','read'))=='A-OTHER' rejects(lambda:g.issue(b,'t1','read')) rejects(lambda:g.issue(c,'t1','read')) rejects(lambda:g.issue(a,'missing','read')) rejects(lambda:g.share(b,'t1',b,'write')) rejects(lambda:g.share(a,'t1',c,'read')) g.share(a,'t1',b,'read'); old=g.issue(b,'t1','read') assert g.read(old)=='A-SECRET' rejects(lambda:g.issue(b,'t1','write')) rejects(lambda:g.write(old,'changed')) assert g.preference(b) is None and g.preference(a)=='brief' and g.preference(c)=='detailed' g.share(a,'t1',b,'write'); rejects(lambda:g.read(old)) writer=g.issue(b,'t1','write'); g.write(writer,'shared update'); assert g.read(g.issue(a,'t1','read'))=='shared update' g.share(a,'t1',b,None); rejects(lambda:g.read(writer)) rejects(lambda:g.write(writer,'revoked write')) rejects(lambda:g.issue(b,'t1','read')) barrier=Barrier(2) def read_concurrently(p,t): barrier.wait(timeout=5) return g.read(g.issue(p,t,'read')),g.preference(p) with ThreadPoolExecutor(max_workers=2) as pool: f1=pool.submit(read_concurrently,a,'t2'); f2=pool.submit(read_concurrently,c,'t3') assert (f1.result(),f2.result()) == (('A-OTHER','brief'),('B-SECRET','detailed')) assert g.read(g.issue(a,'t1','read'))=='shared update' print('18 checks passed') print(sys.version.split()[0], {p:importlib.util.find_spec(p) is not None for p in ['langchain','langchain_core','langgraph']})
Actual local execution output:
18 checks passed
3.13.5 {'langchain': False, 'langchain_core': False, 'langgraph': False}| Check | Observed behavior |
|---|---|
| Owner reads T1 | Correct private state |
| Owner reads separate T2 | Different state |
| Same-tenant nonmember | Denied |
| Cross-tenant same username | Denied |
| Missing thread | Denied |
| Guest attempts self-grant | Denied |
| Cross-tenant share | Denied by this application policy |
| Explicit read share | Guest can read shared fixture |
| Read guest requests write capability | Denied |
| Read ticket used for write | Denied |
| Private preferences | Distinct by tenant and subject; guest does not inherit owner preference |
| Membership revision changed | Old ticket rejected |
| Explicit write grant | Shared update accepted |
| Revoked writer reads | Denied |
| Revoked writer writes | Denied |
| Revoked guest requests fresh ticket | Denied |
| Two concurrent thread-pool tasks | Correct separate states and preferences |
| Final owner read | No revoked write corrupted the state |
The concurrent fixture starts two actual worker tasks at a barrier. The repository lock serializes protected operations, so the test verifies correct results under this in-process concurrent invocation pattern, not parallel backend throughput or a race between network delivery and revocation.
Important limitations of the teaching model#
The Principal instances and Ticket values are trusted internal objects, not public bearer tokens. A client must never be allowed to construct them or pass arbitrary principals directly into Gate. The private and threads dictionaries are deliberately exposed to the fixture setup; a real implementation must encapsulate them and protect every storage path. The create and share methods assume trusted internal callers and well-formed IDs. In particular, share on an unknown thread raises KeyError in this compact example; a public endpoint should normalize missing and unauthorized responses under its policy. The code does not test authentication, session revocation, malformed payloads, database row policies, timing side channels or real checkpoint access.
The access epoch increments on membership changes. It is not a data revision, so it does not prevent concurrent authorized writes from overwriting each other. A production collaboration service needs a separate conflict or ordering policy. The model intentionally permits a write-capable guest to read shared text; other products may define different capabilities.
The read and write checks occur under one in-process RLock. Once a value is returned to another component, later revocation does not erase it. The test does not establish atomicity between authorization and actual network transmission, provider processing or external side effects. It also does not implement multi-process locking, durable ACL persistence, audit logging or distributed fencing. Use a real authorization service, supported transactional storage and integration tests appropriate to the product.
8. Apply defense in depth in production storage#
A shared database can store multiple tenant records when the schema and access controls support it. Establish tenant and thread ownership constraints, ensure application queries use the authenticated scope, and where supported enforce database-level policies for the actual execution identity. If a privileged backend connection bypasses row-level policies, it must still enforce application authorization; enabling a database feature does not automatically restrict a privileged service role.
Keep raw checkpoint tables and memory indexes behind approved service interfaces. Separate operational administration from normal user access, enforce least privilege, and restrict bulk exports. Do not expose a store's arbitrary namespace search or raw checkpoint key enumeration to public clients.
A database transaction can ensure a membership check and a particular storage operation share a consistent authorization snapshot when designed for that purpose. It does not automatically cover external model calls, streaming delivery or separate services. For each boundary, document when access is evaluated, how stale decisions are invalidated and how revocation is propagated.
Where the infrastructure uses separate databases or namespaces for tenants, still enforce authorization in the routing layer. Selecting the wrong database can expose a complete tenant's data. Isolation at one layer does not compensate for unrestricted access at another.
9. Adversarial production verification#
Use separate synthetic tenants and users with unique canary strings. Test against real application endpoints, actual checkpoint and store implementations, streaming and tool access. Assert that protected canaries never appear in unauthorized responses, provider-bound messages, exports, attachments, traces or derived projections. Output filtering alone is insufficient if private content has already been sent to a model.
| Adversarial fixture | Expected invariant |
|---|---|
| Change public conversation ID in a valid session | No other user's state returned |
| Substitute internal checkpoint or historical revision selector | No unauthorized inspection, resume or fork |
| Forge tenant, subject or runtime context in request body | Server uses authenticated scope only |
| Same local user ID in two tenants | No namespace or checkpoint collision |
| Read-only guest submits a message or state update | Contribution denied |
| Guest requests owner's private memory | Denied or correctly scoped to guest |
| Revoke membership after authorization but before retrieval | Stale decision rejected according to policy |
| Revoke during stream or background job | Protected delivery and future actions stopped within documented guarantee |
| Two concurrent requests with identical question | No private cache or context contamination |
| Prompt requests another user's private conversation | No retrieval or action outside authorized scope |
| Shared thread with older private checkpoint | Historical disclosure policy enforced |
| Export, attachment or signed URL obtained through another route | Same object authorization enforced |
| Backend or authorization service unavailable | Fail closed for protected operations |
| Tenant membership change or role downgrade | Current permissions respected |
| Worker restart and retry | No stale privileged identity or inappropriate resumed action |
Evaluate successful authorized behavior as well as denial cases. A system that denies everyone would pass many negative checks but fail the product. Test the intended owner and collaborator experience, including separate sessions and authorized cross-thread preferences. For concurrent tests, use barriers or fault injection to exercise specific race windows; a burst of ordinary requests is not sufficient to prove revocation behavior.
Measure unauthorized access attempts, policy denials, cross-scope retrieval violations, stale access decisions, revocation propagation delay, and authorization-related availability failures. Actual unauthorized data disclosure is a critical security failure, not an acceptable trade-off for lower latency. Use safe resource aliases, request correlations and normalized decision categories in logs; do not include private canary content or real user data in routine telemetry.
Interview-ready answer#
I isolate LangChain conversations by authenticating the principal and authorizing each requested thread operation before constructing configurable.thread_id. I use separate thread identities for separate tasks, build runtime context and store namespaces from trusted tenant and subject identity, and restrict private memory retrieval to the current participant. I distinguish sharing a conversation from sharing the owner's private data or tool privileges. I bind access decisions to action and membership revision, recheck sensitive operations and delivery under the revocation policy, and prevent shared mutable request context or improperly scoped caches. I test real checkpoint, store, tool and streaming paths against cross-user, cross-tenant, sharing, revocation and concurrent-session fixtures. Thread identifiers and namespaces organize data; they do not replace authorization.
Official documentation research leads and verification status#
- LangChain short-term memory
- LangChain long-term memory
- LangChain runtime
- LangChain tools
- LangGraph persistence
- LangChain API reference
- OWASP Authorization Cheat Sheet
- OWASP API1 Broken Object Level Authorization
- Python threading
Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. The standalone application model was actually executed with Python 3.13.5 and passed 18 labeled checks, including a two-worker concurrent fixture. The environment inspection confirmed langchain, langchain_core and langgraph were absent. SDK examples, actual database authorization, real checkpoint and store integration, provider requests, distributed revocation, streaming cancellation, authentication and current documentation were not verified. All identities and canaries are synthetic. Mermaid diagrams use triple-backtick fences; rendering and public website display were not tested.
References
- 1.LangChain short-term memorydocs.langchain.com
- 2.LangChain long-term memorydocs.langchain.com
- 3.LangChain runtimedocs.langchain.com
- 4.LangChain toolsdocs.langchain.com
- 5.LangGraph persistencedocs.langchain.com
- 6.LangChain API referencereference.langchain.com
- 7.OWASP Authorization Cheat Sheetcheatsheetseries.owasp.org
- 8.
- 9.Python threadingdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps