Long-Term User Memory for a Personalized LLM Assistant
System DesignModel answerLast updated
Design a low-latency, scalable memory layer that lets an LLM assistant remember user facts, retrieve the relevant ones per turn, resolve conflicts, and honor deletion requests.
You are building a long-term memory layer for a conversational assistant powered by an LLM. Users casually reveal durable details over time, such as "I like dark mode" or "my dog is called Rex". On later turns, possibly weeks afterward, the assistant should use those details to give more relevant answers.
Assumptions
- Millions of users, with many concurrent conversations.
- Memory lookup on the response path must finish in under 100 ms.
- Reads far outnumber writes, and writes may become visible after a short delay.
Questions to address
- Storage and modeling. How are facts extracted from conversations, stored, and updated? What schema would you use, and how do you weigh structured records against free-form text?
- Retrieval. How do you fetch only the handful of memories relevant to the current message, without scanning a user's whole history?
- Contradictions. A user once said "I'm vegetarian" and later says "I had steak for dinner." How should the system react to conflicting information?
- Scale and lifecycle. How do you keep per-user history from growing without limit? How do you support privacy obligations such as full deletion on request without hurting performance?
Expected deliverables
- An architecture covering your storage choices (vector database, key-value cache, relational store, etc.).
- The end-to-end flow from the user's message to the final LLM reply, including where memories are injected.
- A method for filtering and ranking candidate memories so the prompt stays within a tight token budget.
Include rough capacity estimates and call out the trade-offs you are making.
Hints
Hint 1
Notice that every lookup is scoped to a single user. How does that change what kind of vector search you actually need compared with searching across all stored facts?
Hint 2
Separate stable traits (diet, preferred theme) from one-off events (what someone ate last night). They deserve different storage and different update rules, and an event is evidence about a trait rather than an overwrite of it.
Hint 3
Split the system into a fast synchronous read path and an asynchronous write path. Ask what happens if memory lookup is slow or down, and how you would make deletion propagate to every derived copy (vector index, cache, backups).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and estimates
Functional: extract durable facts, recall relevant ones each turn, and let users view, edit and delete them. Non-functional: p99 retrieval under 100 ms; writes eventually consistent (seconds to minutes); deletion must be reliable and verifiable.
Rough numbers (state assumptions aloud)
- 10M monthly users, 2M daily, about 20 turns each, so about 40M turns/day, roughly 460 QPS average and about 2.5K QPS at peak.
- Extraction yields perhaps 0.2 facts per turn, so about 8M new facts/day.
- About 200 active facts per user on average, capped near 1,000, giving about 2B facts total.
- A 384-dim int8 embedding is about 400 B, so about 1 TB of vectors plus metadata.
Key insight: retrieval is always per user. We never need global nearest-neighbor search over 2B vectors, only a filtered search over a few hundred. That makes partitioning by user_id the central design decision, and it keeps latency low.
2. Data model: hybrid
Source of truth: a relational or document store sharded by user_id.
memory(user_id, memory_id, type {profile, preference, fact, episodic},
slot_key NULL, -- "diet", "ui.theme", "pet.dog.name"
value_text, confidence, source_turn_id,
created_at, last_confirmed_at, last_accessed_at, access_count,
status {active, superseded, deleted}, superseded_by,
sensitivity {normal, pii, special}, ttl_at)
Vector index (pgvector, Qdrant or a managed search service): (memory_id, user_id, embedding), filtered or partitioned by user. It is derived data and can be rebuilt from the source of truth.
Hot cache (Redis): a per-user "core profile" of the top ~20 high-confidence items, loaded at session start and injected every turn without search.
Structured vs unstructured trade-off
- Slots (
diet=vegetarian) give deterministic updates, cheap conflict handling and exact lookups, but need an ontology. - Free text ("training for an October marathon") covers the long tail but is harder to reconcile.
- Use both: the extractor assigns a slot when one fits and otherwise stores text.
3. Request flow
Read path (synchronous, about 100 ms budget)
- Load the core profile from Redis (~2 ms).
- Embed the query with a small model (~10 ms). Optionally rewrite it with the last 2-3 turns so follow-ups like "what should I cook?" carry context.
- Run user-filtered ANN (
user_id = X AND status = active), top 50 (~10-15 ms). Brute force over a few hundred vectors is equally fast. - Hydrate metadata (~5 ms).
- Rank, dedupe and resolve conflicts (~20-30 ms).
- Pack into a 300-500 token block with dates, and instruct the LLM to use memories only when relevant and not to recite them unprompted.
- Degrade gracefully: on timeout, fall back to the core profile only. Memory must never block a reply.
Write path (asynchronous)
- Publish the turn or session to a queue.
- An extraction worker (LLM or small fine-tuned model) emits candidates
{text, slot_key, type, confidence, sensitivity}. Keep a high bar: durable, first-person, user-stated facts only. Skip hypotheticals and facts about third parties. - Reconcile against the same-slot memory plus the top-k similar memories, and decide ADD, UPDATE (supersede), MERGE or NOOP (refresh
last_confirmed_at). - Write to the DB first, then update the vector index through an outbox or CDC so the stores converge. Invalidate the cached profile.
Explicit commands ("remember this", "forget that") use a synchronous fast path so the effect is immediate.
4. Filtering and ranking
score = w1*cos_sim + w2*rerank + w3*confidence
+ w4*recency_decay(last_confirmed_at) + w5*log(1+access_count)
- sensitivity_penalty
- Start with hand-tuned weights, then learn them from signals such as whether the model used the memory or the user corrected it.
- Apply a similarity threshold: injecting nothing beats injecting noise.
- Dedupe by
slot_key, keeping the winner. - Optionally rerank the top 50 with a cross-encoder, then use MMR to avoid near-duplicates.
- Gate sensitive data: do not surface health or other special-category facts unless the query is on that topic.
- Pack by score until the token budget is full.
5. Contradictions
Distinguish traits from events. "I'm vegetarian" is a profile slot. "I had steak tonight" is an episodic event and is evidence against the trait, not an automatic overwrite.
- Explicit restatement ("I'm not vegetarian anymore"): supersede the old value, keep it as history (
superseded) for audit and undo. - Indirect contradiction: lower the trait's confidence and set a conflict flag. At read time, if the slot is relevant, inject both items with dates so the LLM can hedge or ask a clarifying question.
- Read-time tie-break: prefer the latest confirmation weighted by confidence. Recency usually wins, while repeated confirmations resist one-off noise.
6. Lifecycle, scale and privacy
Bounding growth
- Tier the data: raw transcripts with short retention, episodic memories with TTL or decay, and durable profile facts kept long-term.
- A nightly consolidation job merges duplicates, summarizes old episodes into facts and evicts low-score, rarely accessed items.
- Enforce a per-user cap (about 1,000 active items) with score-based eviction.
Deletion
- User-scoped partitioning makes erasure cheap: delete by
user_idacross the DB, vector index, cache and any derived summaries. - Use a tombstone immediately (filter
status != deletedon reads) so the memory stops being used at once, then hard-delete asynchronously with a tracked job. - Cover backups through retention expiry or crypto-shredding with per-user encryption keys.
- Do not train shared models on raw memories, or ensure they are excluded on opt-out.
- Give users a UI to view, edit and delete, and encrypt PII at rest.
Scaling
- Shard by
user_id. The read path is stateless and horizontally scalable. - Cache embeddings of recent queries, and batch embedding calls.
- Choose a vector store with a per-user filter, or per-user partitions to avoid cross-tenant scans.
7. Trade-offs and common mistakes
- Mistake: global ANN over all users. It is slow, costly and a privacy risk.
- Mistake: extracting synchronously on the response path, which blows the latency budget.
- Mistake: overwriting traits on any contradictory event, so one meal erases a diet.
- Mistake: injecting every memory. It wastes tokens, adds noise and can leak sensitive data.
- Mistake: forgetting that deletion must reach the vector index, cache and backups.
- Trade-off: an LLM-based extractor and reconciler gives better quality but costs more and adds latency, which is acceptable off the critical path. Eventual consistency of writes is a reasonable price for a fast read path.
- Evaluation: measure retrieval recall@k on labeled conversations, extraction precision (wrong memories are worse than missing ones), p99 latency, and online signals such as user corrections and thumbs-up rates.