Context Engineering & Memory
Assembling the prompt as a resource-allocation problem — cache-aware ordering, history compaction, and the memory architectures that let a system remember across sessions.
#The framing
Everything a model knows about the current request arrives through the context window. Deciding what goes in it — and in what order — is a resource-allocation problem with four simultaneous constraints:
CAPACITY the window is finite, and effective capacity
is smaller than advertised
COST every token is billed, on every request; input
volume usually dominates in chat products
CACHE only a PREFIX can be reused, so ordering
determines your hit rate
QUALITY irrelevant content actively degrades answersThose four pull against each other. Adding more retrieved documents raises the chance the answer is present and lowers the chance the model finds it, while costing tokens and possibly breaking your cache.
#Layout, and why order is not cosmetic
From KV cache management: a cached prefix is reusable only up to the first byte that differs. So one variable token near the front invalidates everything after it.
✗ BAD LAYOUT
[timestamp: 2026-08-09 14:23:07] ← changes every request
[user: alice, plan: pro]
[system prompt, 2,000 tokens]
[tool definitions, 1,500 tokens]
[retrieved documents]
[conversation history]
[current question]
Cache hit rate ≈ 0.
Every request re-prefills 3,500 tokens of static content.
✓ GOOD LAYOUT
[system prompt, 2,000 tokens] ← identical for everyone
[tool definitions, 1,500 tokens] ← identical
──────── shared prefix ends here ────────
[user profile] ← stable per user
──────── per-user prefix ends here ──────
[conversation history] ← append-only, grows
[retrieved documents] ← varies per turn
[timestamp]
[current question]
Global prefix cached across ALL users.
Per-user prefix cached across their session.
Only the tail is ever re-prefilled.The rule: order by rate of change, most stable first. Anything that rewrites the start of a prompt — including an LLM gateway injecting per-request metadata — silently destroys this. It's the same principle as ordering Docker layers to maximise build cache reuse, and just as easy to get wrong.
#Managing conversation history
History grows every turn, and remember that the whole of it is re-sent on every request — the model retains nothing by itself. So cost per turn climbs steadily, and eventually the conversation simply won't fit. Compaction is the general name for shrinking it, and the options differ in what they throw away.
| Strategy | Mechanism | Cost |
|---|---|---|
| Full history | Send everything | Grows without bound; best quality |
| Sliding window | Keep the last N turns | Constant cost; loses early context abruptly |
| Summarisation | Compress older turns into a summary | Constant-ish; costs a model call; loses detail |
| Hierarchical | Summarise summaries as the conversation grows | Scales to very long sessions |
| Retrieval over history | Store turns, retrieve relevant ones | Best for long sessions with topic jumps |
#Memory across sessions
Context handles one conversation. Memory is what persists beyond it.
The interesting layer is long-term memory, and it's mostly an extraction and retrieval problem rather than a modelling one:
Write path. After a conversation (or periodically during it), extract durable facts — "prefers TypeScript", "works at Acme", "timezone IST". Store them with a timestamp, a source reference, and a confidence.
Read path. At the start of a conversation, retrieve relevant memories and inject them into the stable per-user prefix. Retrieval can be simple — recent plus frequently-accessed is often enough — or embedding-based for large memory stores.
The hard parts are not the storage:
- Contradiction. "I use Python" then later "I've switched to Go." You need supersession (the new fact replaces the old one), not accumulation (both are kept). Store each fact under a named slot — say
primary_language— with a timestamp, so the newer value wins, rather than both facts sitting in the context confusing the model. - Decay. A preference from two years ago is probably stale. Time-weight retrieval (rank older memories lower), or expire them (delete after a set period).
- Over-extraction. Storing everything means retrieving noise. Extract sparingly and prefer precision.
- User control. People must be able to see and delete what's remembered. This is a product requirement and increasingly a legal one, and it's much easier if memories are discrete records rather than an opaque embedding blob.
#Budgeting the window
Explicit allocation beats "fill it until it's full."
128K context window, an agent doing code work:
system prompt + tools 4,000 fixed
user memory 1,000 capped
retrieved code context 40,000 capped, reranked to fit
conversation history 30,000 compacted to fit
current message 2,000
──────────────────────────────────
used 77,000
RESERVED FOR OUTPUT 16,000 ← must be reserved
headroom 35,000 ← for growth mid-task
Rules that follow:
· every category has a cap; nothing grows unbounded
· output space is reserved FIRST, not left over
· when a category exceeds its cap, IT compacts —
it does not steal from anotherReserving output space is the one people miss. Filling 126K of a 128K window leaves room for a two-thousand-token answer, and the generation truncates mid-sentence. The failure looks like a model problem and is a budgeting bug.
#Instructions in the prompt
Beyond content, the shape of the instruction matters and is cheap to get right:
- Put instructions before the data, not after — though with a long context, repeating the key instruction at the end helps, since the end of the window is a high-attention position.
- Be explicit about the failure case. "If the context doesn't contain the answer, say you don't know" measurably reduces fabrication.
- Use structure. XML tags or markdown headings around documents help the model distinguish content from instruction, and make prompt-injection attempts easier to spot.
- Version prompts as artifacts. They are code. They need review, versioning, and a rollback path, and every trace should record which version ran.
#Check yourself
Which four constraints compete for the context window?Show answer
What is the rule for ordering a prompt?Show answer
What is good ordering worth?Show answer
How do you compact history without wrecking the cache?Show answer
What are the four memory layers?Show answer
What makes long-term memory hard?Show answer
What privacy duties does memory create?Show answer
How should the window be budgeted?Show answer
#What to carry forward
- Order by rate of change, most stable first. Only a prefix caches; one variable token at the front costs you everything.
- Compaction breaks the cache. Compact rarely, in large increments, and keep the result stable.
- An append-only context is cacheable; a rewritten one is not.
- Memory is extraction plus retrieval, and the hard parts are contradiction, decay, and deletion.
- Design the deletion path before the write path.
- Budget explicitly and reserve output space first, or generations truncate.