SysDesignAtlas

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.

HLDMedium9 min readaicontextmemoryprompt
Confidence

#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 answers

Those 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.

StrategyMechanismCost
Full historySend everythingGrows without bound; best quality
Sliding windowKeep the last N turnsConstant cost; loses early context abruptly
SummarisationCompress older turns into a summaryConstant-ish; costs a model call; loses detail
HierarchicalSummarise summaries as the conversation growsScales to very long sessions
Retrieval over historyStore turns, retrieve relevant onesBest for long sessions with topic jumps

#Memory across sessions

Context handles one conversation. Memory is what persists beyond it.

Working memory the current context window · this turn Session memory this conversation · full or compacted history Long-term memory facts about the user · extracted, stored, retrieved Shared knowledge documents and data · the RAG corpus
Four layers with different lifetimes, storage, and retrieval mechanisms.

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 another

Reserving 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
Capacity (effective is less than advertised), cost (every token billed every request), cache (only a prefix is reusable) and quality (irrelevant content degrades answers).
What is the rule for ordering a prompt?Show answer
Order by rate of change, most stable first: system prompt and tools, then user profile, then append-only history, then per-turn documents, timestamp and question.
What is good ordering worth?Show answer
Moving 3,500 static tokens ahead of anything variable saves ~350M prefilled tokens a day at 100,000 requests, and ~200 ms of TTFT each — with no quality change.
How do you compact history without wrecking the cache?Show answer
Compaction rewrites the prefix, so compact rarely in large increments and keep each summary fixed once written. An append-only context is cacheable; a rewritten one isn't.
What are the four memory layers?Show answer
Working memory (this turn), session memory (this conversation), long-term memory (extracted facts about the user) and shared knowledge (the RAG corpus).
What makes long-term memory hard?Show answer
Contradictions (newer facts must supersede older ones per slot), decay, over-extraction noise, and user control — discrete, inspectable records with sources.
What privacy duties does memory create?Show answer
Real deletion everywhere (index, caches, backups within retention), no cross-user leakage, no silent retention of sensitive data, and explainable memories. Design deletion before the write path.
How should the window be budgeted?Show answer
Cap every category, reserve output space first, keep headroom, and make an over-cap category compact itself rather than steal from another — otherwise answers truncate.

#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.
00:00
/ 9m