How to Design an Agent Memory System: From RAG Foundations to Layered Abstraction
A practical design guide for agent memory systems: clarify goals and boundaries, treat retrieval augmentation as the foundation, map requirements to a five-layer abstraction, implement ingestion and recall pipelines, evaluate by prioritized dimensions, and avoid common pitfalls.
1. Start with Why Memory Is Needed, Then Discuss Implementation
Most memory system proposals fail not because of algorithms, but because requirements were never clarified. Before implementation, stakeholders should answer at least two high-level questions:
- What goal does memory serve? Is it context reasoning during long-running tasks (maintaining task state across turns and sessions), personal preferences and style adaptation (keeping output consistently aligned with an individual’s habits), or both with different priorities?
- Where are the boundaries of memory? What data can be collected, how long can it be stored, who can read it, and how can it be withdrawn? A memory system with unclear boundaries becomes riskier the “smarter” it gets.
These two questions determine all subsequent trade-offs. Different goals lead to completely different write granularity and recall strategies: task-state memory emphasizes timeliness and structured state, while preference memory emphasizes long-term stability and low noise.
2. Core Judgment: Retrieval Augmentation Remains the Foundation
A counterintuitive but important conclusion: today’s “AI memory” is not a standalone category. It is closer to a subset of context engineering (Harness Engineering), and its implementation principles still revolve around retrieval-augmented generation. This approach includes both vector and non-vector methods: the former relies on semantic similarity, while the latter relies on keywords, structured fields, graph relationships, and rule-based filtering. The two are not substitutes; they are complementary.
At the same time, it must be acknowledged that no current solution leads comprehensively across all evaluation dimensions. For different user groups and scenarios, a memory system does not need top scores across every dimension. Doing two or three key dimensions well enough is already valuable. This leads directly to a design principle: choose dimensions first, then select technology.
3. Map Three Basic Questions to Engineering Layers
The abstract problems that a memory system must solve can be mapped to three groups of engineering problems:
| Abstract question | Engineering meaning | Corresponding layer |
|---|---|---|
| Who the agent is and what it needs to do | Identity, goals, task state | State and profile layer |
| Where data comes from and which parts are noise | Collection, cleaning, credibility | Collection and governance layer |
| How memory is generated and where it is stored | Extraction, writing, distribution | Writing and storage layer |
Based on this, a stable five-layer abstraction can be defined:
- Collection layer: Unified access to multi-channel conversations, documents, and tool-call logs, with unified timestamps and source identifiers.
- Governance layer: Deduplication, correction, privacy redaction, credibility grading, and expiration/eviction.
- Storage layer: Structured storage for state and metadata, vector indexes for semantic representations, object storage for raw long text, and graph structures for entity relationships when necessary.
- Retrieval layer: Hybrid recall + reranking + context budget trimming.
- Generation and feedback layer: Inject recalled content into prompts and feed user feedback back as new memory signals.
The key value of layering is that any layer can be replaced without affecting the others. Changing the embedding model today or the reranking strategy tomorrow should not trigger an architecture rewrite.
4. Write Path: From Raw Conversation to Usable Memory
Writing is the most underestimated part. Putting raw corpora directly into storage almost inevitably causes noise inflation. A four-step pipeline is recommended:
def ingest(raw_message, user_id):# 1. Normalize: unify time, source, and session identifiersitem = normalize(raw_message)# 2. Redact PII and apply compliance filteringitem = redact_pii(item)if not policy_allows(item, user_id):return None# 3. Extract candidate memories (facts / preferences / task state)candidates = extract(item) # structured fields + natural-language snippets# 4. Deduplicate and resolve conflicts: new information supersedes old statefor c in candidates:c.confidence = score(c, item)c.expire_at = ttl_for(c.kind) # preferences long, task state shortupsert_or_supersede(c, user_id)
There are three key points. First, memory must have a type (fact, preference, task state, event), and the type determines its lifecycle. Second, conflicts must be resolved: if a user said last week that they prefer concise answers and this week asks for detailed ones, the system should update the state rather than keep both. Third, confidence and source must be retained; otherwise, it becomes impossible to explain later why the model answered in a certain way.
5. Read Path: Hybrid Recall and Context Budget
The core tension in the read stage is this: too little recall causes forgetting, while too much recall drowns key signals and raises cost. A practical combination strategy is:
- Hybrid retrieval: Vector recall handles semantic approximation, while keyword and structured filtering handle precise constraints (time range, user, project, tags). The two result sets are fused.
- Reranking: Rerank candidates with a cross-encoder or rule-based scoring, and keep only the top few.
- Budget trimming: Set a fixed token budget for memory (for example, 10%–20% of total context), and fill it in order of “relevance × confidence ÷ time decay”.
- Layered injection: Put stable preferences at the system level, task state at the session level, and long documents only as summaries and location information, with secondary retrieval when needed.
def recall(query, user_id, budget=800):dense = vector_search(query, user_id, top_k=50)sparse = structured_filter(query, user_id) # time/tags/projectmerged = fuse(dense, sparse)ranked = rerank(query, merged)[:20]ranked = [m for m in ranked if not expired(m)]return pack_within_budget(ranked, budget) # truncate low-score items if over budget
6. Evaluation: Make Trade-offs by Dimension, Not Pursue Everything
It is recommended to cover at least six dimensions and assign weights according to business priority: recall accuracy, temporal correctness (whether the latest state is used), noise rate, write latency, read latency and token cost, and privacy compliance. The evaluation set should include three types of samples: “must remember”, “must forget”, and “must update”. The latter two are most likely to expose real defects. An evaluation without “must forget” samples is largely ineffective.
7. Common Pitfalls
- Stuffing full long-term conversations into context and mistaking that for memory; this is only caching, not memory.
- Using only vector retrieval without structured filtering and time dimensions, causing outdated information to reappear repeatedly.
- Lacking an eviction mechanism, so storage and retrieval costs deteriorate linearly over time.
- Lacking observability: if you cannot answer which memory a given output referenced, the problem cannot be located.
8. Conclusion
The design order for an Agent memory system should be: clarify goals and boundaries → recognize retrieval augmentation as the foundation → decouple through the five-layer abstraction → make trade-offs across evaluation dimensions → iterate continuously with a feedback loop. If cloud-side support is needed, general-purpose capabilities are usually sufficient: object storage for raw corpora, message queues to decouple the write path, container platforms for retrieval services, and logging, monitoring, and alerting for observability. Only when the architecture remains neutral and replaceable can the memory system evolve together with models and scenarios.
