Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
A finite window,
an endless task.
An agent's context window is a whiteboard of fixed size, but the conversation keeps coming. Sooner or later the board is full — and now every turn is a decision: what do you erase? Erase the wrong thing and the agent forgets the user's name, the plan, the fact that mattered. This is the memory problem, and it has a clean shape: a token budget you can't exceed, two ways to make room (forget, or compress), and an external notebook the agent can search when it needs something it wrote down long ago. Here's the arithmetic of remembering.
The board fills up
Every LLM call is stateless — the model only knows what's in its context window right now. To give an agent continuity, you resend the conversation history each turn. But the window holds a fixed number of tokens, and a real agent's history — messages, tool calls, tool results, retrieved documents — grows without bound. The collision is inevitable: at some point the history no longer fits, and you must decide what to drop.
That decision is agent memory. It's not a fancy neural mechanism; it's a budgeting problem. You have a token budget (the window minus room for the model's reply and system prompt), a stream of content that exceeds it, and a policy for choosing what survives into the next turn and what gets stored elsewhere. Get the policy right and the agent stays coherent over hours; get it wrong and it forgets the thing it needed most, mid-task. Everything else in this handbook is refinements of that budget.
A finite context window forces a memory policy: keep recent turns, evict or summarize old ones to fit the token budget, and push durable facts to external memory you can retrieve.
Short-term vs long-term
Memory splits into two tiers, mirroring how we usually think about it. Short-term (working) memory is the context window itself — the recent messages the model sees directly this turn. It's fast and fully available, but tiny and volatile: anything not in it, the model simply doesn't know. Long-term memory is an external store — a database or vector index — that holds facts, summaries, and past events indefinitely, outside the window.
The agent's job is to shuttle between them: keep the relevant recent turns in short-term memory, write durable facts to long-term memory, and retrieve from long-term back into the context when a turn needs them. This is exactly the architecture MemGPT framed as an operating system for memory — the context window is RAM, external memory is disk, and the agent pages information between them. With that split, an agent can "remember" far more than its window ever holds, because most of its memory lives on disk and only the relevant page is loaded at a time.
Forget or compress
When the context exceeds budget, you have two moves to make room. Eviction drops the oldest messages until the rest fit — first-in-first-out, like a sliding window over the conversation. It's dead simple and keeps the most recent, most relevant turns, but it forgets: whatever falls off the back is gone from context entirely.
Summarization is the smarter move: replace a block of old messages with a short summary that preserves the essential facts for a fraction of the tokens. A rolling summary lets the agent carry a trace of the whole conversation in a small, fixed budget, so it doesn't fully forget the early context — it just holds a compressed version of it. The trade-off is fidelity: summaries lose detail, and a fact dropped from a summary is as gone as an evicted one. That's why the third leg — external memory you can retrieve exact facts from — matters, and why production agents combine all three.
The budget math
The whole problem is a token inequality. The messages you send must fit the budget B (the window minus reply and system-prompt room). Eviction keeps the newest messages whose total stays under B:
FIFO: the newest turns survive, the oldest fall off. Simple, but everything evicted is gone from context.
Summarization changes the arithmetic. Replace a block of history costing T tokens with a summary costing a fraction ρ·T (the compression ratio, e.g. ρ=0.25), and you free most of that budget while keeping the gist:
Compressing old turns to ρ·T lets the agent retain a trace of history it would otherwise evict — trading detail for coverage. The runnable version below fits messages to a budget by eviction, compresses evicted history, and retrieves a fact from external memory.
Fit history to a budget
Agent memory is a token budget with a policy. Eviction keeps the newest messages that fit and drops the oldest (FIFO) — so the context stays under budget but the earliest turns are forgotten. Summarization compresses a block of history to a fraction of its tokens, so a summary plus the recent turns costs far less than the full history while keeping the gist. And an external memory store recalls a specific fact by key even after it left the context entirely. Change the budget, the compression ratio, or the messages and watch what survives.
The external notebook
Eviction and summarization both lose information — the only question is how gracefully. The fix for durable facts is an external memory store the agent can search. It writes facts and past events out (often to a vector index keyed by embeddings), and when a new turn needs something old, it retrieves the relevant items back into context — recalling a specific fact long after it scrolled out of the window.
| Memory type | What it holds |
|---|---|
| Working (context) | Recent messages the model sees this turn — fast, fully available, tiny. |
| Episodic | Past interactions and events, retrievable by relevance ("what did we decide yesterday?"). |
| Semantic | Durable facts and preferences (user's name, project constraints) stored as key-value or vectors. |
| Summary buffer | A rolling compressed summary of the conversation so far, carried in context cheaply. |
The production recipe combines all of it: keep the last few turns verbatim (working memory), maintain a rolling summary of older turns (compression), and retrieve durable facts on demand from external memory (retrieval). This is the memory-stream idea behind generative agents — store observations, retrieve the relevant ones, and let the agent act with a memory far larger than its window. The window is just the desk; the filing cabinet is where most of the memory lives.
Pitfalls
The subtle failure is summarizing away the load-bearing detail. A summary that reads well can quietly drop the exact number, id, or constraint the agent will need later — and once it's out of both context and summary, it's unrecoverable unless it also went to external memory. So route durable specifics (ids, decisions, user facts) to a store, and let summaries carry only the gist. Another trap is retrieval that fetches the wrong memories: bad relevance ranking pulls in irrelevant history and pushes out what mattered, so memory quality depends on retrieval quality just as much as RAG does.
Two more. Recall context rot — a bigger window is not a free pass, because models attend less reliably to the middle of a very long context, so stuffing everything in can hurt even when it fits. And beware unbounded external memory: a store that only ever grows makes retrieval slower and noisier over time, so agents need forgetting policies (decay, deduplication, importance weighting) for long-term memory too. Good agent memory isn't about remembering everything — it's about spending a small token budget on the right things, and knowing where the rest is filed.
A fact only survives if it's in context, in the summary, or in external memory. Summaries and evictions both lose detail — so route anything you must recall exactly (ids, decisions, user preferences) to a durable store, not just a summary.
Worked example: a 20-turn chat in an 8,000-token window
Say the window is 8,000 tokens. Reserve 1,000 for the reply and 500 for the system prompt. Every turn (user message plus agent reply) costs 400 tokens, and the user gave their name in turn 2. Apply the page’s rules with ρ = 0.25.
| Step | Question | Arithmetic | Answer |
|---|---|---|---|
| 1 | Budget B | 8,000 − 1,000 − 500 | 6,500 tokens |
| 2 | History at turn 20 | 20 × 400 | 8,000: over budget by 1,500 |
| 3 | Evict (FIFO): what fits? | newest turns while Σ ≤ 6,500: 16 × 400 | 6,400 kept; turns 1–4 evicted |
| 4 | Where is the user’s name? | it was in turn 2 | Gone from context |
| 5 | Summarize turns 1–10 instead | 10 × 400 × 0.25 | 1,000-token summary |
| 6 | Summary + turns 11–20 | 1,000 + 4,000 | 5,000; 1,500 spare |
| 7 | Retrieve 3 facts from the store | 5,000 + 3 × 100 | 5,300 sent; name recalled exactly |
| 8 | Turn 30, same ratio | 20 × 400 × 0.25 + 10 × 400 + 300 | 6,300: nearly full again |
Step 4 is the silent failure: the agent works fine and has simply forgotten who it is talking to. Step 7 is why the name should have gone to the store when it was said, not left for a summary that may or may not keep it. Step 8 shows that a summary at a fixed ratio still grows with the conversation. Around turn 30 you must summarize the summary itself, and every pass loses a little more detail. So durable facts belong in the store, not the summary.
Cost and trade-offs of each memory policy
Time is the extra work per turn, Space is the tokens each turn sends, and the last column is what you give up. The totals use the example’s 400-token turns and 6,500-token budget.
| Case | Time | Space | Why |
|---|---|---|---|
| Resend everything | None | Grows every turn: 84,000 tokens over 20 turns, 510,000 over 50 | Total cost grows with the square of the conversation length, and it overflows the window at turn 17 anyway. |
| FIFO eviction | A sum over recent turns | Capped at the budget: 272,000 tokens over 50 turns | Cheapest policy that fits. Forgets everything past the window, including the important parts. |
| Rolling summary | An extra model call each time you compress | Summary ρ·T plus recent turns | Keeps the gist of everything. Loses exact numbers, ids and wording, and each re-summary loses more. |
| External store + retrieval | Embed the query and search the store each turn | Only the top few hits enter context; the store grows on disk | Exact recall of what was written down. Only as good as the ranking, and it needs its own forgetting policy. |
| A bigger window | None per turn, but every turn costs more | Up to the larger budget | Delays the problem rather than solving it, and the middle of a long context is attended to less reliably. |
Production agents stack the last three rows: recent turns verbatim, a summary for the gist, and a store for facts that must survive exactly. The eviction row is not a strategy on its own. It is what happens anyway when nothing else is in place.
Where this shows up in production and interviews
- Assistant memory features
ChatGPT’s memory saves facts about the user (name, preferences, ongoing projects) and brings them into later conversations. That is the semantic tier from the table above, kept apart from the chat history.
- Coding agents compacting context
Long coding sessions overflow the window fast, because tool results are large. Claude Code’s
/compactreplaces the history with a summary and carries on, which is the rolling-summary move done on demand. Project files such asCLAUDE.mdact as the durable store that every session reloads. - Framework building blocks
LangChain shipped this recipe as a ready-made class,
ConversationSummaryBufferMemory: recent turns verbatim, older ones summarized, switched by a token limit. MemGPT’s RAM-and-disk paging became the Letta project. - The interview version
For “design a support agent that remembers customers”, do the step 1 arithmetic out loud, then say what goes where: the last few turns in context, a running summary per conversation, and account facts in a store keyed by customer id. Then cover deletion. A user who asks to be forgotten must be removed from the store, not just from the window.
Check yourself
B = 6,500 and every turn is 400 tokens. With FIFO eviction, how many turns does the agent see, and what is the oldest turn it remembers at turn 25?
6,500 ÷ 400 rounds down to 16 turns (6,400 tokens). At turn 25 it sees turns 10–25, so the oldest it remembers is turn 10. Anything said in turns 1–9 is gone unless it was summarized or stored.
A user says “my order id is A-7731” early on. Hours later the agent needs it. Which of evict, summarize or store is the only safe place for it?
The store. Eviction drops it once it leaves the window. A summary may paraphrase it away or garble a digit, and nothing tells you it did. An exact identifier must be written to external memory when it appears and retrieved by key or by relevance later.
You double the window and the agent gets worse at using a detail from the middle of the conversation. Why?
Fitting is not the same as attending. Models use the middle of a very long context less reliably than its start and end, so stuffing more history in can bury the detail. Retrieving the relevant fact and placing it near the end of the prompt often beats a bigger window.
After a month, retrieval keeps pulling in stale, duplicate memories. What is wrong, and what do you add?
The store only grows. Add a forgetting policy: deduplicate on write, let old items decay, weight by importance, and overwrite a fact when it changes (a new address replaces the old one) instead of keeping both.
Quick answers
Why do agents need memory?
The context window is a fixed token budget but the conversation grows without bound, so the agent must decide what to keep, compress, or store externally.
Short-term vs long-term?
Short-term is the context window (recent, fast, tiny); long-term is an external store retrieved into context when needed.
How to stay in budget?
Evict the oldest messages (simple, forgets) or summarize them (compress the gist for fewer tokens) — production agents combine both plus retrieval.
How does retrieval memory work?
Write facts to an external store (often a vector index), then retrieve the relevant ones back into context — recalling facts long after they left the window.
This idea in other formats
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Agentic AI Interview HandbookTwenty topics every senior AI engineer should be able to reason about live — from eval pipelines to reliability patterns for generative systems.Read →
- The Agent Evaluations HandbookA self-contained handbook on evaluating AI agents — theory, interactive widgets, and practical guidance. Trajectory evals, tool-use scoring, LLM-as-judge, observability, and reliability for PMs, engineers, and founders.Read →
- The Agent Patterns HandbookThe design patterns behind every LLM agent — the ReAct Thought–Action–Observation loop, tool/function calling, plan-and-execute, reflection, memory, multi-agent orchestration, and the failure modes (loops, hallucinated tools, recovery, human-in-the-loop) that break agents in production.Read →
- The Model Context Protocol (MCP) HandbookThe open standard connecting AI agents to the outside world — why M×N bespoke integrations collapse to M+N, the host/client/server roles over JSON-RPC, the three primitives (tools, resources, prompts), the connect→discover→call session lifecycle, when MCP earns its keep, and the security sharp edges (a server's output is untrusted input).Read →
- The Loop Engineering HandbookStop prompting your agents — design the system that prompts them for you. The inner vs outer loop, the four loop types (heartbeat, cron, hook, goal), the six building blocks (automations, worktrees, skills, MCP connectors, subagents, external memory), stopping conditions and the verification split, state across runs, cost engineering, and the six failure modes that burn tokens at 3am.Read →
- The Context Engineering HandbookThe discipline that replaced prompt-tweaking: curating everything the model sees under a finite attention budget. The anatomy of a production context window, the three taxes on an overstuffed one (context rot, cost, behavioral drift), the four operations (write, select, compress, isolate), agent-specific patterns like compaction and just-in-time retrieval, six production habits, and where it sits in the prompt → context → loop → harness stack.Read →