Context Windows: Limits, Cost and Long-Context Behaviour
By the Katkat team · Updated · 9 min read
Quick overview
Explain context windows in interviews: quadratic attention cost, lost-in-the-middle, per-token pricing, and when to truncate, summarise or retrieve.
After this lesson you will be able to explain what a context window limits, why long prompts get slower and more expensive, and why a model can have a huge window and still ignore part of it. You will also be able to estimate the cost of a request and argue for truncating, summarising or retrieving instead of stuffing everything into the prompt.
What a context window is
A context window is the maximum number of tokens a model can process in one request. It is measured in tokens, not characters or words, so the same text can fit or not fit depending on the tokenizer (see Tokenization: BPE, Vocabulary Size and Why Tokens Matter).
Everything the model sees counts against the window:
- the system prompt and tool definitions
- the conversation history
- retrieved documents or pasted files
- the user's new message
- the tokens the model generates, including any hidden reasoning tokens on models that produce them
For most APIs the window is shared between input and output, and many models also have a separate, smaller cap on output length. If the input fills the window, there is no room left to answer. The window is a hard limit: a request over the limit is either rejected or silently truncated, depending on the provider and settings.
The window length is fixed by training and by how position information is encoded. Models are often extended to longer windows with extra training and changes to positional schemes (see Positional Information: Sinusoidal, Learned and RoPE). An advertised window tells you what fits, not how well the model uses it.
Why attention cost grows quadratically
In self-attention, every token computes a score against every other token it may attend to. For a sequence of n tokens, each head in each layer builds an n × n score matrix. Doubling the length quadruples the number of scores.
| Tokens (n) | Scores per head per layer (n²) | Relative to 8,000 |
|---|---|---|
| 8,000 | 64 million | 1x |
| 32,000 | 1.024 billion | 16x |
| 128,000 | 16.384 billion | 256x |
If you stored one 32,000 × 32,000 score matrix in 16-bit floats, it would take 1.024 billion × 2 bytes ≈ 2 GB for a single head in a single layer. Real implementations avoid materialising it, which is the point of FlashAttention and IO-Aware Attention. FlashAttention changes the memory traffic, not the fact that the work is still quadratic.
Quadratic attention is not the whole bill. In a standard transformer layer with model width d and a 4x MLP, the projections and MLP cost roughly 12·n·d² multiply-adds, while the attention scores and weighted sum cost roughly 2·n²·d. The ratio is about n / (6d). For d = 4,096, attention matches the rest of the layer at n ≈ 6 × 4,096 = 24,576 tokens. At 8,192 tokens, attention is about a third of the other work. At 32,768 it is about 1.3 times as much. This is a rough estimate that ignores grouped-query attention and other variations, but it explains why costs look almost linear for short prompts and then bend upward.
Prefill versus decode, and the KV cache
The quadratic term mostly hits the prefill phase, where the model processes the whole prompt in parallel. During decode, each new token attends to all n cached keys and values. That is linear in n per generated token, and the pressure shifts to memory: the model must read the whole KV cache for every token it generates. See Prefill, Decode and the KV Cache for the full picture.
KV cache size grows linearly with context. Take an illustrative configuration: 32 layers, 8 KV heads (grouped-query attention), head dimension 128, 16-bit values.
- Per token: 2 (keys and values) × 32 layers × 8 heads × 128 × 2 bytes = 131,072 bytes = 128 KiB.
| Tokens | KV cache for one sequence |
|---|---|
| 8,000 | about 1.05 GB |
| 32,000 | about 4.19 GB |
| 128,000 | about 16.8 GB |
That is per concurrent request. A server handling many long requests runs out of GPU memory long before it runs out of compute, which limits batch size and raises cost per request. Real models differ in layers, heads and precision, so treat these numbers as an example of the method.
Lost in the middle
A model that accepts 128,000 tokens does not necessarily use all of them equally well. The paper "Lost in the Middle: How Language Models Use Long Contexts" studied tasks where the relevant fact is placed at different positions in a long input. The reported pattern is a U shape: models tend to use information near the beginning and the end more reliably than information in the middle. The size of the effect varies by model and task, and newer models have often improved, so do not assume it is gone or that it is fixed.
Two related points matter in practice:
- Needle tests are easy. Finding one planted sentence is much easier than combining several facts scattered across a long document. A good needle score does not guarantee good multi-hop reasoning.
- More context can hurt. Irrelevant or near-duplicate passages act as distractors. Adding ten extra retrieved chunks can reduce accuracy even though the answer is still present.
Mitigations you can state in an interview:
- Put instructions at the start and repeat the key constraint or question at the end.
- Rerank retrieved chunks and place the best ones at the edges, not buried in the middle (see Hybrid Search and Reranking).
- Send fewer, better chunks rather than as many as fit.
- Measure on your own data by moving the answer-bearing passage to different positions and comparing accuracy.
Pricing per token
Hosted models usually charge per token, with separate rates for input and output, and output tokens are commonly priced higher. Some vendors discount cached input tokens, and some charge extra for very long prompts. These details vary by vendor and change over time, so check the current price sheet.
Worked example with illustrative prices of $3 per million input tokens and $15 per million output tokens. A RAG request sends 12,000 input tokens and gets 500 output tokens.
- Input: 12,000 × $3 / 1,000,000 = $0.036
- Output: 500 × $15 / 1,000,000 = $0.0075
- Total: $0.0435 per request
At 100,000 requests per day that is $4,350 per day. If better retrieval cuts the prompt to 4,000 tokens:
- Input: 4,000 × $3 / 1,000,000 = $0.012
- Total: $0.012 + $0.0075 = $0.0195, or $1,950 per day
That saves $2,400 per day, and the shorter prompt is also faster.
Chat history makes this worse because each turn resends everything. Suppose the system prompt is 1,000 tokens and each turn adds 300 tokens of history. Input tokens billed on turn k are about 1,000 + 300k.
- Over 10 turns: 10 × 1,000 + 300 × (1 + 2 + … + 10) = 10,000 + 300 × 55 = 26,500 tokens
- Over 20 turns: 20 × 1,000 + 300 × 210 = 83,000 tokens
Doubling the conversation length more than triples the total input billed (83,000 / 26,500 ≈ 3.1). Cumulative cost grows quadratically with turns, which is a separate effect from quadratic attention. Prefix caching helps when the start of the prompt is identical across calls (see Prefix Caching).
Truncate, summarise or retrieve
When content does not fit, or fits but is too costly or noisy, you have four options.
| Strategy | How it works | Good for | Risks |
|---|---|---|---|
| Truncate | Drop the oldest turns or cut a document to a token budget | Casual chat, content where recent text matters most | Loses facts silently, may cut instructions or the question |
| Summarise | Replace old content with a short model-written summary | Long conversations, long documents read once | Extra call and latency, lossy, errors can compound across rounds |
| Retrieve | Store content externally and fetch only relevant pieces | Large knowledge bases, long histories with specific lookups | Retrieval misses, chunking quality matters |
| Use full long context | Put everything in the prompt | Small corpora, tasks needing whole-document reasoning | High cost and latency, distractors, middle-of-context weakness |
A sensible approach starts with a token budget. For a 32,000-token window, reserve 1,000 for output, 1,500 for the system prompt and tools, and a 5% safety margin of 1,600 tokens because your token count may differ slightly from the server's. That leaves 32,000 − 1,000 − 1,500 − 1,600 = 27,900 tokens for history and retrieved content. Then fill that budget in priority order: the system prompt and the current question are never dropped, the most relevant retrieved chunks come next, and the oldest history is trimmed or summarised first.
Practical rules for summarising: keep exact identifiers, numbers, names and user-stated constraints verbatim rather than paraphrased, and summarise in a rolling way with a trigger such as "when history exceeds 60% of the budget". For more on memory designs see Conversation Memory for Chat Applications.
How does this come up in interviews?
1. Why does a long prompt make inference slower and more expensive? Prefill attention does work proportional to n², so doubling the prompt roughly quadruples that part, though the MLP part grows only linearly. The KV cache also grows linearly with length, which uses GPU memory and reduces how many requests can be batched. On hosted APIs you additionally pay per input token.
2. What is lost-in-the-middle and how would you handle it in a RAG system? Models tend to use information at the start and end of a long prompt more reliably than information in the middle. I would send fewer chunks, rerank so the best ones sit at the edges, repeat the question at the end, and test accuracy while moving the gold passage to different positions.
3. The model has a 128k window. Should we skip retrieval and put the whole knowledge base in the prompt? Usually not. A full prompt costs far more per request, is slower, adds distractors, and the knowledge base may exceed the window or change often. Full context is reasonable for small, static corpora or tasks needing whole-document reasoning, and I would decide by comparing cost, latency and accuracy on an evaluation set.
4. A chat app hits the context limit after a long session. What do you do? Compute a token budget that reserves room for output and the system prompt. Keep the recent turns verbatim, summarise older turns into a rolling summary that preserves exact facts, and optionally store older details externally for retrieval. Trigger this before the limit is reached, not after a failure.
5. Estimate the daily cost of a feature that sends 10,000 input tokens and gets 400 output tokens, 50,000 times a day. State the prices as assumptions, then multiply: input tokens per day are 10,000 × 50,000 = 500 million, and output tokens are 400 × 50,000 = 20 million. Apply the per-million rates, and mention cached-input discounts and shorter prompts as levers.
Common mistakes
- Treating the advertised window as the usable window, ignoring that output tokens and the system prompt consume part of it.
- Saying attention is "quadratic" without noting that it matters mostly in prefill and that the MLP part is linear.
- Forgetting that chat history is resent each turn, so billed input grows faster than the conversation looks.
- Assuming a perfect needle-in-a-haystack result means the model will reason well over many scattered facts.
- Stuffing in every retrieved chunk instead of choosing and ordering a few good ones.
- Summarising away exact values such as IDs, dates and amounts.
- Counting tokens with the wrong tokenizer and hitting limits in production.
- Quoting vendor prices or window sizes as fixed facts instead of stating them as assumptions.