The Word "Memory" Is Doing Too Much Work
When someone says their agent "has memory," they usually mean one of four things, and they almost never specify which one. That ambiguity is where the production bugs come from.
Borrowing from cognitive science, agent memory splits cleanly into four kinds:
- Short-term — the live working context. The current turn, the last few turns, the scratchpad. This is just the context window.
- Episodic — past conversations. "Two weeks ago we talked about migrating the billing service."
- Semantic — facts about the world or the user. "Ashish prefers snake_case." "The prod database is in us-east-1."
- Procedural — learned tool patterns. "When the user asks for a refund, call
lookup_orderbeforeissue_refund."
Most "memory" libraries do exactly one thing: they summarize chat history and store the summaries in a vector database. That covers episodic, badly. It pretends to cover semantic. It doesn't touch procedural.
That's fine. Summarization plus retrieval is a useful primitive. But if you ship it under the name "memory" and your users expect the model to remember that they said use snake_case, you are going to have a bad time.
Why Summarization Quietly Destroys the Useful Bits
The failure mode I keep seeing in production: summarization averages out the load-bearing details.
Turn 14, the user says: "Always use snake_case for column names, never camelCase, and prefix audit columns with audit_."
Turn 47, the agent generates SQL with userId and createdAt. The user is annoyed. You go check the summary buffer. It reads:
The user has discussed database schema preferences and naming conventions.
That's a true sentence. It's also useless. The specific, opinionated, load-bearing instruction got laundered into a vague nominalization. The model can't act on "preferences."
This happens because LLM summarizers are trained to produce summaries that look good to humans skimming them. They are not trained to preserve the directives a downstream agent needs to act on. Generic summarization is a lossy compressor with the wrong loss function.
Extract Facts, Don't Summarize Conversations
The fix is to stop summarizing and start extracting. After each turn (or every N turns), run a structured extraction pass that pulls out facts in a fixed shape:
type Fact = {
id: string // uuid
subject: string // "user" | "system" | entity ref
predicate: string // "prefers" | "owns" | "located_in"
object: string // "snake_case for column names"
source_msg_id: string // for audit + verification
confidence: number // 0..1, from the extractor
created_at: Date
last_accessed_at: Date
pinned: boolean // manual override
}
The extractor prompt is boring on purpose. Show it the last few turns, ask it to emit triples in JSON, give it a tools-style schema so it can't hallucinate the wrapper. Reject anything below a confidence threshold. Deduplicate by (subject, predicate) — if there's a newer fact with the same key, mark the old one stale.
The win: when the agent later needs to know how the user wants column names, you don't retrieve a paragraph of vibes. You retrieve a row that says user / prefers / snake_case for column names. The model can act on that.
Storage: Boring Is Correct
For the storage layer, I have not found anything that beats Postgres with pgvector for facts plus a normal relational table for episodic threads. The whole stack:
create table facts (
id uuid primary key,
subject text not null,
predicate text not null,
object text not null,
source_msg_id uuid references messages(id),
confidence real not null,
embedding vector(1024), -- whatever your model produces
pinned boolean default false,
access_count int default 0,
last_accessed timestamptz default now(),
created_at timestamptz default now(),
unique (subject, predicate, object)
);
create index facts_embedding_idx
on facts using hnsw (embedding vector_cosine_ops);
create index facts_subject_idx on facts (subject);
Querying is two paths joined:
async function recall(query: string, subject: string) {
const qvec = await embed(query)
// Semantic: nearest facts by embedding, scoped to subject.
const semantic = await sql`
select *, 1 - (embedding <=> ${qvec}) as score
from facts
where subject = ${subject}
order by embedding <=> ${qvec}
limit 20
`
// Pinned: always include, regardless of similarity.
const pinned = await sql`
select * from facts
where subject = ${subject} and pinned = true
`
return dedupe([...pinned, ...semantic])
}
Pinned facts are not optional. Every real deployment ends up with a handful of facts that must be in context every turn ("the user's company is X," "the deploy target is staging"). Trying to surface those via cosine similarity alone is how you end up with the agent forgetting the company name on turn 30.
Eviction Is the Actually Hard Problem
Everyone gets storage right. Everyone gets eviction wrong.
LRU is the obvious wrong answer. Rare important facts ("the API key rotates every 90 days") get accessed once, never bubble up in normal queries, and get evicted right before they become relevant. The thing that's accessed least is often the thing that matters most.
What works better is an access-time-weighted score that's bounded from below for pinned facts:
score = w1 * log(1 + access_count)
+ w2 * recency_decay(last_accessed)
+ w3 * confidence
+ (pinned ? +infinity : 0)
Tune the weights against a labelled set of "facts you would have wanted." I've landed on roughly w1 = 0.3, w2 = 0.5, w3 = 0.2 across two different deployments — recency dominates, but a fact that's been hit ten times still beats one hit yesterday.
The other half of the answer: don't evict, just don't retrieve. Storage is cheap. Keep everything, score everything, only top-K reaches the prompt. Hard delete only when a fact is contradicted by a newer one with higher confidence.
Recency vs. Relevance: A Concrete Failure
A real one from production. User asked the agent in January: "we use Stripe for payments." Six months later, the company migrated to Adyen. User mentioned it once, in passing, in May.
The agent kept generating Stripe code through July. Why? The January fact had been re-accessed (and re-embedded) dozens of times across the user's sessions. The May fact got embedded once and lost to cosine similarity because the embedding emphasized the migration phrasing, not the payment-provider semantics.
Two fixes, both required:
- Contradiction detection at write time. New fact arrives, query for facts with the same
(subject, predicate). Ifobjectdiffers, run a tiny classifier that asks: is this an update or a coexistence? Update → mark old fact stale. Coexistence → keep both. - Recency floor on retrieval. When two facts contradict, the newer one wins regardless of similarity score. Don't let a stale, well-embedded fact outvote a fresh one.
Memory Drift: The Three-Month Time Bomb
The other failure mode is drift. After enough turns, your fact store contains things that were true once and aren't anymore. The user's job title changed. The project moved repos. The team got reorganized.
You need a periodic verification pass. Cheap version: every N days, sample 1% of facts, ask the model to flag any that look stale or self-contradictory given the recent conversation. Expensive version: re-confirm with the user — "still using snake_case on the new project?"
I have shipped both. The cheap version catches roughly half of drift before the user does. The expensive version annoys users if you run it too often. Once a month, on facts older than 60 days, for high-stakes domains only.
The Library Landscape, Honestly
Three things worth looking at, with their actual tradeoffs:
| Library | What it actually is | When it fits |
|---|---|---|
| Mem0 | Fact extraction + pgvector + a thin API. Closest to what I described above. | Good default if you don't want to build the extraction loop yourself. |
| Letta (formerly MemGPT) | OS-style memory hierarchy with the model doing its own paging via tool calls. | Useful when the agent itself should reason about what to remember. Heavier, more tokens. |
| Zep | Hosted, opinionated, knowledge-graph flavored. Decent extraction quality. | If you want a managed service and your data isn't sensitive enough to require self-hosting. |
None of them solve eviction well. None of them solve drift at all. You will end up writing the verification pass yourself regardless of which one you pick.
What Didn't Work
The first version I built was clever, which is always the warning sign. I had a single embedding space for everything — chat turns, extracted facts, tool call traces — and ranked them together at retrieval time.
It looked elegant on the whiteboard. In practice, raw chat turns dominated the top-K because they were more numerous and their embeddings were noisier (more lexical overlap with arbitrary queries). Facts, the things I had spent extraction tokens to produce, were getting outvoted by literal copies of the conversation they were extracted from.
The fix was unglamorous: separate tables, separate retrieval calls, merge at the end with type-aware weights. Facts get a 2x multiplier over raw chat. Pinned facts skip the ranker entirely.
Lesson: a unified vector space is the kind of architectural purity that costs you accuracy. The "right" abstraction is not the one with the fewest tables.
A Sharper Takeaway
Agent memory is a database with worse access patterns. Treat it that way. Pick a schema, pick eviction rules, write the verification job, and stop pretending an embedding model has opinions about what your users care about. Don't overthink it. But don't underthink it either — the model only knows what you decided to put in front of it.