Agent Memory Is a Database Problem Before It Is an LLM Problem
Long-term agent memory should not be an ever-growing transcript. A practical design for durable facts, provenance, retrieval, updates, expiry, and user-scoped deletion in TypeScript and Python.
On this page
A chat transcript is not a memory system.
It looks like one while the conversation is short because the application keeps resending recent messages. Close the session, cross the context limit, or start a new thread and the illusion disappears.
The usual reaction is to store every message forever and retrieve “relevant history” with embeddings. That gives the agent more persistence, but it also creates a noisy database full of duplicated statements, stale preferences, accidental secrets, and facts that were only true for one task.
I prefer to model long-term agent memory as application data with a lifecycle.
The model helps decide what may be worth remembering. The application decides how that memory is stored, scoped, retrieved, updated, expired, and deleted.
The example here is a developer-support assistant that works across sessions. It can remember stable project preferences such as “this repository uses pnpm” or “prefer PostgreSQL migrations over application-side schema sync.” It should not remember every stack trace or every temporary branch name forever.
Start with memory classes, not embeddings
Different memories have different lifetimes.
I usually separate at least these concepts:
- profile facts: durable user or project preferences;
- task facts: useful for one active workflow;
- decisions: choices the system should preserve with provenance;
- ephemeral observations: recent tool results that should age out quickly.
A single vector table can store all four, but they should not share the same retention or retrieval rules.
type MemoryKind = "profile" | "task" | "decision" | "observation";type MemoryRecord = { id: string; tenantId: string; subjectId: string; kind: MemoryKind; key: string; value: string; sourceRunId: string; sourceMessageId?: string; confidence: number; createdAt: Date; updatedAt: Date; expiresAt?: Date;};Python:
from dataclasses import dataclassfrom datetime import datetimefrom enum import Enumclass MemoryKind(str, Enum): PROFILE = "profile" TASK = "task" DECISION = "decision" OBSERVATION = "observation"@dataclass(frozen=True)class MemoryRecord: id: str tenant_id: str subject_id: str kind: MemoryKind key: str value: str source_run_id: str source_message_id: str | None confidence: float created_at: datetime updated_at: datetime expires_at: datetime | NoneThe key matters. A memory such as package_manager=pnpm is easier to replace cleanly than five free-form sentences that all say roughly the same thing.
Write memory through a policy, not directly from the transcript
I do not let every user sentence become durable memory.
A memory candidate should first pass simple rules:
- is it likely to matter in a later session?
- is it about this user/project/tenant?
- is it safe and appropriate to retain?
- is it already known?
- does it conflict with an existing value?
- should it expire?
The model can propose a candidate, but application code validates the proposal.
type MemoryCandidate = { kind: MemoryKind; key: string; value: string; confidence: number;};function validateCandidate(candidate: MemoryCandidate): void { if (candidate.key.length > 80 || candidate.value.length > 1_000) { throw new Error("Memory candidate is too large"); } if (candidate.confidence < 0 || candidate.confidence > 1) { throw new Error("Invalid memory confidence"); } const forbiddenKeys = new Set(["password", "api_key", "access_token"]); if (forbiddenKeys.has(candidate.key.toLowerCase())) { throw new Error("Secret-like data must not be stored as memory"); }}A production system needs more than a short key blacklist for sensitive data, but the architectural point is important: memory retention has a gate.
The model does not get unlimited write access to a permanent profile simply because it can summarize the conversation.
Upsert stable facts instead of appending duplicates
Suppose the user said in March that a project used npm and in May migrated it to pnpm.
Appending both facts and retrieving them later forces the model to arbitrate between stale state and current state.
For keyed profile facts, I would rather replace the active value while preserving change history in an audit table.
INSERT INTO agent_memories ( tenant_id, subject_id, kind, key, value, source_run_id, confidence, updated_at)VALUES ($1, $2, 'profile', $3, $4, $5, $6, now())ON CONFLICT (tenant_id, subject_id, kind, key)DO UPDATE SET value = EXCLUDED.value, source_run_id = EXCLUDED.source_run_id, confidence = EXCLUDED.confidence, updated_at = now();This is conventional database modeling, and it prevents a whole class of “the agent remembered both versions” bugs.
For observations or task notes, append-only storage may be more appropriate. The memory kind decides the write behavior.
Retrieval should be scoped before it is semantic
Embeddings are useful for finding which memories relate to the current request. They should not decide which tenant's memory is searchable.
The filter comes first.
type MemoryQuery = { tenantId: string; subjectId: string; kinds: MemoryKind[]; query: string; limit: number;};async function recall(query: MemoryQuery): Promise<MemoryRecord[]> { return memoryStore.semanticSearch({ tenantId: query.tenantId, subjectId: query.subjectId, kinds: query.kinds, query: query.query, limit: query.limit, excludeExpired: true, });}The model should never retrieve across users and then be told not to mention the wrong memories. Isolation belongs inside the store/query boundary.
For highly structured facts, semantic search may not be needed at all. If the application knows it needs the project's package manager, a keyed lookup is faster and more reliable than embedding the question.
That leads to a useful rule: use semantic memory retrieval for fuzzy relevance, not for data that already has a natural key.
Keep the context projection small
The memory database may contain hundreds of records. The prompt should not.
I render a compact projection containing only what the current turn needs:
function renderMemories(memories: MemoryRecord[]): string { return memories .map((memory) => `- ${memory.key}: ${memory.value}`) .join("\n");}The surrounding prompt can clearly mark this block as stored context, not fresh user instructions.
I also cap the number and total size of memories inserted. A memory system that solves persistence by recreating an enormous context window has moved the problem rather than solved it.
Memory needs expiration
Some facts decay naturally.
An observation such as “CI is currently failing on the integration test job” should probably expire soon. A task fact such as “working branch is agent/refactor-auth” may expire when the task closes. A stable project preference may have no automatic TTL.
Python makes the policy explicit:
from datetime import timedeltadef expiry_for(kind: MemoryKind, now: datetime) -> datetime | None: if kind is MemoryKind.OBSERVATION: return now + timedelta(hours=6) if kind is MemoryKind.TASK: return now + timedelta(days=14) return NoneTTL is not only a cost feature. It prevents old operational state from masquerading as current truth.
Contradictions should create an update path
Memory extraction is probabilistic. People also change their minds.
If a new candidate conflicts with an existing stable fact, I do not want an automatic append.
A simple resolution flow can be:
- load the current keyed memory;
- compare the new candidate;
- if they agree, refresh provenance/confidence if useful;
- if they conflict and the new statement is explicit, replace the active value and record history;
- if the conflict is ambiguous, ask rather than guess.
This is one of the places where a small clarification is better than an agent that confidently “remembers” the wrong preference for the next six months.
Provenance matters when memory is wrong
Every durable memory should tell me where it came from.
If the assistant starts recommending an obsolete architecture because it remembers api_style=REST, I want to trace that fact back to the run and message that created it.
That allows three useful operations:
- debug bad extraction;
- correct a specific memory;
- rebuild memory if the extraction logic changes.
Without provenance, long-term memory becomes an opaque second model state that is hard to repair.
User control is part of the design
If a system stores durable facts about a user, the user should be able to inspect and remove them where the product context calls for it.
Deletion needs to be real, not “tell the model to ignore this.”
async function deleteSubjectMemory( tenantId: string, subjectId: string, key: string,): Promise<void> { await memoryStore.delete({ tenantId, subjectId, key }); await embeddingStore.delete({ tenantId, subjectId, key });}If the memory has been copied into a secondary vector index, cache, or analytics store, the lifecycle needs to account for those copies too.
This is another reason to centralize memory writes rather than scatter them across agent nodes.
Do not store hidden reasoning as memory
The useful durable artifacts are usually facts, explicit decisions, user preferences, task checkpoints, and tool-produced state.
Hidden chain-of-thought is not a good long-term memory format. It is verbose, can contain sensitive restatements of input, and is difficult to treat as stable truth.
Store the decision and its provenance instead.
For example:
{ "kind": "decision", "key": "database_migration_strategy", "value": "expand-contract", "sourceRunId": "run_123"}That is much easier to retrieve and audit later than pages of intermediate reasoning.
Evaluate memory over time, not one turn
A memory feature can look impressive in a demo and degrade badly across weeks.
I would test at least:
- recall of a stable fact in a new session;
- replacement of an outdated keyed fact;
- expiration of temporary observations;
- tenant/user isolation;
- non-retention of secret-like data;
- deletion propagation;
- irrelevant-memory rate;
- contradiction handling.
One useful metric is precision of injected memory: of the memories inserted into prompts, how many were actually useful to the response? Retrieving ten “maybe relevant” memories every turn can create more confusion than value.
When not to build long-term memory
Many assistants do not need it.
If every task is self-contained and the required state already lives in your application database, load that state directly. Do not create an embedding-based memory layer just to make the architecture look agentic.
If the assistant only needs continuity within a short conversation, normal session history plus compaction may be enough.
Long-term memory earns its complexity when later sessions genuinely benefit from durable facts that are not already modeled elsewhere.
At that point, I want it to behave like a well-designed data subsystem: typed records, clear scope, provenance, retention rules, updates, deletion, and retrieval I can measure.
The model can help decide what matters. The database should decide what survives.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article