Context Window Scaling: 1M+ Token Retrieval, Needle-in-a-Haystack, and KV Cache Limits

Context Window Scaling: 1M+ Token Retrieval, Needle-in-a-Haystack, and KV Cache Limits

A team ships a contract-review assistant. The prototype works: paste a 60-page agreement into the prompt, ask for the termination clauses, get a correct answer. Then the product owner asks the obvious next question. Why not load the whole deal room, all 600 pages of it, and let users ask anything? The model card advertises a million-token window, so it should fit. It does fit, in the sense that the request is accepted. Then the first load test arrives. Time to first token is measured in tens of seconds, twenty concurrent users exhaust the GPU memory that comfortably served two hundred short chats, and an answer that cites a clause from page 340 turns out to be a paraphrase of a similar clause from page 12.

None of these three failures comes from a bug. They are the three costs of long context showing up together: the memory the attention cache occupies, the compute needed to read the prompt in the first place, and the gap between the number of positions a model can accept and the number it can actually use. This article walks through each one with arithmetic you can redo for your own model, then through the techniques that shrink or avoid the cost, and ends with a checklist for deciding whether a long window or retrieval is the better tool.

1. The arithmetic of a KV cache

During generation, a transformer does not recompute the keys and values of earlier tokens at every step. It stores them. That store is the KV cache, and its size follows directly from the model's shape:

bytes per token = 2 × layers × kv_heads × head_dim × bytes per element

The 2 counts the key tensor and the value tensor. Take a shape that is common for a 70B-class dense model with grouped-query attention: 80 layers, 8 KV heads, a head dimension of 128, stored in 16-bit floats. That is 2 × 80 × 8 × 128 × 2 = 327,680 bytes, roughly 320 KiB for every token in the context. The same model with one KV head per query head (64 heads, classic multi-head attention) would need eight times that, about 2.5 MiB per token.

The script below reproduces the numbers in this section. Swap in the layer and head counts from your own model's configuration file.

from dataclasses import dataclass


@dataclass
class ModelShape:
    layers: int
    kv_heads: int
    head_dim: int


def kv_bytes_per_token(m: ModelShape, bytes_per_elem: float = 2.0) -> float:
    # One K tensor and one V tensor per layer, each kv_heads * head_dim wide.
    return 2 * m.layers * m.kv_heads * m.head_dim * bytes_per_elem


def kv_cache_gib(m: ModelShape, tokens: int, bytes_per_elem: float = 2.0) -> float:
    return kv_bytes_per_token(m, bytes_per_elem) * tokens / 2**30


shape = ModelShape(layers=80, kv_heads=8, head_dim=128)

for tokens in (8_000, 128_000, 1_000_000):
    for label, width in (("fp16", 2.0), ("fp8", 1.0), ("int4", 0.5)):
        gib = kv_cache_gib(shape, tokens, width)
        print(f"{tokens:9,} tokens  {label:4}  {gib:8.1f} GiB per sequence")

For fp16 it prints about 2.4 GiB at 8,000 tokens, 39 GiB at 128,000 tokens and 305 GiB at one million tokens, for one sequence. The weights of a 70B model in 16-bit precision are around 140 GB. At a million tokens the cache for a single user is more than twice the size of the model itself, and it grows linearly with every added token and every concurrent user. The 4-bit row ignores the scale and zero-point metadata that real quantization schemes store, so treat it as a lower bound.

Rule of thumb. Capacity planning for long context is a multiplication, not a benchmark: bytes per token × tokens per sequence × concurrent sequences. If that product exceeds the memory left after weights, no scheduler trick will save the deployment. Only a smaller cache, fewer sequences or more devices will.

2. Prefill and decode: two different bottlenecks

A request has two phases that stress different resources. Prefill processes the whole prompt in parallel and produces the cache. Decode then generates one token at a time, and each new token attends to everything stored so far.

Prefill is compute-bound and quadratic

Self-attention compares every prompt token with every earlier one, so the work grows with the square of the prompt length. FlashAttention-style kernels avoid writing the full n × n score matrix to memory, which fixes the memory blow-up, but they do not change the arithmetic count. Doubling the prompt roughly quadruples the attention portion of prefill. The feed-forward layers scale only linearly, so for short prompts they dominate and the quadratic term is invisible. At hundreds of thousands of tokens the attention term takes over. That is why time to first token, not generation speed, is the first number that degrades in a long-context product.

Decode is memory-bandwidth-bound

Generating one token requires reading the model weights and the sequence's whole cache from device memory, doing a small amount of math, and writing one new cache entry. The ratio of arithmetic to bytes moved is low, so the accelerator waits on memory. Back-of-envelope: if a single device with roughly 3 TB/s of memory bandwidth had to read a 305 GiB cache for every generated token, the read alone would cost on the order of 100 ms per token. Real deployments shard the cache across devices to divide that, which is one reason million-token serving needs several accelerators per replica.

The practical consequence is that the two phases want different tuning. Prefill benefits from large batches of prompt tokens and high compute utilization. Decode benefits from a small cache, and from batching many sequences so one pass over the weights serves all of them. Long contexts hurt that batching, because each sequence drags its own large cache into the pass.

3. Shrinking the cache by architecture

The most effective compression is the one chosen when the model is designed, because the model is trained to work with it.

  • Multi-query and grouped-query attention. Multi-query attention shares one key/value head across all query heads. Grouped-query attention (GQA) is the middle ground: several query heads share each KV head. The 8-KV-head shape used above is already a GQA design, and it is the reason the cache is 320 KiB per token instead of 2.5 MiB.
  • Multi-head latent attention (MLA). Introduced with the DeepSeek-V2 model family, MLA stores a compressed low-rank latent vector per token and reconstructs keys and values from it when needed. It cuts the per-token footprint further than GQA with a small projection cost at read time.
  • Local and global layers. Some model families interleave layers that attend only to a sliding window of recent tokens with a minority of layers that attend to everything. Local layers keep a cache bounded by the window size, so only the global layers grow with context.
  • State-space and hybrid layers. Recurrent or state-space blocks keep a fixed-size state instead of a growing cache. Hybrids mix them with a few attention layers. They trade exact recall of arbitrary earlier tokens for constant memory.

You cannot add these to a model you did not train. They matter when you choose which model to serve, because two models with the same advertised window can differ several-fold in cache cost per token. Read the configuration file before the marketing page.

4. Shrinking it after the fact: quantization, eviction, offloading

When the architecture is fixed, three families of techniques remain, and each has a quality price.

Quantizing the cache

Storing keys and values in 8-bit (integer or floating point) halves the cache relative to 16-bit, and 4-bit schemes roughly quarter it. Keys are usually harder to quantize than values because a few channels carry large outliers, so better schemes treat the two differently or quantize per channel. The risk is silent: perplexity on short text barely moves, while exact-recall tasks at long range degrade first. Test with retrieval-style probes, not just chat quality.

Evicting tokens

Not every cached token is equally useful. Research on attention sinks (the StreamingLLM line of work) found that models put disproportionate attention on the first few tokens, and that keeping those plus a recent window lets a model run on an unbounded stream with a fixed cache. Heavy-hitter methods such as H2O keep the tokens that have received the most attention so far. These approaches bound memory, but they discard information permanently. If a user later asks about a detail from the evicted region, the model cannot recover it. They suit streaming chat and monitoring, and they are a poor fit for document question answering where any sentence may matter.

Offloading

Cold cache pages can move from GPU memory to CPU memory or fast local storage and return when needed. This turns a hard capacity limit into a latency cost on the requests that touch cold pages. It works well for idle sessions you want to resume (a long conversation paused overnight) and badly for a single request that needs the whole cache at once, because the transfer time lands inside the user's wait.

Technique What it reduces Main risk Needs training?
GQA / MQA Cache size per token Small quality loss vs full multi-head Yes, at model design time
MLA Cache size per token, further than GQA Extra projection compute; fewer serving engines support it Yes
Local + global layers Growth of cache with context Weaker long-range recall in local layers Yes
KV quantization (8-bit, 4-bit) Bytes per cached element Exact-recall errors at long range No (calibration helps)
Token eviction / attention sinks Number of cached tokens Evicted facts are gone for good No
CPU / disk offload GPU-resident bytes Latency spikes on cold pages No
Prefix caching Duplicate cache for shared prompts and repeated prefill Needs byte-identical prefixes No
Context / sequence parallelism Per-device memory and prefill time Inter-device communication cost No

The table is qualitative on purpose. The size of each effect depends on the model, the kernel and the workload, so measure on your own traffic before committing.

5. Serving-layer tactics: paging, prefix reuse, chunked prefill

Several of the highest-leverage techniques live in the inference server, not the model.

Paged cache management

Naively reserving a contiguous slab for each sequence's maximum possible length wastes memory through fragmentation and over-reservation. PagedAttention, the idea behind vLLM, stores the cache in fixed-size blocks mapped through a block table, like virtual memory pages. Blocks are allocated as the sequence grows and freed when it ends, and blocks can be shared between sequences. Most current serving stacks adopt a variant of this design.

Prefix caching

If many requests begin with the same tokens, the server can compute that prefix once and share its cache blocks. Hosted APIs expose the same idea as prompt caching, usually with discounted pricing for the cached portion. The condition is strict: the prefix must match exactly, token for token. A timestamp, a request ID or a reordered tool list at the top of the prompt breaks the match for everything after it. Put stable content first (system instructions, reference documents) and volatile content last.

Chunked prefill

A single 500,000-token prefill can occupy the accelerator for a long time and stall every decoding user behind it. Chunked prefill splits the prompt into pieces and interleaves them with decode steps of other requests, trading some prefill latency for steadier generation latency for everyone else. For very long prompts, context parallelism (ring-attention-style schemes) spreads one prompt across several devices so that prefill time and memory both divide.

6. Accepting a position is not the same as using it

Everything above is about the cost of holding the context. The other half of the problem is whether the model uses it.

How windows get extended

Most models encode position with rotary embeddings (RoPE). A model trained on, say, an 8,000-token window has never seen the rotation angles that appear at position 500,000. Techniques such as position interpolation, NTK-aware scaling and YaRN rescale the angles so long positions map into the range the model already knows, followed by a continued-training phase on longer documents. Without that phase, quality at the extended range is usually poor. The advertised window tells you what the model was extended and tested to handle, not what it handles equally well everywhere.

What the tests actually measure

The popular needle-in-a-haystack test inserts one distinctive sentence at a chosen depth in filler text and asks the model to retrieve it. Passing it shows the model can find a single, lexically unusual fact. It does not show that the model can combine several scattered facts, resolve near-duplicates, or ignore plausible distractors. Follow-up benchmarks such as RULER add multi-needle retrieval, variable tracking and aggregation tasks, and reported results show that the length at which accuracy stays high is often well below the advertised maximum. Earlier work on the lost in the middle effect found that models tend to use information near the start and end of a long prompt more reliably than information in the middle, though the strength of the effect differs between models and has been reduced in newer ones.

Test your own needle. Build an evaluation from your real documents: questions whose answers sit at known depths, some requiring two facts from different places, some with a near-duplicate clause as a distractor. A model that scores perfectly on the synthetic test and fails this one is telling you about your workload, which is the only result that matters.

7. Long context or retrieval? A decision checklist

Retrieval-augmented generation and long windows are not rivals. They solve different problems, and many strong systems use both. Use the questions below in order.

  1. Does the corpus fit with room to spare? If the material is a few thousand tokens, put it all in the prompt. Retrieval adds moving parts for no gain.
  2. Will many requests reuse the same material? If yes, a cached shared prefix makes the long prompt cheap after the first request. This favors long context.
  3. Does the question need the whole document at once? Summarizing a contract, finding contradictions across sections, or tracing a defined term through a text benefit from seeing everything. This favors long context.
  4. Is the answer a lookup in a large, changing corpus? Thousands of documents, frequent updates, per-user permissions: retrieval handles freshness and access control, and a window cannot.
  5. Do you need to cite and audit? Retrieval returns specific passages with identifiers, which makes citations checkable. With a giant prompt, you must still ask the model to quote and then verify the quote against the source.
  6. What is the latency budget? A cold 500k-token prefill is slow. If users expect answers in a couple of seconds and prefixes are not shared, retrieve a small context instead.
Situation Better fit Why
One long document, many questions Long context with prefix caching Prefill paid once, whole document visible
Large corpus, narrow lookups Retrieval Only relevant passages cost tokens
Frequently updated knowledge base Retrieval Index updates are cheap; cache invalidates on any change
Cross-section reasoning in one file Long context Needs the pieces together, not top-k fragments
Strict per-user access rules Retrieval with filters Permissions enforced before text reaches the model
Very long agent transcript Summarize or prune, then retrieve Old tool output is mostly noise; cost grows every turn

Worked example: the deal room

Return to the contract-review team. Their corpus is about 400,000 tokens. With the 70B-class shape from section 1, one fp16 sequence of that length needs about 122 GiB of cache. Twenty simultaneous users, each holding a private copy, would need roughly 2.4 TiB, which is why the load test failed.

Now apply the tools in order. Put the deal room first in the prompt and keep it identical for everyone, so prefix caching lets all twenty sessions share a single copy of that 122 GiB, plus a small per-user tail for the question and answer. Quantize the shared cache to 8-bit if recall tests on contract questions stay clean, which halves it to about 61 GiB. Shard across devices so decode bandwidth per token drops. Add retrieval in front for the long tail of questions that only concern a single document, so those requests use a few thousand tokens instead of 400,000. The design that results holds one shared big cache, serves narrow questions cheaply and reserves the full window for questions that really need it.

8. Failure modes and common mistakes

  • Sizing from the advertised window instead of from measured recall. A model that accepts a million tokens may only be dependable at a fraction of that on multi-fact tasks. Find that length on your data.
  • Breaking the cache prefix. Injecting the current time, a UUID or a shuffled list of tools at the head of the prompt silently disables prefix reuse and multiplies cost.
  • Letting agent history grow without bound. Every turn appends tool output, and every later turn pays to carry it. Prune stale tool results, summarize old turns and keep decisions, not raw dumps.
  • Quantizing on perplexity alone. Aggregate quality metrics hide long-range retrieval regressions. Evaluate with the needle-style tests built from your own data.
  • Treating eviction as lossless. Once a token leaves the cache, the model cannot answer questions about it. Do not combine eviction with a product promise of whole-document recall.
  • Ignoring tail latency from long neighbors. One huge prefill can stall short requests on the same replica. Separate pools or chunked prefill keeps interactive traffic responsive.
  • Paying twice for the same prompt. Re-sending a large static document with every request, without caching, bills the full prefill each time.

When not to use a very long window

Skip it when answers depend on a small number of passages that a good retriever can find, when the corpus changes faster than a cache can stay warm, when users expect sub-second responses, or when you cannot afford the memory for peak concurrency. A larger window also gives the model more room to be distracted by irrelevant text, so it can reduce accuracy as well as raise cost.

9. What to do Monday

  1. Pull the layer count, KV head count and head dimension from your model's configuration and run the script above. Write the per-token and per-sequence numbers on the design doc.
  2. Compute peak concurrency × context length × bytes per token and compare it with free memory after weights. If it does not fit, decide which lever you will pull before you write more code.
  3. Build a 30-question evaluation from your real documents with answers at varied depths, including multi-fact questions and a near-duplicate distractor. Run it at the context lengths you plan to ship.
  4. Restructure prompts so that stable content comes first and volatile content last, then confirm that your server or provider reports prefix cache hits.
  5. Instrument time to first token and per-token decode latency separately. They fail for different reasons.
  6. Decide a pruning policy for long-running agent sessions before they reach the window limit.

Short FAQ

Does a bigger window remove the need for retrieval? No. It changes where the trade-off sits. Retrieval still wins on freshness, access control, citation and cost per question over a large corpus.

Is the cache only a GPU problem? Mostly, yes. It is the dominant memory consumer during decode at long context, and it competes with batch size. Offloading moves part of it to other tiers at a latency cost.

Can I just turn on 4-bit cache quantization? You can, and it often works. Verify it with long-range retrieval tests first, because the failure mode is a silently wrong detail rather than an obvious error.

How does this relate to agent systems? Long-running agents accumulate context fast. The disciplined pattern is to keep a short working context, store durable state outside the prompt, and have each step read only what it needs. Systems that verify results before moving on also avoid carrying failed attempts forward, which keeps both cost and confusion down.