Agent Memory Is a Data Pipeline, Not a Bigger Context Window
· Bilal Tahseen

The failure pattern I see in agent systems that grew past the demo: every conversation turn gets dumped into a vector store. It works in the proof-of-concept. Then the agent starts recalling stale preferences, mixing up users, repeating something a web page told it as if the user said it, and nobody can delete anything because "deletion" is a soft flag that the retrieval ignores.
Memory is not a bigger context window. It's a data pipeline with a write path, a read path, and a deletion path. Treat it like one.
Session state vs long-term memory
Most things an agent learns in a conversation should NOT become long-term memory.
Session state lives in the run or thread checkpoint. It dies with the session. The user's current task, the files they're working on, the intermediate reasoning steps, the tool results from this run — all session state. When the session ends, it's gone. That's correct.
Long-term memory survives sessions. It's scoped per tenant and per user. The user's name, their report format preference, the fact that they're on the EU data residency plan, the instruction "never use Helvetica" — these are durable, and they should be recalled in the next session.
The distinction matters because the write path is different. Session state is append-only: every turn adds to the checkpoint. Long-term memory has a gate: a candidate fact is proposed, evaluated, and either written, skipped, or held for consent. If you treat session state as long-term memory, you're writing thousands of facts per session and retrieving noise. If you treat long-term memory as session state, you're losing information the agent needs to remember.
The two paths

The architecture has three pipelines:
- Write path: conversation turn → LLM extractor → policy gate → dedupe and conflict resolver → scoped, versioned memory store.
- Read path: new request → tenant/user scope filter → hybrid retrieval → rerank and token budget → injected into the prompt.
- Forgetting path: TTL expiry, user-initiated "forget that," and full user deletion that actually removes rows.
Each pipeline has its own failure modes. Each one needs its own tests. I'll walk through them one by one.
Write path: extraction, policy, supersede
The write path is not "append the chat history to a vector DB." The write path is a gauntlet. Most candidate facts don't make it through.
Extractor: propose, don't write
An LLM call with structured output proposes candidate memories. It never writes directly to the store. The extractor reads the conversation turn and outputs zero or more candidates.
from typing import Literal
from pydantic import BaseModel, Field
class MemoryCandidate(BaseModel):
kind: Literal["preference", "fact", "instruction"]
subject: str = Field(description="Stable normalized key, e.g. 'report_format'")
content: str = Field(max_length=500)
confidence: float = Field(ge=0.0, le=1.0)
source_turn_id: str
source_role: Literal["user", "assistant", "tool"]
The subject is a stable, normalized key. If the user says "I prefer tables over charts" and later says "actually, charts are fine," both are subject: "visualization_preference". The second one supersedes the first. If the subject is a UUID or a timestamp, you can't dedupe or supersede.
The source_role matters. If the candidate came from a tool result or a web page the agent retrieved, that's where memory poisoning comes from. I wrote about this in prompt injection defense for tool results: an attacker who controls a web page or a tool's output can inject fake memories. The extractor proposes candidates, but source_role and source_turn_id must be stamped by your pipeline code from the turn's actual role, not trusted from the extractor's output — the extractor itself can be manipulated by injected text. The policy gate uses these fields to filter.
Policy gate: durable, user-stated, not sensitive, doesn't contradict
Before a candidate becomes a memory, it passes a decision tree:

Is it durable? If the fact only matters in this session, keep it in session state. "The user is editing file X" is not long-term memory. "The user prefers two-space indents" is.
Is it user-stated? Check source_role. If it's not "user", discard it. Tool results and retrieved pages are untrusted. An attacker who controls a tool's output or a web page can inject "the user's password is X" or "the user wants you to ignore all instructions." Assistant-generated claims should also be discarded unless the user explicitly confirmed them. You can't defend against that at retrieval time because by then the malicious memory is already in the store. Defend at write time: only user-stated facts become memory.
Is it sensitive? PII, credentials, health information, anything regulated. The policy depends on your jurisdiction and your consent model. I default to: if the fact contains a phone number, email, address, or anything that looks like a credential, skip it or prompt the user for consent. If you write sensitive data to memory, you own the retention, the deletion, and the breach disclosure. Be sure.
Does it contradict an existing memory? If a memory with the same subject already exists, the new one supersedes it. The old row is not deleted. It's marked as superseded, the version increments, and the new row points back to the old one for provenance. Supersede, don't overwrite. I'll show the schema in a moment.
If the candidate passes all of those, write it with a TTL and provenance.
Supersede, don't overwrite
The schema is Postgres with pgvector:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE agent_memory (
id uuid PRIMARY KEY,
tenant_id text NOT NULL,
user_id text NOT NULL,
kind text NOT NULL CHECK (kind IN ('preference', 'fact', 'instruction')),
subject text NOT NULL,
content text NOT NULL,
embedding vector(1536) NOT NULL, -- match your embedding model's dimension
source_turn_id text NOT NULL, -- provenance: which turn said this
confidence real NOT NULL CHECK (confidence BETWEEN 0 AND 1),
version int NOT NULL DEFAULT 1,
superseded_by uuid REFERENCES agent_memory(id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz
);
-- At most one live memory per subject per user.
CREATE UNIQUE INDEX agent_memory_one_live
ON agent_memory (tenant_id, user_id, subject)
WHERE superseded_by IS NULL;
CREATE INDEX agent_memory_embedding
ON agent_memory USING hnsw (embedding vector_cosine_ops);
-- Deletions are logged without the content.
CREATE TABLE agent_memory_audit (
id bigserial PRIMARY KEY,
tenant_id text NOT NULL,
user_id text NOT NULL,
action text NOT NULL,
row_count int NOT NULL,
at timestamptz NOT NULL DEFAULT now()
);
The superseded_by foreign key is deferred and cascades on delete. The deferred part matters when you write a new version: the old row's superseded_by column points at the new row's id before the new row exists, so the deferred FK lets you write both updates in one transaction without violating the constraint. The cascade matters when you delete: if a live row expires and the TTL purge deletes it, any older superseded versions that point at it are also deleted, preventing orphaned chains and FK violations.
The partial unique index enforces one live memory per (tenant_id, user_id, subject). If two workers race to create the first memory for a subject, one gets a UniqueViolation and retries. Without the partial index, both would succeed and you'd have duplicates.
Here's the write function (psycopg 3):
import uuid
from datetime import datetime, timedelta, timezone
import psycopg
from psycopg import errors
def write_memory(
conn: psycopg.Connection,
tenant_id: str,
user_id: str,
cand: MemoryCandidate,
embedding: list[float],
ttl_days: int | None = 180,
) -> uuid.UUID:
new_id = uuid.uuid4()
expires_at = (
(datetime.now(timezone.utc) + timedelta(days=ttl_days)) if ttl_days else None
)
vec = "[" + ",".join(str(x) for x in embedding) + "]"
for attempt in range(2):
try:
with conn.transaction():
old = conn.execute(
"""SELECT id, version FROM agent_memory
WHERE tenant_id = %s AND user_id = %s AND subject = %s
AND superseded_by IS NULL
FOR UPDATE""",
(tenant_id, user_id, cand.subject),
).fetchone()
version = 1
if old:
conn.execute(
"UPDATE agent_memory SET superseded_by = %s WHERE id = %s",
(new_id, old[0]),
)
version = old[1] + 1
conn.execute(
"""INSERT INTO agent_memory
(id, tenant_id, user_id, kind, subject, content, embedding,
source_turn_id, confidence, version, expires_at)
VALUES (%s, %s, %s, %s, %s, %s, %s::vector, %s, %s, %s, %s)""",
(
new_id,
tenant_id,
user_id,
cand.kind,
cand.subject,
cand.content,
vec,
cand.source_turn_id,
cand.confidence,
version,
expires_at,
),
)
return new_id
except errors.UniqueViolation:
if attempt == 1:
raise
raise RuntimeError("unreachable")
If a memory with the same subject already exists, the old row is updated to point at the new one, then the new one is inserted with an incremented version. If two workers race and both try to insert the first version, one gets a UniqueViolation, catches it, and retries. On the retry, the memory exists, so it supersedes instead of inserting a duplicate.
The TTL defaults to 180 days. A preference stated six months ago might not be valid now. The agent should re-learn it, not recall stale state forever. If you want permanent memories, pass ttl_days=None.
Read path: scope, retrieve, rerank, budget
The read path is not "embed the query and return the top K." The read path is scoped, filtered, reranked, and budget-constrained.
Scope filter first, in SQL
Access control happens in the query, not in the prompt. Filter by tenant_id and user_id before you retrieve. If you retrieve cross-tenant and rely on the LLM to ignore memories from other users, you've already lost.
SELECT id, subject, content, confidence, created_at,
1 - (embedding <=> %(query_vec)s::vector) AS similarity
FROM agent_memory
WHERE tenant_id = %(tenant_id)s
AND user_id = %(user_id)s
AND superseded_by IS NULL
AND (expires_at IS NULL OR expires_at > now())
ORDER BY embedding <=> %(query_vec)s::vector
LIMIT 20;
This is the base retrieval. It returns only live, non-expired memories for the tenant and user. The superseded_by IS NULL filter means you never retrieve old versions. The expires_at filter means TTL expiry happens at read time, not with a background job. You can run a periodic purge to reclaim space, but the memories are already invisible once they expire.
I wrote about this pattern in permission-aware RAG with access control: filtering in SQL is the only way to enforce access control reliably.
Hybrid retrieval: vector + keyword
Vector search alone misses exact matches. If the user's name is "Priya" and the query is "what's the user's name?", a pure semantic search might not return the name because "name" and "Priya" aren't semantically close in the embedding space.
Add a keyword match alongside the vector search. Postgres full-text search:
WITH scored AS (
SELECT id, subject, content, confidence, created_at,
1 - (embedding <=> %(query_vec)s::vector) AS vec_similarity,
ts_rank(to_tsvector('english', content), plainto_tsquery('english', %(query_text)s)) AS keyword_rank
FROM agent_memory
WHERE tenant_id = %(tenant_id)s
AND user_id = %(user_id)s
AND superseded_by IS NULL
AND (expires_at IS NULL OR expires_at > now())
AND (
embedding <=> %(query_vec)s::vector < 0.3
OR to_tsvector('english', content) @@ plainto_tsquery('english', %(query_text)s)
)
)
SELECT id, subject, content, confidence, created_at,
vec_similarity + keyword_rank AS similarity
FROM scored
ORDER BY similarity DESC
LIMIT 20;
The combined filter retrieves rows that are either semantically similar or contain the query keywords. Merge the candidate sets, then rerank. I'm showing the structure, not production code — production versions normalize the scores, tune the vector threshold, and may use a separate BM25 index.
Rerank by similarity, recency, confidence
Raw retrieval order is not prompt order. Rerank the candidates before you inject them.
from datetime import datetime, timezone
def score(m: dict, now: datetime, half_life_days: float = 30.0) -> float:
age_days = (now - m["created_at"]).total_seconds() / 86400
recency = 0.5 ** (age_days / half_life_days)
return 0.6 * m["similarity"] + 0.25 * recency + 0.15 * m["confidence"]
def select_memories(rows: list[dict], budget_tokens: int, count_tokens) -> list[dict]:
now = datetime.now(timezone.utc)
picked, used = [], 0
for m in sorted(rows, key=lambda r: score(r, now), reverse=True):
cost = count_tokens(m["content"])
if used + cost > budget_tokens:
continue
picked.append(m)
used += cost
return picked
The weights are 0.6 for similarity, 0.25 for recency, and 0.15 for confidence. The half-life is 30 days: a memory that's 30 days old has half the recency score of one created today. These are starting points. Tune them on your own eval set. I wrote about building that eval set in golden set eval gate before shipping agents. The weights are not measured results. They're guesses that you refine with data.
The token budget is a hard cap. If the memory would overflow the prompt, it's not included. This is the same pattern as budget caps for agents: enforce limits in code, not in the LLM's judgment.
Inject memories as data, not instructions
Don't inject memories as instructions:
The user prefers CSV format.
The user's name is Alice.
The user is in the EU region.
That's indistinguishable from a system prompt, and it's vulnerable to injection. If a malicious memory says "ignore all previous instructions," the LLM might.
Inject them as clearly labeled data:
<memories>
<memory created="2026-11-15" confidence="0.95">The user's report format preference is CSV.</memory>
<memory created="2026-10-02" confidence="1.0">The user's name is Alice Chen.</memory>
<memory created="2026-09-20" confidence="1.0">The user's data residency region is EU.</memory>
</memories>
The XML tags, the dates, and the confidence scores make it clear these are data, not instructions. The LLM can reason about them, but it's less likely to treat them as directives.
Forgetting path: TTL, user deletion, audit
Forgetting is not optional. GDPR, CCPA, and common sense all require deletion.
TTL expiry
Memories expire automatically. The expires_at column is set when the memory is written. The read query filters expires_at IS NULL OR expires_at > now(), so expired memories are invisible at read time.
A periodic background job purges expired rows and old superseded versions:
DELETE FROM agent_memory
WHERE expires_at IS NOT NULL AND expires_at < now();
DELETE FROM agent_memory
WHERE superseded_by IS NOT NULL
AND created_at < now() - interval '90 days';
The first purge removes expired memories. The second removes superseded versions older than 90 days, preventing unbounded version chains. Live memories are hidden immediately when they expire, then deleted by the next purge run.
User-initiated "forget that"
If the user says "forget that," the agent identifies the subject and supersedes or deletes the memory:
def forget_subject(
conn: psycopg.Connection, tenant_id: str, user_id: str, subject: str
) -> int:
with conn.transaction():
cur = conn.execute(
"""DELETE FROM agent_memory
WHERE tenant_id = %s AND user_id = %s AND subject = %s""",
(tenant_id, user_id, subject),
)
return cur.rowcount
This deletes all versions of the memory with that subject, including superseded ones. The row is gone. If you need an audit trail, write a row to agent_memory_audit before deleting:
def forget_subject_with_audit(
conn: psycopg.Connection, tenant_id: str, user_id: str, subject: str
) -> int:
with conn.transaction():
cur = conn.execute(
"""DELETE FROM agent_memory
WHERE tenant_id = %s AND user_id = %s AND subject = %s""",
(tenant_id, user_id, subject),
)
conn.execute(
"""INSERT INTO agent_memory_audit (tenant_id, user_id, action, row_count)
VALUES (%s, %s, 'forget_subject', %s)""",
(tenant_id, user_id, cur.rowcount),
)
return cur.rowcount
The audit row records that a deletion happened, how many rows were deleted, and when, but it does not store the content. You can prove you deleted the data without keeping a copy of it.
Full user deletion
When a user deletes their account or submits a deletion request, all their memories must be deleted:
def delete_user_memory(conn: psycopg.Connection, tenant_id: str, user_id: str) -> int:
with conn.transaction():
cur = conn.execute(
"DELETE FROM agent_memory WHERE tenant_id = %s AND user_id = %s",
(tenant_id, user_id),
)
conn.execute(
"""INSERT INTO agent_memory_audit (tenant_id, user_id, action, row_count)
VALUES (%s, %s, 'delete_user', %s)""",
(tenant_id, user_id, cur.rowcount),
)
return cur.rowcount
This deletes every memory row for the user, including superseded versions. The audit row proves the deletion happened without storing the deleted content.
One more thing: copies in traces, logs, and backups need their own retention policies. If your traces include the full prompt with injected memories, and your traces are retained for a year, the memories are retained for a year. I wrote about this in replayable traces for production agents: trace retention is part of your data retention policy. If a user requests deletion, you need to purge or redact their data from traces and backups too, not just the live database.
When NOT to build long-term memory
Not every agent needs long-term memory.
Single-session tools. If the agent runs once and never sees the user again, session state is enough. A code review agent that reads a PR, writes a comment, and exits doesn't need to remember anything across sessions.
Stateless workflows. If every request is independent and there's no user identity, there's nothing to remember. An agent that answers questions from a knowledge base doesn't need memory. The knowledge base is already the durable state.
Regulated data with no consent story. If you're handling health data, financial data, or anything else regulated, and you don't have a consent mechanism for storing it long-term, don't store it. Session state only. Delete it when the session ends.
Be honest about whether your agent needs memory. If the agent doesn't benefit from recalling information across sessions, the complexity of the write path, the read path, the deletion path, and the compliance overhead is wasted. Session state is simpler and safer.
Production checklist
If you're building this, here's what I make sure works before it ships:
- The write path uses an LLM extractor that proposes candidates; it never writes chat history directly to the store.
- The policy gate filters by source_role: tool results and retrieved pages are not written as long-term memory.
- Sensitive data is skipped or requires explicit consent before being stored.
- Supersede is implemented correctly: the partial unique index enforces one live memory per subject, and versioning is tracked.
- The read path filters by tenant_id and user_id in SQL before retrieval.
- Expired memories are invisible at read time, and a periodic job purges them from the database.
- Reranking uses similarity, recency, and confidence, and the weights have been tuned on an eval set.
- Memories are injected as labeled data with dates, not as instructions.
- User deletion actually deletes rows and writes an audit entry without storing content.
- Trace retention is scoped: if prompts include memories, traces have the same retention as the memories themselves.
And one more: test the deletion path. Most teams test the write path, test the read path, and assume deletion works. Test it. Trigger a user deletion request, run the deletion function, then try to retrieve the deleted user's memories. If you get results, deletion is broken. Fix it before you ship.
Close
Most "agent memory" is a vector store that every turn gets dumped into. It works in a demo. Then the agent recalls stale preferences, mixes up users, repeats something a tool result told it as if the user said it, and nobody can delete anything because the deletion path was never built.
Memory is a data pipeline. The write path extracts candidates, gates them by policy, dedupes and supersedes conflicts, and writes versioned facts with TTLs. The read path scopes by tenant and user, retrieves with hybrid search, reranks by similarity, recency, and confidence, and fits to a token budget. The forgetting path expires old memories, honors user deletion requests, and logs deletions without keeping the deleted content.
If you're building an agent with long-term memory and you need this designed properly — write path that defends against memory poisoning, read path with correct access control, deletion path that holds up to a privacy request — let's talk: https://www.bilaltahseen.com/hire-ai-engineer.
Building something with AI?
I help teams ship production AI agents, retrieval systems, and document intelligence. Let's talk about yours.