Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 99/ 160
05. AI System Design

Context Window Management

Priority packing of instructions, tools, memory, and retrieved docs under a hard limit.

IntermediatePriority Pack · Truncate3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The AI can only read so much at once, so you pick the most important things to show it, shorten the rest and put the key stuff where the AI notices it.

Think of it like…

Packing a carry-on bag: essentials go in first (passport, charger), then the most useful extras by value per cm³, bulky items are compressed or left behind, and the things you need quickly sit on top.

Where you’ve seen it

A support assistant has an input budget of 6,000 tokens. Required: instructions 600, tool schemas 500, user message 200 (1,300 total), leaving 4,700. Memory facts: the top 3 at 80 tokens each (240) → 4,460 left. History: the last 2 turns verbatim (500) and the 6 older turns summarised into 250 tokens → 3,710 left. Retrieved chunks are 400 tokens each ranked by reranker score; 10 would need 4,000, so the packer keeps the top 9 (3,600), leaving 110. Total 1,300 + 240 + 500 + 250 + 3,600 = 5,890 tokens. Chunks are placed with the best first and second-best last (the middle holds the weaker ones) because accuracy tends to be highest for information at the start and end of a long context, and the user's question comes last. Near-duplicate chunks are removed with MMR before packing, and an ablation shows that cutting from 10 to 9 chunks changes answer accuracy by less than 0.5 points while saving 400 tokens (about $0.001 per request).

Words you’ll hear

Priority packing
Filling the prompt with required items first and optional items by value per token.
Lost in the middle
The tendency of models to use information at the start and end of long contexts better than in the middle.
Context rot
Declining accuracy as a context fills with irrelevant or redundant tokens.
MMR (maximal marginal relevance)
Selecting results that are relevant but not redundant with those already chosen.

Visual diagram

Loading interactive diagram

Theory & deep dive

A packing algorithm

Treat the prompt as a knapsack: each candidate item has a token cost and a value (relevance score, recency, importance). First reserve mandatory items (system instructions, tool schemas actually needed for this turn, the current user message) and the output budget. Then fill the rest by tiers: durable memory facts (few tokens, high value), the most recent turns (necessary for coherence), then retrieved chunks in reranked order, with older history summarised into a compact running summary. Within a tier, take items in decreasing value per token until the budget is spent, stop at a minimum score threshold (don't pad with weak chunks just because there's room) and keep a small reserve for safety.

Reduce waste before packing: de-duplicate near-identical chunks (MMR or embedding similarity), compress long chunks by extracting only the relevant sentences (with a small model or extractive method), truncate tool outputs (keep head and tail, paginate big tables) and drop tool schemas not needed this turn (tool retrieval selects a few relevant tools). Count tokens with the model's tokenizer and test the packer with adversarial inputs (a 50,000-token user paste, 40 long history turns) so it degrades predictably. Tune budgets per tier through ablation: measure quality as you vary the number of chunks or history length and choose the knee of the curve, not the maximum that fits.

Greedy fill

Budget 6,000. Required 1,300 → 4,700 left. Memory 240 → 4,460. History 500 + 250 → 3,710. Chunks of 400: floor(3,710 ÷ 400) = 9 chunks = 3,600 → 110 left. Total used 5,890.

Key takeaway: Reserve required content, fill by value per token with thresholds, compress and de-duplicate first, and tune budgets by ablation.

Ordering, long contexts and failure modes

Position matters. Studies of long-context use (for example the "Lost in the Middle" results) found that model accuracy is often highest when relevant information sits at the start or end of the context and drops by double-digit points when it sits in the middle of many documents. Practical consequences: put instructions first, the most relevant evidence next, weaker context in the middle, and restate the key question and format requirements at the end; for long documents, order by relevance rather than original document order, or place the question both before and after. Use clear delimiters and labels (<doc id=3>) so the model can cite sources, and keep consistent structure so prefix caching works (stable parts first).

A larger window doesn't mean you should fill it: context rot and distractors reduce accuracy, and cost and latency grow with tokens (prefill time and per-token price). Prefer retrieving less but better, reranking before packing and using summaries and memory for long conversations; use full long-context prompts only when the task truly needs whole-document reasoning (legal review of one contract, codebase-wide questions) and compare with retrieval on your eval set. Failure modes to test: the answer chunk gets truncated by a hard limit, instructions are pushed out of the window by a long paste (always protect them), summaries drop a key constraint, and stale history contradicts new instructions. Log what was included, dropped and summarised per request so failures can be traced to packing decisions.

Sandwich ordering

Ranked chunks 1 to 9. Order in the prompt: chunk 1, then chunks 3 to 9 in the middle, then chunk 2 last, followed by the question. The two strongest pieces sit at the start and end, where the model is most reliable.

Key takeaway: Order by importance with strong items at the edges, avoid filling the window for its own sake and log packing decisions.

How it works, step by step

Step 1 of 4
Engineering

1. Set budgets

Define the total input budget and the output reserve, and list required versus optional components.

6,000 in · required 1,300
Key numbers at this step
Protect
instructions

When to use it & trade-offs

What it is

Context window management decides what goes into the prompt, in what order and in how many tokens: instructions, tool definitions, memory, retrieved documents, conversation history and the user's message, all competing for a limited budget. The core technique is priority packing: reserve space for the required items, then fill the remainder with the most valuable optional content (ranked by relevance per token), compress what doesn't fit (summarise old turns, extract key sentences from chunks) and order the content to exploit how models use long inputs. A bigger window does not remove the need: cost, latency and "context rot" (quality decline as irrelevant text grows) still reward a tight, well-organised prompt.

Why it matters: Prompts that dump everything (full history, ten retrieved documents, every tool schema) are slow, expensive and often *less* accurate: models can miss information buried in the middle of long contexts, and distractors can mislead them. A deliberate packing policy improves answer quality at lower cost, makes behaviour predictable when inputs are large and gives a defined fallback when content exceeds the budget.

When to reach for it

  • Chat assistants with long histories
  • RAG with many candidate chunks
  • Agents with large tool outputs

When to avoid or be careful

  • Filling the window just because it's available
  • Letting a long paste push out instructions
  • Placing the most important evidence in the middle

Handling too much context

Priority packing with truncation
Best for: Predictable, cheap prompts

Strengths: Simple, controllable.

Watch out: May drop useful items at the margin.

Summarisation and compression
Best for: Long histories and verbose documents

Strengths: Keeps key facts in fewer tokens.

Watch out: Extra calls; risk of losing details.

Retrieve on demand (RAG or memory tools)
Best for: Huge corpora and long-running agents

Strengths: Pulls only what's relevant.

Watch out: Depends on retrieval quality.

Interview signals & numbers to know

When this topic comes up

  • “The model ignores the document I gave it”
  • “Context length exceeded”
  • Lost in the middle
  • Context rot
  • Rolling summaries

Benchmarks & rules of thumb

5,890 of 6,000 -
tokens used in the packing example
−0.5 pt / −400 tokens -
effect of using 9 instead of 10 chunks
start and end -
positions where long-context accuracy is typically highest

Common mistakes & follow-ups

Common interview mistakes

  • Adding all retrieved chunks regardless of score.
  • Summarising history without keeping user constraints verbatim.
  • Changing prompt structure so often that prefix caching never hits.

Likely interviewer follow-ups

  • How would you pack a prompt for a RAG chat assistant?
  • What is the lost-in-the-middle effect and how do you mitigate it?
  • Why not just use the largest context window available?
Interview tip: Describe it as a knapsack with required items, value per token and a threshold. It shows you treat context as a scarce resource.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Context Window Management with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
RAG vs Fine-tuning
Next topic
Cost Optimization