Personal Assistant That Remembers You
Design a memory layer that recalls each user's preferences and past tasks within 300 ms, keeps users apart and forgets on request.
- Kind
- Case study
- Level
- Core
- View
- Interview prep
- Sections
- 4
- By
- Sourav Banerjee
- Last updated
- 21 Nov 2026
Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.
Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.
Case brief
The case in one line: a daily assistant that remembers each user across weeks, keeps every user's memories apart and adds at most 300 ms at p95 to a turn.
30-Second Cheat Sheet
- The product: an assistant used daily by the same people for months that remembers their name, time zone, last week's asks and the trip they're planning.
- The honesty rule: asked about "the flight you booked last Tuesday", it finds that user's booking, never a plausible invented one.
- The privacy rule: it must never show one person's memories to another.
- The speed rule: memory adds at most 300 ms at p95 to each turn.
- A bigger context window doesn't solve it: the window is rebuilt every turn, starts empty in a new conversation and gets slower and dearer as you stuff it.
- The design: four scopes (thread, session, semantic, episodic), each with its own key, write rule, lifetime and way of going wrong.
- The turn rule: resolve the user from auth → read memory in parallel → assemble a bounded prompt → reply → write after the reply from a queue.
- The tension (source's words): remember enough to feel personal, forget enough to stay fast, correct and private.
1. What the Assistant Has to Remember
What it must do
- Remember each user across weeks:
- The name they prefer.
- Their time zone.
- What they asked last week.
- The trip they're planning.
- Asked about "the flight you booked last Tuesday", find that user's booking rather than invent one.
- Never show one person's memories to another.
It also has to stay fast
- Memory may add at most 300 ms at p95 to each turn.
- Occasional slow store reads count against that limit.
p95 = the 95th percentile: 95 of every 100 measured turns must meet the limit.
Why a bigger context window doesn't solve it
Context window = the text a large language model (LLM) reads on one call.
- It's rebuilt every turn and starts empty in a new conversation, so it remembers nobody on its own.
- Stuffing more history into it makes every turn slower and dearer.
What the design has to do
- Keep the prompt flat as history grows.
- Keep users apart.
- Make deleting a fact remove it everywhere.
Soundbite (source's tension): "Remember enough to feel personal, and forget enough to stay fast, correct and private."
2. Four Scopes, One Turn
Scope = one kind of memory with its own key, write rule, lifetime and way of going wrong.
| Scope | Holds | Key | How it's kept |
|---|---|---|---|
| Thread memory | One live conversation | thread_id |
A checkpointer persists it so a restart can resume |
| Session memory | Short-lived login context, such as "planning the Lisbon trip" | session_id |
Expires after a TTL |
| Semantic memory | Stable facts: time zone, preferred name | (semantic, user_id) |
One stable key per fact |
| Episodic memory | Completed tasks, such as "booked flight to Lisbon" | (episodic, user_id) |
One new record per task |
| Term | Meaning |
|---|---|
| Checkpointer | The component that saves conversation state after each step |
| TTL | Time to live: the period an entry stays valid |
| Namespace | The key prefix that scopes a set of records to one owner |
The core idea as one turn (source figure, as a flow)
user turn → resolve the user from auth → read four memory scopes in parallel → assemble a bounded prompt → reply → write memory from a queue
- Read it as a rule:
- Read memory in parallel, inside the budget.
- Keep the prompt bounded.
- Write after the reply.
- The
user_idthat selects every long-term namespace always comes from the authenticated session, never from the model.
3. Follow One Request Through Memory
Caveat: this trace is illustrative. The source doesn't narrate one.
The setup:
- Three weeks ago the user told the web app "call me Sam."
- Two days ago the assistant booked them a flight to Lisbon.
- Today they open the chat app and ask: "Can you move the flight you booked to Friday?"
The trace:
- Identity.
- The gateway authenticates the chat account.
- The identity service resolves it to the same
user_idas the web account, so both channels share one memory.
- Five reads fan out in parallel.
- Thread checkpoint: empty, because this is a new conversation.
- Session state.
- Every semantic fact for the user, including
preferred_name = Sam. - The episode digest.
- A vector search over that user's episodes. It embeds the question and returns "booked flight to Lisbon."
- Assemble and answer.
- The context builder puts those pieces into a fixed-order prompt.
- The model replies to Sam about the Lisbon flight and calls the booking tool.
- Write after the reply.
- After the reply streams, the turn is checkpointed by
thread_id. - The queue receives the writes: a new episode for the changed booking.
- "Move it to Friday" is a one-off task detail, so no new semantic fact is stored.
- After the reply streams, the turn is checkpointed by
Two failure paths
- Episode search misses its timeout → the assistant answers without it and says it couldn't find the booking instead of guessing.
- The identity service can't resolve a user → no memory is read at all.
Separately
- The user can open a settings page that lists the stored rows and erase any of them.
4. What You Need to Design
The prompt (verbatim from the source)
"Design the memory layer for a personal assistant used daily by the same users over months. It needs to hold a live conversation, recall stable preferences from weeks ago, remember what tasks it did recently, and never mix up two users' data. Keep p95 added latency from memory under 300ms."
Your job
- Choose the scopes and their keys.
- Bound both what the model sees and what the stores keep.
- Find the right memory inside the budget.
- Make isolation and deletion hold.
- Show how you'd prove recall.
- Then defend the design against follow-ups and a cost pivot.
The four source cases
| Source case | What it contributes here |
|---|---|
| Mock design: "Real-time personal assistant that remembers you across weeks" | The prompt, the 8-point scoring rubric and the 7-point strong answer (walkthrough steps 5 to 7; deep dives on search, latency and isolation; the rubric in the full casebook's Practice) |
| Memory and state interview tutorial, sections 1 to 5 | Scopes, the memory taxonomy, gotchas and trade-offs (steps 5 to 8 and the deep dives) |
| Notes on agent state and memory, and a supervisor-to-deep-agent case study | Three scopes of state, per-user isolation and a real 30-day thread-retention decision (steps 2 and 5, isolation deep dive) |
| Cost and latency notes | The cost pivot (cost deep dive and its drill in the full casebook) |
Caveat on the numbers
- The underlying source is short. Section 6 of the memory tutorial gives a prompt, a rubric and seven bullets, about 25 lines in all.
- No diagram, no sizing and no cost.
- Everything else, including every sizing and latency figure, is a worked assumption for the whiteboard, not a measurement.
Who it's for
- Engineers preparing for Forward Deployed, solutions or applied-AI engineering interviews.
- Especially a round on assistants, copilots or agents that must remember users over time.
What it assumes you know
- LLM context windows
- Key-value stores
- Vector search
- Basic latency budgeting
By the end you should be able to
- Explain the design end to end, starting from the four scopes and their keys.
- Answer follow-ups on:
- The read budget
- Write rules
- Pruning
- Index search
- Isolation
- Measuring recall
- Cost
How to use it
- Work through the walkthrough in order.
- Score your own answer against the rubric in the full casebook (Practice).
- Rehearse the 45-minute plan aloud with a timer (full casebook).
- Reread Quick review and the level calibration (full casebook) the night before.
Quick Recall: Lines to Say in the Interview
- "Memory adds at most 300 milliseconds at p95, and slow store reads count against it."
- "A bigger context window remembers nobody: it starts empty every conversation."
- "Four scopes, four keys: thread_id, session_id, and two user_id namespaces."
- "Facts get one stable key; tasks get one new record each."
- "Resolve, read in parallel, assemble, reply, then write from a queue."
- "user_id comes from the authenticated session, never from the model."
- "If episode search times out, I say I couldn't find it rather than guess."
- "No identity, no memory read."
Design walkthrough
The goal: a memory layer with four scoped stores, parallel reads inside 300 ms at p95, writes after the reply,
user_idfrom auth and a harness that proves recall.
30-Second Cheat Sheet
- Clarify first: "remembers you" hides four promises. Settle that the 300 ms budget covers reads, and writes run after the reply.
- Testable requirements: recall a fact 20 turns later and across conversations, zero cross-user reads, flat prompt tokens, deletion everywhere.
- Size it aloud: 1M users × 30 turns → ≈ 1,050 turns/s at peak, ≈ 2,100 long-term reads/s, ≤ 100M episodes, ≈ 400 GB of vectors.
- Architecture: resolve → read → assemble → reply → write. Three boundaries: identity service, parallel fan-out, queue.
- Four scopes, four keys:
thread_id,session_id,(semantic, user_id),(episodic, user_id). - Bound the prompt: summarise past ~15 turns plus recent raw turns, in a fixed order, stable prefix first so it caches.
- Write rule pair: a fact that can change gets a stable key; a fresh event gets a fresh key. Keep one prior version.
- Measure recall, not fluency: planted-fact recall, false-memory rate, rows per key = 1, Recall@k, cross-user tests at zero.
1. Clarify What "Remembers You" Means
- Ask what the user expects remembered before drawing a box.
- "Remembers you" hides four promises:
- Hold the conversation.
- Keep preferences for good.
- Recall what it did last week.
- Keep one user's life out of another's view.
- Each promise needs a different store with a different lifetime, so each clarifying question settles a design decision.
| Question | Why it changes the design |
|---|---|
| What must it recall weeks later: preferences, past tasks, or both? | Decides whether episodic memory exists at all |
| Which channels does one user reach it through? | Web, phone and chat must resolve to one user_id before memory can be shared |
| Can the user see, correct and erase what it remembers? | Decides whether memory is a user-facing product surface or a hidden cache |
| What must never be stored? | Health, payment or third-party data may be barred from long-term memory |
| Where must the data live? | Residency rules decide where each store physically runs |
| Is "300ms" added latency on read, write, or both? | Decides which work may run after the reply |
The last question decides the architecture's shape
- If the interviewer won't answer it, answer it yourself:
- The 300 ms budget covers reads on the critical path.
- Writes run after the reply is sent.
- That assumption lets fact extraction, embedding, summarising and pruning leave the reply path (step 4).
- Saving the turn to the thread checkpoint is a separate, durable step. Only the promotion of that turn into long-term memory is deferred.
Soundbite: "I'll take the 300 ms as read latency on the critical path; writes run after the reply."
2. State Requirements as Testable Constraints
- A requirement that can't fail a test is a preference.
- "Remembers preferences" is a preference.
- "Recalls a preference stated 30 days ago in a new conversation" is a constraint: a test can plant it, open a new conversation later and check the answer.
Functional requirements (the four promises, plus correction and restart)
| # | Requirement |
|---|---|
| F1 | Hold a live multi-turn conversation, resolving "it" and "that one" to earlier turns |
| F2 | Recall stable preferences (time zone, preferred name, dietary rule) in any new conversation |
| F3 | Recall recently completed tasks ("the flight I booked last Tuesday") |
| F4 | Update a preference when the user restates it, without duplicating it |
| F5 | Show the user what is remembered, and forget on request |
| F6 | Survive a server restart mid-conversation |
Non-functional constraints
- Four come from the source prompt or its take-home (marked source).
- Durability, freshness and deletion are added by this case so each promise has a test.
| Constraint | Stated so it can be tested |
|---|---|
| Latency | Memory adds under 300ms at p95 to each turn (source) |
| Isolation | Zero cross-user reads; user_id comes from auth, never from the model (source) |
| Recall | A fact planted early is recalled 20 turns later, measured on an eval set (source take-home) |
| Bounded growth | Prompt tokens per turn flat after the summary threshold; episodes capped per user (source) |
| Durability | A completed turn and a saved fact survive a process restart |
| Freshness | A fact written in one conversation is readable from a new conversation within seconds |
| Deletion | "Forget X" and account deletion propagate to every store, index and cache |
Every requirement gets an owner
- So a failed test points at a component.
| Requirement | Primary component(s) |
|---|---|
| F1, F6 | Thread checkpointer, context builder |
| F2, F4 | Semantic store with stable keys, memory writer |
| F3 | Episodic store, vector index, episode digest |
| F5 | Memory API behind the user's settings page, deletion job |
| Latency | Parallel read fan-out, vector index, async write queue |
| Isolation | Identity service, namespaces keyed by user_id |
Two rows shape later decisions
- F5 makes memory a user-facing product surface with its own API and settings page, not a hidden cache.
- That's why the deletion job in step 4 has to reach every store.
- Freshness only promises "within seconds" across conversations.
- That's what allows long-term writes to queue.
3. Size the Memory Before the Model
- Say the arithmetic aloud: it shows why the design needs an index and a pruning policy.
- Every number is an assumption for the whiteboard. The method is what gets scored.
| Step | Assumption | Result |
|---|---|---|
| Daily active users | 1M | Starting assumption |
| Turns per user per day | 30 | 30M turns a day |
| Average turn rate | 30M ÷ 86,400 s | ≈ 350 turns/s |
| Peak | 3× average | ≈ 1,050 turns/s |
| Memory reads per turn | 1 semantic fetch + 1 episodic search | ≈ 2,100 long-term reads/s at peak |
| Completed tasks per user per day | 5 | 5M episode writes a day |
| Episodes kept per user | 100 (source cap) | ≤ 100M live episodes |
| Stable facts per user | 50 | ≈ 50M semantic rows |
| Vector size | 1,024 dims × 4 bytes | ≈ 4 KB per episode vector, ≈ 400 GB at the cap |
| Summary calls | One per ~15 turns (source threshold) | 2 per user a day, ≈ 2M extra model calls, about 7% on top of 30M |
Follow the chain
- 1M users × 30 turns = 30M turns a day.
- ÷ 86,400 s ≈ 350 turns/s; a 3× peak ≈ 1,050.
- One semantic fetch + one episodic search per turn → peak long-term reads ≈ 2,100/s.
- The full fan-out is five store reads a turn (adds thread checkpoint, session state and digest) → about 5,250/s at peak (1,050 × 5). Still modest throughput.
- 5 tasks/user/day = 5M episode writes a day.
- Cap of 100 episodes/user → at most 100M live.
- At five tasks a day, a user hits the cap in about 20 days (100 ÷ 5).
- So anything older than about three weeks is recalled only through the digest.
- 1,024 dims × 4 bytes ≈ 4 KB a vector → about 400 GB for the capped vectors.
- Raw vectors only: index structures, metadata and replicas add to it.
- Summarising every ~15 turns at 30 turns/day = two folds per user per day → 2M extra model calls, about 7% on top of the 30M turns.
Three conclusions
- The episode cap bounds the index. Without it, 5M writes a day grow without limit, and each user's search runs over an ever-larger set.
- The read rate is modest. About 2,100 reads a second is easy throughput, so latency depends on the index, not on raw capacity.
- The summary calls are a real line on the bill. The ~15-turn threshold is a cost lever as well as a quality setting.
4. Draw the Architecture End to End
- Organising rule: resolve → read → assemble → reply → write.
- Identity first, because every key depends on it.
- Reads fan out in parallel inside the budget.
- Writes happen after the reply, off the critical path.
- The source draws the system as two diagrams: a request path and an async write path.
Request path (source figure, as a flow)
web / phone / chat client → gateway → identity service derives user_id from the auth session → five parallel reads (thread checkpoint, session state, semantic facts, episode search, episode digest) → context builder → assistant with calendar, mail and booking tools → stream reply → checkpoint turn by thread_id → enqueue async writes
- A client reaches the gateway.
- The identity service derives
user_idfrom the auth session. Nothing below it can choose a different user. - Five reads run at once, each keyed by its own namespace:
- Thread checkpoint by
thread_id. - Session state by
session_id. - Semantic facts and the episode digest by
user_id. - An episode search filtered to that user.
- Thread checkpoint by
- The context builder places them in a fixed order with the new message: system prompt, facts, digest, top-k episodes, summary, recent turns, the message.
- The assistant answers and may call calendar, mail or booking tools; the reply streams.
- Only then is the turn checkpointed and the long-term writes enqueued.
Async write path (source figure, as a flow)
queue → memory writer (extract → policy filter → upsert by stable key, one prior version kept) | episode writer (append once per task → embed → index) | summariser (after ~15 turns → running summary) | pruner (newest 100 per user, older → rolling digest) | forget / account delete → deletion job across every store and index
- Memory writer: candidate facts → policy filter → stable-key upserts, previous value kept one version back.
- Episode writer: appends one record per completed task, then embeds and indexes it.
- Summariser: folds older turns into the running summary after about 15 turns.
- Pruner: enforces the 100-episode cap and feeds the digest.
- Deletion job: a forget or account-delete request removes data from every store and index.
The control plane around both paths
- The source asks you to version:
- The category-specific memory policy.
- Retention and caps per scope.
- The ~15-turn summary threshold.
- The 100-per-user episode cap.
- The session TTL.
- The extraction prompts.
- Residency.
- The evaluation gates.
- Each of those changes what the assistant remembers, so each is versioned and gated by the evaluation suite in step 8.
- Monitor read latency, hits and writes by category without logging memory text: the text is the private data the design protects.
The same flow in three lanes (source's second drawing)
| Lane | What's in it | Budget |
|---|---|---|
| Control plane | Memory policy (allowed categories), retention and caps (15-turn summary, 100 episodes, session TTL), versioned extraction prompt | Changes only by release |
| Request path | Client → gateway → identity service → parallel read of five stores → context builder → assistant model with tools | The only lane inside the 300 ms added |
| Async write path | Write queue → memory writer, episode writer, summariser, pruner, deletion job | After the reply |
The fourteen components, in request order
| # | Component | Responsibility | Fails how |
|---|---|---|---|
| 01 | Gateway | Auth, rate limit, streams the reply | Closed on auth failure |
| 02 | Identity service | Resolves one user_id across every channel |
Closed: no identity, no memory read |
| 03 | Thread checkpoint | Conversation state per thread_id, saved after each step |
Replicated; a restart resumes from the last step |
| 04 | Session state | Short-lived context per login session, with a TTL | Degrades: session context lost, conversation continues |
| 05 | Semantic store | Stable facts under stable keys, one prior version kept | Degrades: answer without preferences, never invent one |
| 06 | Episodic store + index | One record per completed task, vector-searchable, filtered by user | Degrades: skip recall past a timeout, say so if asked |
| 07 | Episode digest | Rolling summary of episodes older than the newest 100 | Degrades: answer from recent episodes only |
| 08 | Context builder | Assembles the prompt in a fixed order within a token budget | Degrades: fewer episodes, same order |
| 09 | Assistant model + tools | Answers and acts | Fails over to a fallback model |
| 10 | Memory writer | Extracts candidate facts, applies policy, upserts by key | Retries from the queue; a lost write is re-extracted next turn |
| 11 | Episode writer | Appends, embeds and indexes a finished task | Retries from the queue |
| 12 | Summariser | Folds old turns into the running summary | Degrades: window trimming until it recovers |
| 13 | Pruner | Enforces the 100-episode cap, feeds the digest | Degrades: index grows for a while, alert fires |
| 14 | Deletion job | Propagates "forget" and account deletion everywhere | Closed: retried until every store confirms |
Three patterns in the "fails how" column
- Fail closed: gateway, identity service, deletion job.
- Without a trusted
user_id, no namespace is safe to read. - A deletion that stops early leaves data the user asked to remove.
- Without a trusted
- Degrade: most read-side components. The assistant answers with less memory but never invents what it couldn't read.
- Retry from the queue: the writers.
- The source adds that a lost fact write is re-extracted on the next turn.
- That recovery depends on the user speaking again, so keep the source turn on the queue as well, so a retry doesn't need a new turn.
Point at three boundaries while the diagram is up
- The isolation boundary is the identity service. Every namespace below it carries a
user_idit supplied. - The latency boundary is the parallel fan-out. The slowest store sets the turn's added latency.
- The write boundary is the queue. Nothing after it can slow a reply.
5. Separate Four Scopes and Give Each Its Own Key
- Each kind of memory answers a different question:
- A
thread_idanswers "which conversation." - A
user_idnamespace answers "which person."
- A
- Only the first → it forgets everyone between conversations.
- Confuse them → it leaks memory across users.
| Scope | Holds | Key | Write rule | Read rule | Lifetime |
|---|---|---|---|---|---|
| Thread (short-term) | The live conversation | thread_id |
Checkpoint after each step | Summary plus recent turns | Retention policy, for example 30 days |
| Session | Login-session context, such as "planning the Lisbon trip" | session_id |
Overwrite | Get by key | TTL, sliding or fixed |
| Semantic (long-term) | Stable facts: time zone, preferred name | (semantic, user_id) + stable key |
Overwrite in place | Get all keys for the user | Until changed or erased |
| Episodic (long-term) | Completed tasks: "booked flight to Lisbon" | (episodic, user_id) + fresh key |
Append one per task | Vector search, top-k | Newest 100, older folded into a digest |
Read the write and read rules as pairs
- Thread: checkpoints every step, but sends the model only a summary and the recent turns.
- Session: overwritten and read by key.
- Semantic: overwritten in place and read all at once, because there are only about 50 per user.
- Episodic: appended and searched, because there can be up to 100 and only a few matter for any question.
"Short-term" describes scope, not lifetime
- A durable checkpointer keeps thread history on disk across restarts. That's the point: F6 requires surviving a restart mid-conversation.
- One source case study records a real deployment that stored thread checkpoints in a table with 30-day retention.
- Chosen so conversations survived an endpoint restart and stayed auditable.
- Thirty days is that deployment's decision, not a default for every customer.
Procedural memory: the fifth kind
Procedural memory = instructions that change the assistant's own behaviour.
- Keep it out of scope for a personal assistant unless asked.
- If it appears, gate every change behind human approval.
- Keep that approval outside the model's reach: an approval passed as a tool argument lets the model approve itself.
Keep enterprise knowledge out of memory entirely
- A stale preference fails as mildly wrong personalisation.
- An outdated policy fails as a wrong answer.
- They refresh on different cadences, so they live in different stores.
- Company documents belong in a retrieval system with its own governance.
Soundbite: "thread_id answers which conversation; user_id answers which person. Confuse them and you leak."
6. Bound What the Model Sees on Every Turn
- Store every turn; send the model only what this turn needs.
- Full replay makes tokens and latency grow linearly with turns.
- The source answer summarises once the buffer crosses about 15 turns, so cost stays flat on long chats.
| Option | Costs | Buys | Choose when |
|---|---|---|---|
| Full history replay | Tokens and latency grow with every turn | No information loss | Short conversations only |
| Sliding window | Anything outside the window is gone | Flat, bounded cost | Only the last few turns matter |
| Summarisation | One extra model call per fold, and it's lossy | Bounded cost and a record of older turns | Long conversations where old facts still matter |
Pick summarisation with a window of raw recent turns
- Illustration (source's): at turn 40 of a long chat, the model sees the running summary of older turns plus the latest few raw turns.
- The prompt is roughly the size it was at turn 16, not two and a half times larger.
Volunteer the failure mode
- The summariser can drop something it judged unimportant that matters later.
- The semantic store is the safety net: a preference already extracted into a stable key, such as
preferred_name, no longer depends on the summary keeping it.
Two gotchas that separate a practitioner from a reader
- Trimming the prompt doesn't trim the stored checkpoint. Only an explicit removal or a retention policy shrinks storage.
- A running-summary field with no merge rule can be reset by a stray input on the next call, so the summary appears never to accumulate.
- Pass only the fields meant to overwrite, and give the summary an explicit merge.
Fixed assembly order
system prompt → semantic facts → episode digest → top-k episodes → running summary → recent turns → new message
- Stable parts go first, so a provider's prefix cache can reuse them across turns.
Prefix cache = the provider's reuse of an identical prompt opening, which cuts input cost and time to first token. Reuse stops at the first token that differs.
- What caches: the system prompt, the user's facts and the digest, while the same user keeps talking inside the cache lifetime.
- Five minutes by default on Anthropic's API, refreshed on each hit.
- What doesn't: everything from the top-k episodes onward changes with the question and is billed at full input price every turn.
- Minimum prefix length: providers skip caching below it.
- 1,024 tokens on Claude Sonnet 5, 4,096 on Claude Haiku 4.5.
- So a short system prompt may not cache at all.
- Any cache you add yourself must include the user's scope in its key.
7. Write Facts in Place and Events by Appending
- A fact's key comes from what the fact is; an event's key comes from nothing at all.
- Restating "call me Sam" updates the single
preferred_namerow, not a second one. - A completed task is a new event every time, so a fresh key per write is correct for episodes.
- Restating "call me Sam" updates the single
- The rule comes as a pair:
- If a fact can change, its key must be stable.
- If it's a fresh event, a fresh key is correct.
- Mix them up (a random key per fact) → semantic memory quietly turns into a pile of duplicate facts, because nothing ever overwrites.
Handle a conflict explicitly
- The source answer overwrites the existing key and keeps the previous value one version back.
- That makes "you told me X last month, now Y" answerable instead of silently lost.
- Store a timestamp and the source turn with each value, so the assistant can say when it learned something.
- When a new statement contradicts an old one and it matters for the task, mention the change or ask.
Name what isn't persisted
- The source keeps raw intermediate tool outputs and one-off task details in short-term or episodic memory only.
- They're promoted to semantic memory only when the user restates them as a standing preference.
| User says | Stored as |
|---|---|
| "Book me a window seat this time" | An episode |
| "I always want a window seat" | A fact |
Decide who chooses what to write
| Writer | Strength | Weakness |
|---|---|---|
| Hard-coded rule | Predictable | Misses facts it didn't anticipate |
| Model-driven writer (in the style of MemGPT's self-editing memory tools) | Catches more | Can misjudge what is durable |
| Model extractor behind a policy filter (the choice) | Model proposes candidates; policy decides which categories may be stored at all | Needs the policy kept current |
MemGPT-style memory = the model edits its own memory through function calls.
- The policy filter is where barred categories from step 1 (health or payment data) are enforced.
- Run the extractor on the write queue, never on the reply path.
Two additions from this casebook
- Stable task identity per completed task → a retried episode write doesn't append the same booking twice.
- Accept candidate facts only from the user's own turns, never from tool output such as an email or web page.
- Text the assistant read isn't something the user said.
Soundbite: "If a fact can change, its key is stable. If it's an event, the key is fresh."
8. Measure Recall, Not Fluency
- Measure whether the assistant remembers, not whether it sounds as if it does.
- A fluent answer that invents a preference is worse than one that asks again.
- Few worked examples cover memory-quality evaluation, so building a harness is the strong move in this round.
The harness (from the source's take-home)
- Plant a fact early in a long synthetic conversation.
- Ask for it 20 turns later.
- Score full history, sliding window and summarisation against each other on recall and cost.
- Extend it across conversations for this design: plant in thread A, ask in thread B a simulated week later.
- That tests the semantic store and the queue, not the summary.
| Worry | Metric that answers it |
|---|---|
| Does it recall what it should? | Recall of planted facts, same thread and across threads |
| Does it invent what it never heard? | False-memory rate: answers that assert a fact never stated |
| Did the summary drop something that mattered? | Recall of planted facts after a summary fold |
| Does it duplicate facts? | Rows per stable key per user; should be exactly 1 |
| Is episode search finding the right task? | Recall@k on labelled "which task did I mean" questions |
| Is memory within budget? | Added latency p95 per store and in total |
| Is it isolated? | Cross-user read tests at zero, run before every release |
| Is growth bounded? | Episodes per user at the cap; prompt tokens per turn flat past the threshold |
Recall@k = the share of questions whose intended episode appears in the top k search results.
Each metric targets a mechanism
- Recall after a fold → tests the summariser and the semantic safety net.
- Rows per stable key → catches random-key writes.
- Recall@k → tests the episode index.
- False-memory rate → catches the fluent failure that recall alone misses.
Gate changes on the suite
- Extraction prompt changed → rerun the suite.
- Summary threshold changed → rerun the suite.
- Episode cap changed → rerun the suite.
- Each one changes what the assistant remembers.
Quick Recall: Lines to Say in the Interview
- "'Remembers you' is four promises, and each needs its own store."
- "The 300 ms is read latency on the critical path; writes run after the reply."
- "1,050 turns a second at peak, about 2,100 long-term reads: the index, not capacity, sets latency."
- "At five tasks a day, a user hits the 100-episode cap in about 20 days; older work lives in the digest."
- "The isolation boundary is the identity service, the latency boundary is the fan-out, the write boundary is the queue."
- "Trimming the prompt doesn't trim the checkpoint."
- "Stable parts first, so the prefix caches; the user's scope goes in every cache key."
- "Facts only from the user's own turns, never from an email the assistant read."
- "A fluent invented preference is worse than asking again, so I measure the false-memory rate."
Technical deep dives
What this part covers: the mechanisms behind follow-up questions. Pruning, index search, the 300 ms budget, isolation and deletion, failure modes and the cost pivot.
30-Second Cheat Sheet
- Cap episodes at 100 per user and fold older ones into a rolling digest, never into nothing.
- TTL expiry is a sweep, not a read check, in the LangGraph store: schedule the sweeper or check age on read.
- Index, not scan: fine at 5 facts, slow at 500. Filter by
user_idduring the search, or partition by user. - Critical path ≈ 115 ms (5 + 40 + 60 + 10): the longest chain, not the sum of every row.
user_idfrom auth, never from the model. Leaks → audit namespace derivation first.- Deletion reaches everything: prior versions, episodes, vectors, digest, checkpoints, summaries, caches, plus a deletion marker against queued writes.
- Ten failure modes, most visible in stored state before users complain.
- Cost pivot: storage is cheap; the cost is model calls to write memory and tokens to read it back. Measure, route, bound, cache.
1. Prune Episodes Into a Digest, Not Into Nothing
- Cap episodic memory per user, because nothing else will.
- Every completed task is a fresh append with no natural ceiling.
- A year-long user's row count only climbs; their search slows and gets noisier.
- The source answer keeps the most recent 100 per user and folds older ones into a rolling digest rather than deleting them outright.
What the digest is
- Keeps the gist of older activity at a fixed size.
- "Booked four trips to Lisbon this year" survives even after the four booking episodes are pruned.
- Approximate: it keeps the pattern, not every booking detail.
- Read by key alongside the semantic facts.
- The pruner runs as a background job on the write path, so pruning never costs a reply any latency.
- If it falls behind, the index grows for a while and an alert fires.
Session memory needs the same discipline
- A TTL marks entries for expiry.
- Sliding expiry extends the session on activity.
- Fixed expiry ends it at a set time.
- The gotcha: in the LangGraph store, expiry is enforced by a sweep, not checked on every read. An expired entry can still be returned until the sweeper runs.
| Store (checked by the source in September 2026) | TTL behaviour |
|---|---|
| SqliteStore | Sweep only; expired rows can be returned |
| PostgresStore (default) | Sweep only; expired rows can be returned |
PostgresStore with omit_expired |
Hides expired rows on read |
| InMemoryStore | No TTL at all |
- Fix: schedule the sweeper, or check the entry's age on read if a few seconds of staleness matter.
- Recheck these library details against the version you deploy.
2. Search With an Index, Not a Scan
- Search by relevance, because a scan's cost grows with how much has been stored.
- An unfiltered scan over a namespace is invisible at 5 facts and slow and noisy at 500.
- The source answer puts an embedding index on the semantic and episodic namespaces.
- Recall at 1,000+ saved items becomes a vector query, not a full scan.
- That keeps p95 under 300 ms as history grows.
Why demos pass and pilots fail
- Many simple memory demos skip this: long-term search is an unfiltered scan or a similarity check by the model, with no real embedding index.
- That's the difference between working with 10 memories and working with 10,000.
- It's why a demo can pass while a long-tenure pilot user gets slow answers.
Use each search shape for what it does best
| Worry | Search shape |
|---|---|
| What is this user's time zone? | Get by stable key; no search at all |
| What did I book for them last week? | Vector search on episodes, filtered by user_id, sorted by recency |
| Who is the manager of the person who organised that trip? | Graph memory: triples and a bounded-hop traversal |
| Did they ever mention a peanut allergy? | Keyword or field lookup, because exact recall matters more than similarity |
How the user filter runs matters
- Semantic facts are few (about 50 in the sizing), so fetch them all by key. The index on that namespace matters only if facts grow well past that.
- Search is for episodes, and it must carry the
user_idfilter so it never ranks another user's records. - The post-filter trap:
- A global approximate nearest-neighbour index ranks all 100M episode vectors, then filters to one user's 100.
- It can return fewer than k results, or none, because that user's records rarely reach the global top candidates.
- Fix: partition the index by user, or use an engine that applies the filter during the search.
- Inside one user's slice: at 100 episodes, an exact comparison is about 100 × 1,024 multiply-adds and needs no approximate index.
- The index earns its place across the whole store, not inside one user's capped slice.
- Allergy → exact lookup, because a similar-sounding but wrong result is dangerous.
- Graph memory earns its extraction cost only when answers chain facts never stated together. Mention it; don't build it by default.
Approximate nearest-neighbour (ANN) index = a vector index that trades exactness for speed by searching only likely candidates.
3. Spend the 300 ms Budget Deliberately
- Budget memory like any other dependency: a slow memory read can dominate p95 as easily as a slow retriever.
- Spend the 300 ms on reads in parallel; move every write after the reply.
| Step | p95 assumption | Critical path? |
|---|---|---|
Resolve user_id from the auth session |
5 ms | Yes |
| Embed the query for episode search | 40 ms | Yes, in parallel with key reads |
| Episode vector search, filtered by user, top-k | 60 ms | Yes, after the embedding |
| Semantic facts, digest, session state by key | 15 ms | Yes, in parallel |
| Thread checkpoint load | 20 ms | Yes, in parallel |
| Context assembly | 10 ms | Yes |
| Critical-path total | ≈ 115 ms (5 + 40 + 60 + 10) | Leaves headroom for tail latency |
| Fact extraction, episode embed and index, summary fold, pruning | 1–3 s | No: queued after the reply |
Caveat: the figures are assumptions.
The total is the longest chain, not the sum
- Identity (5 ms) must finish first.
- Embedding (40 ms) → episode search (60 ms) is the slowest branch.
- Key reads (15 ms) and checkpoint load (20 ms) run beside it and finish inside it.
- Context assembly (10 ms) waits for everything.
- → 5 + 40 + 60 + 10 ≈ 115 ms, leaving headroom under 300 ms.
- Adding per-step p95 estimates is a planning exercise, not a measured end-to-end p95. Load-test the combined path with one store slowed down.
Why every write can leave the critical path
- A fact said in this thread is already in the checkpoint, so the long-term write can lag by seconds without anyone noticing.
- The only freshness promise that matters is cross-conversation, and a queue that drains in seconds meets it.
- Watch queue age, so a backlog shows up before users notice a missing preference.
Timeouts
- A timeout on each read.
- Episode search misses its timeout → answer without it and log the miss rather than blowing the budget.
- Identity failure is different: it blocks memory reads entirely.
Soundbite: "About 115 ms on the critical path: the longest chain, not the sum. Then I load-test it with one store slowed."
4. Take user_id From Auth, Never From the Model
- Read the isolation key from the server-side session on every request, because anything the model can set, a prompt can set.
- The source answer:
user_idcomes from the server-side session or auth config, never from a tool-call argument the model could fill in. - Every namespace tuple includes it.
Debugging, both directions
| Bug | Symptom | Usual cause |
|---|---|---|
| Cross-user leak | Two users see each other's memories | A user_id sourced from the wrong place. Audit namespace derivation first. |
| Collapse to per-conversation | Preferences vanish in each new chat | A thread_id used by mistake as the long-term namespace |
Channels must agree on identity
- A web app and a chat bot both need to resolve to the same
user_idat the identity layer. - The memory system doesn't care which channel wrote a fact.
Governance follows from the same design
| Governance ask | Design answer |
|---|---|
| What does the assistant know about me? | Query the namespaces directly and show the rows, not the model's summary of itself |
| Forget that I said X | Delete the semantic key and its prior version; scrub matching episodes, their vectors and the digest; redact the fact from retained thread checkpoints and running summaries, or an old conversation repeats it |
| Delete my account | The deletion job clears checkpoints, session state, facts, episodes, digest, vectors and caches, then confirms |
| How long is each thing kept? | Named per scope: thread retention, session TTL, facts until changed, newest 100 episodes |
| EU data stays in the EU | The residency map pins the user's stores to a region; the index is sharded by user, so it follows |
Two answers worth explaining
- "What does it know about me?" queries the stores, because a model's summary of its own memory can omit or invent entries.
- Residency works because the index is sharded by user: pinning a user's stores moves their vectors with them.
- Sharding is only the precondition. The shard map must place each user's shard in the pinned region, and replicas and backups must stay there too.
One safeguard this casebook adds (not in the source)
- Deletion must stop an already-queued write from recreating a forgotten fact.
- Record a deletion marker per key or per user that writers check before committing.
- Make sure no cache serves data outside the user's pinned region.
5. Name the Failure Modes Before They Do
- Volunteer how the design breaks: a design with no failure modes hasn't been examined.
- The source lists ten.
| Failure | Symptom | Fix |
|---|---|---|
| Random key per write | "Remember X" three times makes three rows | Key facts by what they are |
| Trimmed prompt, untrimmed store | Storage grows while prompts look bounded | Retention policy on checkpoints |
| Summary reset by stray input | The running summary never accumulates | Pass only fields meant to overwrite; add a merge rule |
| Unbounded episodes | A year-long user's search slows and gets noisy | Cap at 100, fold into the digest |
| Scan instead of index | Fine at 5 facts, slow at 500 | Embedding index with a user filter |
user_id from the model |
One user reads another's facts | Identity from auth only |
| Expired session still readable | A read returns an entry past its TTL | Scheduled sweeper, or check age on read |
| Stale preference wins | Assistant uses last month's value | Overwrite with one version kept; ask when a new statement contradicts an old one |
| Extractor over-stores | Transient details become "facts" | Policy filter on categories; promote only restated preferences |
| Memory poisoning | Text from an email or web page is saved as a user preference | Write only from the user's own turns; never from tool output |
Most are visible in stored state before users complain
- That's why the evaluation suite (walkthrough step 8) checks state as well as answers.
| Failure | Where it shows |
|---|---|
| Random keys | More than one row per stable key |
| Untrimmed store | Checkpoint storage rising while prompt tokens stay flat |
| Unbounded episodes | Episodes per user above the cap |
| Scan | Read latency rising with tenure |
Model-supplied user_id |
Only cross-user read tests, so they run before every release |
| Reset summary, stale preference, over-eager extractor | In answers: recall after a fold, conflicting-preference cases, the false-memory rate |
| Memory poisoning | Caught by recording the source turn on every fact and rejecting any candidate not from the user's own turn |
6. Answer the Cost Pivot
- The pivot: "memory made the bill go up; what do you cut?"
- Answer with the cost-drill card.
| Card field | Answer |
|---|---|
| Main cost driver | Input tokens: memory, summary and history re-sent on every turn; then the extra model calls for summarising and extracting |
| Cheapest lever first | Send top-k episodes, not all; fetch facts by key; fold history past ~15 turns; keep the stable prefix first so it caches; run extraction on a small model, in batches, off the reply path |
| Metric that proves it | Input tokens per turn by section (facts, digest, episodes, summary, turns); extraction and summary calls per 1,000 turns; cost per active user per day; recall on the harness |
| Do not | Stuff every memory into every prompt, or extract on every turn with the premium model |
| 60-second line | "Storage is cheap; the cost is the model calls to write memory and the tokens to read it back. Retrieve a few relevant memories, summarise in steps, extract with a small model after the reply, and prove recall held with the harness." |
The first driver explains most surprises
- Input tokens grow with context.
- Teams count the user's question and ignore the system prompt and the hidden history, so the bill rises while traffic stays flat.
- Its fix list reads like this design: trim prompts, compress context, summarise history, cache static prompt parts.
The FDE answer (non-engineer version)
FDE = Forward Deployed Engineer.
- Cost scales with how often memory is written and searched, not with how much is stored.
Four verbs, in order
- Measure tokens per prompt section first, so you know whether facts, digest, episodes, summary or recent turns dominate.
- Route extraction and summarising to a small model.
- Bound episodes, summary length and top-k.
- Cache safely, with the stable prefix first and the user's scope in every key.
- Then rerun the recall harness: a cut that saves tokens by dropping memory the user relied on has moved the cost into wrong answers.
Spoken answer (source's 60-second line): "Storage is cheap; the cost is the model calls to write memory and the tokens to read it back."
7. References
Caveat: the source checked these on 27 September 2026. Library behaviour may have changed since.
| Reference | What it shows |
|---|---|
| LangGraph TTLConfig source | refresh_on_read gives sliding expiry; omit_expired defaults to off; sweeping deletes expired items |
| LangGraph SqliteStore source | get doesn't filter expired rows; sweep_ttl and start_ttl_sweeper delete them |
| LangGraph PostgresStore source | Optional omit_expired read filter; the sweeper must be started explicitly |
| MemGPT: Towards LLMs as Operating Systems | The model edits its own memory through function calls |
Quick Recall: Lines to Say in the Interview
- "Newest 100 episodes per user; older ones fold into a digest, not into nothing."
- "In the LangGraph store, TTL is a sweep, not a read check, so I schedule the sweeper."
- "A global index that filters afterwards can return fewer than k results for one user. Filter during the search."
- "For a peanut allergy I use an exact lookup: a similar-sounding wrong answer is dangerous."
- "About 115 ms on the critical path, and I load-test it with one store slowed."
- "Anything the model can set, a prompt can set, so user_id comes from auth."
- "Forget means the key, its prior version, episodes, vectors, digest, checkpoints and summaries, plus a marker against queued writes."
- "Cost scales with how often memory is written and searched, not how much is stored."
- "Measure, route, bound, cache, then rerun the recall harness."
Quick review
Closing answer: four scopes with four keys, reads in parallel inside 300 ms, writes after the reply,
user_idfrom auth, and a recall harness that proves the assistant remembers the right person's facts and nothing it never heard.
30-Second Cheat Sheet
- Each turn: resolve
user_idfrom auth → read the scopes in parallel → assemble a bounded prompt → reply → write from a queue. - Three boundaries: isolation = identity service, latency = parallel fan-out, write = queue.
- Four scopes: thread, session, semantic, episodic, each with its own key and write rule.
- Budget: 300 ms p95 is for reads; critical path ≈ 115 ms.
- Writes: key facts by what they are, append events, keep one prior version.
- Ten failure modes to volunteer, from random keys to memory poisoning.
- Measure recall and false memories, not fluency. The rubric has eight lines.
- Memory cost is writes and read-back tokens: retrieve a few, summarise in steps, extract small and late.
1. The Architecture and the Four Scopes
resolve user_id from auth → read the scopes in parallel → assemble a bounded prompt → reply → write from a queue
- Isolation boundary: the identity service.
- Latency boundary: the parallel fan-out.
- Write boundary: the queue.
| Scope | Key | Write rule | Read rule | Lifetime |
|---|---|---|---|---|
| Thread | thread_id |
Checkpoint after each step | Summary plus recent turns | Retention such as 30 days |
| Session | session_id |
Overwrite | Get by key | TTL with a scheduled sweeper |
| Semantic | (semantic, user_id) + a stable key |
Overwrite in place with one prior version | Fetch all (~50) by key | Until changed or erased |
| Episodic | (episodic, user_id) + a fresh key |
Append per task | Vector search filtered by user | Newest 100, then a digest |
- Procedural memory needs human approval outside the model's reach.
- Enterprise knowledge stays in retrieval, not memory.
2. Numbers and Decisions
| Topic | What to say |
|---|---|
| Clarify | The four promises; settle that the 300 ms p95 budget is for reads |
| Requirements | Testable: recall 20 turns later and across conversations, zero cross-user reads, flat prompt size, deletion everywhere |
| Context | Store every turn; send a running summary past ~15 turns plus recent turns, in a fixed order, stable prefix first. Trimming the prompt doesn't trim storage. |
| Writes | Key facts by what they are, append events, keep one prior version, persist transient details only as episodes, extract with a model behind a policy filter on the queue |
| Reads | About 115 ms on the critical path (5 + 40 + 60 + 10), timeouts on every read, answer without episodes when search times out |
| Governance | Show stored rows; delete everywhere including prior versions, digest, vectors and caches; name retention per scope; pin residency per user |
Sizing (assumptions, not measurements)
| Item | Value |
|---|---|
| Users × turns | 1M × 30 |
| Peak turn rate | About 1,050 turns/s |
| Long-term reads at peak | 2,100/s |
| Store reads at peak (five-way fan-out) | About 5,250/s |
| Raw episodes per user | About 20 days at five tasks a day |
| Episode writes | 5M a day |
| Live episodes at the cap | ≤ 100M |
| Vectors at the cap | About 400 GB |
| Summary folds | About 7% more model calls |
3. Failures and the Closing Answer
Volunteer the ten failure modes
- Random keys
- Untrimmed stores
- Reset summaries
- Unbounded episodes
- Scans
- Model-supplied identity
- Expired sessions still readable
- Stale preferences
- Over-storing extractors
- Memory poisoning
Evaluate and pace
- Measure recall of planted facts and false memories, not fluency.
- The rubric has eight lines (in the full casebook's Practice).
- The 45 minutes go to scopes, bounds and isolation.
Cost in one line
- Memory cost is writes and read-back tokens: retrieve a few, summarise in steps, extract small and late.
Closing answer: "Four scopes with four keys, reads in parallel inside 300 ms, writes after the reply, user_id from auth, and a recall harness that proves the assistant remembers the right person's facts and nothing it never heard."
Flashcard Drill
Quick Recall: Lines to Say in the Interview
- "Resolve, read in parallel, assemble, reply, then write from a queue."
- "Identity service, fan-out, queue: the isolation, latency and write boundaries."
- "Semantic facts overwrite with one prior version; episodes append and get pruned to 100."
- "The 300 ms is for reads; the critical path is about 115."
- "1,050 turns a second at peak, about 400 GB of vectors at the cap."
- "Trimming the prompt doesn't trim storage."
- "Measure recall and false memories, not fluency."
- "Retrieve a few, summarise in steps, extract small and late."
Where next
- Revise the concepts