Skip to main content
Back to all articles
AI Engineering 9 min readUpdated October 4, 2026

Your Agent Remembers Too Much. Give Its Memory a Garbage Collector.

Long-term agent memory degrades when every old observation remains equally alive. Separate supersession, decay, and forget; reinforce useful evidence; archive weak memories; and run background GC so stale state stops competing with current truth.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#AI Agents#Agent Memory#Memory Garbage Collection#Evidence Decay#Supersession#Context Engineering#TypeScript#Python#Production AI
On this page

A support agent is reviewing a $420 refund.

At 9:10 in the morning, it stored this memory:

Text
Refunds above $500 require manager approval.

Later that day, the policy changed. A newer memory says:

Text
Refunds above $300 require manager approval.

At 4:30, the agent searches its long-term memory. Both statements are semantically relevant. The older one happens to be a slightly better embedding match, so it comes back first.

The retriever worked.

The memory system failed.

This is the failure mode I care about once agent memory survives long enough to become useful: old evidence keeps competing as if it were still current.

I wrote earlier about treating agent memory as application data: typed records, scope, provenance, expiry, updates, and deletion. That is the foundation.

This article starts later, when that foundation has been running for months and the store is full of memories that were once useful.

At that point, the hard problem is not remembering more.

It is deciding what should still be allowed to influence the next decision.

A vector database is an index, not a retention policy

Vector search answers a narrow question:

Which stored items look similar to this query?

It does not answer:

Which of those items is still current?

It also does not know whether an old observation has been replaced, whether a memory has repeatedly led to bad decisions, or whether a user explicitly asked for something to be forgotten.

Those are lifecycle decisions.

I think of memory retrieval and memory garbage collection as two different systems:

Text
retrieval  -> what looks relevant right now?​memory GC  -> what is still allowed to compete at all?

If every historical statement stays permanently active, retrieval quality eventually becomes a function of how much stale material happens to resemble the current request.

That is not long-term memory. It is an ever-growing argument with your past self.

Supersession, decay, and forgetting are different operations

I would not implement one generic deleteOldMemories() job.

There are at least three reasons a memory should stop appearing in normal retrieval, and they need different semantics.

Supersession: this used to be true

The refund threshold changed from $500 to $300.

The old memory is not necessarily garbage. It may be useful for audit, incident review, or understanding a decision made yesterday.

But it is no longer the current value.

I want the relationship recorded explicitly:

Text
refund_policy_v1  valid until 2026-09-22 14:30  superseded by refund_policy_v2​refund_policy_v2  current

Normal retrieval should prefer the current record and exclude the superseded one unless the query is explicitly historical.

Decay: this stopped being useful

Now imagine a troubleshooting agent remembers:

Text
The checkout service usually fails because the Redis connection pool is exhausted.

That observation helped during an incident two months ago. The system has since changed. Nobody has used the memory recently, and newer incidents point elsewhere.

This is a good decay candidate.

The statement is not necessarily false. It has simply lost enough current value that it should no longer outrank fresher evidence.

Decay is about retrieval influence, not rewriting history.

Forget: this should not exist for the agent

A user asks the system to remove a stored preference. A retention policy expires personal data. A secret was accidentally captured.

That is not decay.

Lowering the vector score is not deletion.

I want an explicit forget path that removes the memory from active storage, vector indexes, derived caches, and other replicas according to the product's deletion policy. If an audit tombstone is required, the tombstone should contain the minimum metadata needed to prove the deletion happened—not the sensitive content we were supposed to erase.

That distinction matters enough that I would encode it in the state model.

TypeScript
type MemoryState =  | "active"  | "superseded"  | "archived"  | "forgotten";​type MemoryRecord = {  id: string;  tenantId: string;  subjectId: string;  kind: "fact" | "preference" | "observation" | "procedure";  claim: string;  state: MemoryState;​  sourceId: string;  sourceVersion?: string;​  createdAt: string;  lastUsedAt?: string;  lastValidatedAt?: string;​  helpfulUses: number;  harmfulUses: number;​  supersedesId?: string;  validUntil?: string;};

The point is not these exact fields. The point is that *currentness* and *survival* are first-class state rather than something the retriever is expected to infer from cosine similarity.

Do not let retrieval reinforce a bad memory forever

A common lifecycle idea is that frequently retrieved memories should become stronger.

That can be useful, but I would be careful with the word retrieved.

Suppose the stale $500 refund rule is returned ten times because it is a strong semantic match. If every retrieval increases its survival score, the mistake can make itself immortal.

I prefer to reinforce a memory only after there is evidence that it helped.

For example:

Text
candidate retrieved        ↓actually entered working context        ↓used in a decision        ↓result validated / successful        ↓reinforce

A memory that was merely considered is not proven useful.

A memory that produced a failed tool call, contradicted the source of truth, or had to be corrected should move in the other direction.

A small utility score can be enough:

TypeScript
function utility(memory: MemoryRecord): number {  const total = memory.helpfulUses + memory.harmfulUses;​  if (total === 0) return 0.5;​  return memory.helpfulUses / total;}

I would not use this number as truth. It is one lifecycle signal alongside provenance, source freshness, explicit importance, and the memory type.

A user's pinned preference should not disappear because it was not used for three months. A volatile operational observation probably should fade much faster.

Facts should be invalidated by evidence, not by a timer

This is where I think simple “memory decay” explanations become misleading.

A fact does not become 40% false because thirty days passed.

If the agent remembers:

Text
This repository uses pnpm.

and the repository still uses pnpm, the fact remains correct even if nobody asked about package management for six months.

For factual memory, I care more about evidence freshness than elapsed time.

If a memory came from a source with a version, keep that version:

Text
claim: repository uses pnpmsource: package.jsonsource version: commit a81e7c

When the source changes, mark the claim as needing revalidation.

The recent OpenWiki work from LangChain makes this distinction nicely: a changed source does not prove that a stored claim is wrong, but it does remove the right to assume the claim is still current until it is checked again.

That is a much stronger model than “old memories get a lower score.”

For production memory, I want both concepts:

Text
evidence freshness  -> can I still trust this claim as current?​usage decay  -> even if valid, is it useful enough to keep hot?

Those are different questions.

The lifecycle I would actually run

The background loop looks like this:

Agent memory garbage collection lifecycle

I like borrowing the vocabulary of a normal garbage collector, with one important difference: we are not deciding whether an object is reachable. We are deciding whether a memory is still valid, useful, and policy-eligible.

Mark

The GC job evaluates active memories and records what should happen next.

Questions include:

Text
Was this memory superseded by a newer value?Has its supporting source changed?Was it explicitly pinned?Has it been useful recently?Has it repeatedly produced bad outcomes?Is it under a hard retention or deletion policy?Does another memory duplicate the same claim?

No destructive work needs to happen during this phase.

Sweep

The sweep removes weak memories from the active retrieval path.

That may mean moving a record from hot to warm storage, de-indexing it from the default vector collection, or marking it archived so ordinary recall excludes it.

The key point is that normal aging should usually remove *influence* before it removes *history*.

Compact

Now merge duplicates and compress repeated episodes into something smaller and more durable.

Suppose five incidents contain variations of:

Text
checkout failed because Redis pool was exhausted

If the pattern has been independently validated, I do not necessarily want five nearly identical memories occupying five retrieval slots.

I may consolidate them into one procedural memory with provenance back to the supporting episodes.

That saves context and reduces duplicate retrieval without throwing away the audit trail.

A GC decision should be explainable

I do not want an LLM to look at 20,000 memories every night and silently decide what survives.

The model can help with semantic consolidation or contradiction detection, but the lifecycle decision should have inspectable reasons.

For example:

TypeScript
type GcDecision =  | { action: "keep"; reason: string }  | { action: "revalidate"; reason: string }  | { action: "archive"; reason: string }  | { action: "supersede"; replacementId: string; reason: string }  | { action: "purge"; reason: string };​function decideGc(  memory: MemoryRecord,  now: Date,): GcDecision {  if (memory.state === "forgotten") {    return { action: "purge", reason: "explicit forget state" };  }​  if (memory.supersedesId) {    return { action: "keep", reason: "this is a replacement memory" };  }​  if (    memory.validUntil &&    Date.parse(memory.validUntil) < now.getTime()  ) {    return { action: "revalidate", reason: "validity window expired" };  }​  const uses = memory.helpfulUses + memory.harmfulUses;  const harmfulRatio = uses === 0 ? 0 : memory.harmfulUses / uses;​  if (uses >= 3 && harmfulRatio > 0.5) {    return { action: "archive", reason: "memory has repeatedly hurt outcomes" };  }​  return { action: "keep", reason: "no lifecycle rule fired" };}

Python follows the same idea:

Python
from dataclasses import dataclassfrom datetime import datetimefrom typing import Literal​​@dataclass(frozen=True)class GcDecision:    action: Literal[        "keep",        "revalidate",        "archive",        "supersede",        "purge",    ]    reason: str    replacement_id: str | None = None​​def decide_gc(memory: dict, now: datetime) -> GcDecision:    if memory["state"] == "forgotten":        return GcDecision("purge", "explicit forget state")​    valid_until = memory.get("validUntil")    if valid_until and datetime.fromisoformat(valid_until) < now:        return GcDecision("revalidate", "validity window expired")​    helpful = memory.get("helpfulUses", 0)    harmful = memory.get("harmfulUses", 0)    uses = helpful + harmful​    if uses >= 3 and harmful / uses > 0.5:        return GcDecision(            "archive",            "memory has repeatedly hurt outcomes",        )​    return GcDecision("keep", "no lifecycle rule fired")

These examples are deliberately conservative. A real policy would vary by memory type and data class.

The useful property is that a memory can tell me *why* it left the active set.

Do not hard-delete ordinary decay

If an observation simply became irrelevant, I usually archive it first.

That gives me three benefits.

First, a rare but legitimate historical query can still reach it through an explicit archive path.

Second, I can debug why the agent behaved differently last month.

Third, a lifecycle bug is reversible. If the GC job was too aggressive, archived memories can be restored without recreating them from raw conversations.

Hard deletion should be deliberate: user request, legal/policy expiry, secret removal, or another explicit requirement.

This is the same reason databases use tombstones, soft deletion, and retention tiers in other systems. Irrelevance and erasure are not the same event.

Keep the authoritative source outside memory when you can

The best stale-memory fix is sometimes not better garbage collection.

It is not storing the fact as memory in the first place.

If the refund threshold already lives in a policy service, the agent should retrieve the current policy from that service. Duplicating the threshold into long-term memory creates a second source of truth that now needs synchronization.

Memory is a good place for things that would otherwise disappear:

Text
user preferencespast decisionsinteraction outcomesuseful procedural experienceproject-specific context

It is a bad place to mirror business records that already have an authoritative home.

A memory GC can reduce stale data. It should not become an excuse to cache your whole company inside an agent profile.

The background worker should stay off the inference path

I do not want a user request to pause while the system scans six months of memory and decides what to archive.

The online path should remain small:

Text
query  -> scope filter  -> active-memory retrieval  -> rank  -> assemble context

Lifecycle work happens asynchronously:

Text
memory events  -> reinforcement updates  -> source-change signals  -> scheduled GC  -> consolidation  -> archive / purge

Microsoft's current multi-agent reference architecture uses the same broad lifecycle idea: extraction, consolidation, reinforcement, decay, and deletion are separate stages, with access metadata written back asynchronously rather than blocking retrieval.

That separation is operationally important. A memory system should not make every inference depend on the health of a nightly curation job.

What I would measure

A garbage collector is only useful if retrieval gets better because of it.

I would track a small set of memory-specific metrics:

Text
active memories per subjectarchived memories per subjectsupersession raterevalidation rateexplicit forget completion timeduplicate-memory ratestale-memory retrieval ratememory precision in assembled contextmemory tokens per requestGC decisions by reason

The one I care about most is stale-memory retrieval rate.

How often did an inactive, contradicted, or evidence-stale memory make it into the context that influenced an answer?

That is a better signal than “the vector database contains 40% fewer rows.”

Storage size is an infrastructure metric.

Stale influence is a product-quality metric.

Test the failures that take months to appear

Memory systems look great in demos because the store is clean and the facts are recent.

I would create an evaluation that deliberately ages the system.

For example:

Text
T1: store refund threshold = $500T2: use it successfully several timesT3: policy changes threshold to $300T4: ask about a $420 refundT5: ask a historical question about the old policyT6: explicitly delete a stored user preference

Then assert:

Text
T4 uses the $300 current ruleT5 can still explain the historical $500 rule when history is requestedT6 cannot retrieve the deleted preference through normal memory, vectors, or cache

I would also test the uncomfortable case:

Text
A stale memory was previously very popular.

Frequency must not beat supersession.

A memory used 200 times yesterday can still become wrong today.

The production rule I would keep

Long-term memory is not an append-only feature.

Once an agent can remember across weeks or months, the memory layer needs an active lifecycle:

Text
write with provenancevalidate against evidencesupersede changed factsreinforce useful memoriesreduce influence when usefulness fadesarchive before ordinary deletionpurge when policy or the user requires itcompact duplicates in the background

The subtle part is keeping those operations separate.

A superseded fact is not the same thing as an unused observation. An unused observation is not the same thing as data a user asked you to erase. And a frequently retrieved memory is not automatically a good memory.

Retrieval decides what looks relevant. Garbage collection decides what still deserves a vote.

That is the memory system I want running behind a production agent: not one that remembers everything forever, but one that can explain why a memory is current, why it became historical, and why some things are gone.

References

KEEP READING

Related engineering notes