Conversation Memory for Chat Applications
By the Katkat team · Updated · 10 min read
Quick overview
Learn how chat apps remember: sliding windows, rolling summaries, retrieval memory, per-user state and privacy, with token math for interviews.
After this lesson you will be able to explain why chat models need an explicit memory layer and compare the main strategies: windowing, summarisation and retrieval memory. You will also be able to describe how per-user state and privacy requirements shape the design. You should be able to size a conversation history against a token budget and defend a hybrid design.
The model has no memory; your application does
An LLM API call is stateless. The model sees only the tokens you send in that request. When a chat app "remembers" the previous turn, it is because the application stored the earlier messages and sent them again inside the next prompt.
This gives you three consequences:
- Memory is a prompt-construction problem. Every turn, you decide which past information goes into a limited context window and in what form.
- Cost grows with history. Input tokens are billed on every call, so a long conversation re-pays for old turns on every turn.
- Quality can drop with length. Models tend to use information in the middle of a long prompt less reliably than information at the start or end, so more history is not always better.
It helps to split memory into two kinds. Short-term memory is the current conversation (the thread). Long-term memory is what persists across conversations for a user. Windowing and summarisation mostly serve short-term memory, while retrieval and per-user state mostly serve long-term memory. For the agent-flavoured version of this topic, see Agent Memory and State.
Windowing: keep the most recent turns
The simplest strategy is a sliding window. You keep the last N messages, or better, as many recent messages as fit in a token budget, and drop the rest.
Mechanism:
- Always include the system prompt (it is never dropped).
- Reserve tokens for retrieved documents, tool results and the model's output.
- Fill the remaining budget with the newest messages, going backwards in time.
- Never split a unit that must stay together, such as a tool call and its result, or a user message and the reply it prompted.
Worked example. Suppose the model has a 16,000-token context window.
| Item | Tokens |
|---|---|
| System prompt | 800 |
| Retrieved documents | 3,000 |
| Reserved for output | 1,000 |
| Left for history | 16,000 − 800 − 3,000 − 1,000 = 11,200 |
If an average user+assistant exchange is about 400 tokens, the window holds 11,200 / 400 = 28 exchanges. Beyond that, the oldest exchanges fall off.
Now see why you cannot just keep everything. In a 40-exchange conversation with no trimming, the history sent at exchange k is about 400 × (k − 1) tokens. Summing over all 40 calls gives 400 × (0 + 1 + … + 39) = 400 × 780 = 312,000 history tokens, plus 40 × 800 = 32,000 for the system prompt. Total input grows quadratically with the number of turns, because each turn re-sends everything before it.
Trade-offs of windowing: it is cheap, deterministic and needs no extra model call. Its weakness is abrupt forgetting. A user's name, goal or constraint stated at turn 2 disappears at turn 30, and the model may contradict it.
Summarisation: compress what you drop
Instead of discarding old turns, compress them into a running summary that sits near the top of the prompt. A common layout is: system prompt, then summary, then the last few exchanges verbatim, then the new user message.
Mechanism:
- Keep a recent buffer (say the last 6 exchanges).
- When the buffer overflows, take the oldest exchanges plus the existing summary and ask a model to produce an updated summary.
- Store the new summary and delete the folded-in raw messages from the prompt (keep them in your database).
Worked example. Continue the numbers above. At exchange 41 of the conversation, full history is 40 × 400 = 16,000 tokens. With summarisation you send 6 × 400 = 2,400 tokens of recent exchanges plus a 500-token summary = 2,900 tokens. That saves 13,100 tokens per call, about 82%. The summary update costs an extra call, but if you fold in 6 exchanges at a time, each update reads roughly 500 + 2,400 = 2,900 tokens and writes about 500. That is paid once per 6 turns rather than on every turn.
Trade-offs:
- Summaries are lossy. Exact numbers, names, code and quoted wording are the first things to be blurred.
- Repeated summarisation can drift, because errors in one summary are inherited by the next. Mitigate by summarising from the raw messages when possible, and by pinning important facts separately.
- The summariser can hallucinate. Instruct it to include only what was stated.
- Batching helps caching. If you re-trim the prompt on every turn, the start of the prompt changes constantly, which defeats prefix caching where a provider or server supports it. Folding in chunks keeps the prefix stable between summary updates.
Retrieval memory: search the past instead of carrying it
Retrieval memory treats past conversation content as a searchable store. You write memories (messages, extracted facts or summaries) into a vector index as embeddings, and at each turn you embed the new message and fetch the top-k most relevant items.
Mechanism:
- Write: after a turn, decide what is worth saving. Saving every message is noisy; extracting short standalone facts ("prefers metric units", "works in Python 3.11") works better.
- Index: store text, embedding and metadata (user ID, timestamp, source, type).
- Read: embed the current query, filter by user ID, take the top-k, and optionally rerank.
- Inject: place the results in a clearly labelled section of the prompt.
Worked example. A user has 2,000 stored memory snippets of about 60 tokens each, which is 120,000 tokens. That would never fit in the window. Retrieving the top 5 costs 5 × 60 = 300 tokens per turn, which is 0.25% of the store.
Trade-offs: retrieval scales to unlimited history and is cheap per turn, but it can miss things. A follow-up like "what about the second one?" has little semantic content, so the query may need rewriting using recent turns first. Retrieved memories also lose their conversational order and context, so store timestamps and show them. This is the same machinery as RAG, applied to the user's own history rather than a document corpus.
Comparing the strategies
| Strategy | Extra model calls | Preserves exact wording | Long-range recall | Main failure mode |
|---|---|---|---|---|
| Sliding window | None | Yes, for recent turns | None beyond the window | Abrupt forgetting |
| Rolling summary | One per fold | No | Moderate, coarse | Lossy, drift |
| Retrieval memory | Embedding call per turn (plus optional extraction) | Yes, for stored items | High, if retrieval works | Missed or irrelevant retrievals |
| Per-user structured state | Optional extraction | Yes (explicit fields) | High for known fields | Stale or wrong fields |
Production systems usually combine them: a window for the immediate thread, a summary for the earlier thread, retrieval for older or cross-session facts, and a small structured profile for stable preferences.
Per-user state
Not everything should be free text. Stable, high-value information is better stored as structured fields in an ordinary database: display name, language, timezone, plan tier, preferences, and open tasks. You load the relevant fields into the system prompt on every conversation.
Advantages over free-text memory:
- Deterministic. You read a field instead of hoping retrieval finds it.
- Editable. The user or your support team can see and correct it.
- Cheap. A 100-token profile is always included without a search.
Design questions to settle:
- Scope: thread-level, user-level, or organisation-level? A fact stated in one thread may not belong in all of them.
- Write policy: who updates memory, and when? Letting the model write directly to memory via a tool is flexible but risky. Writing through a validation step, or only after explicit user confirmation for sensitive items, is safer.
- Conflict handling: if the user says "I moved to Berlin" and the profile says Paris, newer information should supersede older, and you should keep a timestamp.
- Concurrency: two tabs or devices may update the same state, so use versioning or last-write-wins deliberately.
A research system called MemGPT explored the idea of letting the model manage its own tiers of memory, moving information between the prompt and external storage. You do not need its details for most interviews, but the framing of the context window as fast, scarce memory and external storage as slow, large memory is a useful way to explain the design.
Privacy, security and lifecycle
Persistent memory turns a chat product into a system that stores personal data, so interviewers will expect you to raise it.
- Data minimisation. Store only what improves the product. Consider redacting or not saving sensitive categories such as credentials, payment details and health data.
- User control. Let users view, edit and delete memories, and offer a way to turn memory off. Be transparent about what is remembered.
- Deletion must reach every copy. Raw messages, summaries, extracted facts, embeddings in the vector index, caches and backups can all contain the same information. A deletion request that only removes the chat log leaves derived data behind. Design the data model so every derived item records its source and owner, and can be purged.
- Retention limits. Expire old memories by policy, not only on request.
- Tenant isolation. Always filter retrieval by user or tenant ID, and enforce it on the server. Never let the model choose which user's memory to read; the ID must come from the authenticated session.
- Memory poisoning. If the model can write to memory, an attacker who plants text in a web page or document can get an instruction saved and replayed in later sessions. Treat recalled memory as untrusted data, not as instructions, and see Prompt Injection and Guardrails.
- Training use. Using stored conversations to train or fine-tune models is a separate decision from using them for memory, and usually needs separate consent.
- Regulation. Rules such as GDPR include rights to access and erasure. Describe your design as supporting those requirements, and defer to legal counsel for specifics.
How does this come up in interviews?
1. Design the memory for a customer-support chatbot where conversations can last hundreds of turns. Use a hybrid: a token-budgeted window of recent turns, a rolling summary of earlier turns, and a small structured record of the case (order ID, issue, steps already tried). Add retrieval only if cross-conversation recall matters. State the token budget explicitly and say how you will evaluate whether the bot contradicts earlier facts.
2. Why not just put the entire conversation in a model with a very large context window? Cost and latency both grow with input length, and total tokens processed across a conversation grow quadratically if you resend everything. Long prompts can also reduce how reliably the model uses details in the middle. A large window raises the ceiling but does not remove the need to choose what goes in.
3. A user says the bot forgot their name from earlier in the conversation. How do you diagnose and fix it? Check what was actually in the prompt for that turn by looking at traces: was the name trimmed by the window or lost in a summary? Fix it by pinning stable facts such as the name in a structured profile that is always included, rather than depending on raw history or summarisation.
4. How would you implement "delete my data" for a chat product with memory? Enumerate every store holding user-derived data: message logs, summaries, extracted facts, vector index entries, caches, analytics and backups. Key each of them by user ID, delete or tombstone them in a defined workflow, and verify with a test that retrieval returns nothing for that user afterwards. Mention backup expiry and confirm the policy with legal.
5. When would you choose retrieval memory over summarisation? Choose retrieval when the history is very large, when exact details matter, or when relevant facts may come from many sessions ago. Choose summarisation when the thread is a single continuous narrative and you need cheap, coarse continuity. In practice combine them, and mention retrieval's weakness with vague follow-up queries.
Common mistakes
- Treating the model as if it remembers, and forgetting that every call must carry its own context.
- Trimming by message count instead of token count, so a few long messages overflow the window.
- Dropping the system prompt or splitting a tool call from its result during trimming.
- Summarising repeatedly with no source of truth, so errors compound.
- Saving every message to the vector store, which fills retrieval results with noise.
- Embedding a vague follow-up query directly without rewriting it using recent context.
- Letting the model write to memory with no validation, confirmation or provenance.
- Forgetting that summaries, embeddings and caches also contain personal data when handling deletion.
- Taking the user ID from model output or request parameters instead of the authenticated session.
- Re-trimming the prompt every turn and unknowingly breaking prefix caching.