Serving Million-Token Contexts: Four Optimizations for Attention and Inference Systems
Supporting million-token inputs is more than enlarging a context window. This article breaks the problem into three separate questions—capacity, performance, and quality—and walks through four practical optimizations: reducing KV cache footprint, controlling quadratic attention cost, reusing shared prefixes, and scheduling mixed workloads. It also outlines how to validate task quality and system performance before rolling out long-context serving in production.
1. First, Separate Three Problems: Capacity, Compute, and Accuracy
Feeding an entire technical specification, cross-module codebase, or multi-round review history into a single request reduces the information loss caused by manual chunking. For example, verifying whether an interface constraint is honored across several modules usually requires reading the spec, the implementation, and the tests together; retrieving only the most relevant fragments can miss low-frequency but critical exception clauses. The value of long context lies precisely in preserving these cross-section, cross-file relationships.
But supporting million-token input does not mean you can process it at acceptable cost and latency, nor does it guarantee the model reliably uses every piece of evidence in it. In engineering terms, you should validate three questions independently: Can the model accept a sequence of the target length? Can the inference system complete the computation at the target concurrency? Can the model find the correct evidence amid distractors and act on it? These correspond to capacity, performance, and quality—and a context-window limit cannot stand in for any of them.
Understanding these constraints requires splitting inference into two phases. The prefill phase processes the existing input, computes representations for each position, and builds the key-value (KV) cache. The decode phase generates new tokens step by step while reading historical KV states. Long inputs typically increase prefill time and time-to-first-token (TTFT); once generation begins, a longer history can also raise the per-step KV read overhead during decoding. The former determines how long users wait before seeing output; the latter determines whether output can be sustained steadily. The four optimizations below address these bottlenecks, but they must ultimately be validated as one system.
2. Optimization 1: Change the KV Representation to Reduce Cache Burden
Standard multi-head attention (MHA) gives each query head its own keys and values. Autoregressive inference caches the keys and values of past positions to avoid recomputing the entire prefix for every generated token. The cost: with other settings unchanged, cache capacity grows linearly with sequence length, and every in-flight request occupies its share of space.
Multi-query attention (MQA) keeps multiple query heads but lets them share a single set of keys and values. Different query heads can still produce different attention weights over the same past positions, while the system stores far fewer KV heads. Grouped-query attention (GQA) sits between MHA and MQA: several query heads share one set of keys and values, and different groups use different KV representations. It offers a tunable middle ground, but the right grouping must be validated against both model quality and serving load.
Multi-head latent attention (MLA) takes a different route: it compresses KV information into low-dimensional latent representations, caches those at inference time, and performs attention based on the specific kernel implementation. The key distinction from MQA is that MLA changes the cached representation, while MQA changes how KV heads are shared. Both can reduce cache overhead, but they cannot be ranked by compression ratio alone: latent dimensions, extra cached entries, compute kernels, and hardware memory-access patterns all affect real-world results.
For implementations using a conventional KV cache layout, you can estimate per-sequence cache size with:
KV cache bytes ≈ number of layers using this layout × cached token count × number of KV heads × head dimension × bytes per element × 2
The factor of 2 accounts for keys and values separately. This is only a capacity estimate—it does not apply directly to latent-representation caches, and it excludes model weights, temporary tensors, memory-allocation overhead, and cross-device communication buffers. In deployment, validate with your real length distribution and concurrency stress tests, not just by checking whether a single longest request fits in GPU memory.
3. Optimization 2: Reduce Comparisons to Control Long-Sequence Compute
A smaller KV cache does not mean fewer position pairs for full attention to process. In standard causal attention, every position can attend to all earlier positions; running full prefill over an input of length (L) still means the number of attention interactions grows on the order of (L^2). In other words, optimizing KV representation answers “how much does each position store,” while sequence-compute optimization answers “how much history does each position need to see.”
If the model architecture allows, a local window can handle neighboring tokens, while global positions, hierarchical computation, or sparse selection preserve some long-range connections. A fixed window restricts attention to nearby context, which suits continuous prose and local code relationships; for tasks requiring distant evidence, you must verify that the additional information pathways still cover exception clauses, cross-file definitions, and combinations of evidence scattered across the input. Sparse selection is not free either: filtering itself costs compute, and once key evidence is excluded, no amount of efficient computation can recover the missing input.
A second class of methods leaves the visible positions unchanged and instead changes how computation executes. Chunked computation, for example, avoids materializing the full attention matrix at once, reducing intermediate tensor footprint; scheduling prefill for long prompts in segments prevents a single request from monopolizing compute resources for a long stretch. Both can improve serving behavior, but neither reduces full attention’s asymptotic complexity to linear. In particular, avoid silently truncating history at the deployment layer and marketing it as natively supported sparse attention: if the model was not adapted to that visibility range during training, output quality may degrade.
4. Optimization 3: Compute Shared Prefixes Only Once
Long requests in enterprise applications often share a stable prefix—the same version of an operations spec, project materials, or review guidelines. For token prefixes that match an existing cache, the inference system can reuse the corresponding KV states and only process the newly added content. This cuts redundant prefill work and can shorten TTFT for warm requests.
To improve reuse, you can—without changing task semantics—place stable content at the front and frequently varying content such as questions and timestamps at the back, while keeping document order and template serialization consistent. Whether a cache is reusable cannot be judged by “the text looks the same”; you must also consider tokenization results, model version, compute configuration, and permission boundaries. When documents are updated, access is revoked, or isolation scopes change, there should be a clear cache-invalidation mechanism; do not put requests that require isolation into the same reuse domain just to boost hit rates.
Also distinguish prefix reuse from prefix omission. A cache hit means the prefill for the matched portion need not be re-executed—it does not mean the decode phase can skip reading those historical states. The cache itself consumes space. So beyond hit rate, evaluate the actual number of reused tokens, the residency cost of the cache, TTFT for cache-miss requests, and eviction behavior under high concurrency. Testing only the warm-start scenario of repeatedly sending the same material will overestimate real-world gains.
5. Optimization 4: Schedule by Load So Long Requests Don’t Starve Short Ones
A single very long request running successfully and a system stably serving a mix of long and short traffic are two different things. If concurrency is limited only by request count, a prefill task near the window limit can compete with many short Q&A requests for the same compute and cache resources, driving up tail latency for the short requests. Admission and scheduling should factor in input token count, expected output length, remaining cache capacity, and business deadlines—rather than assigning identical resource weight to every request.
In practice, interactive Q&A and batch document review can use separate queues with their own deadlines and resource budgets. With chunked prefill, partially decoded requests can be interleaved to improve streaming experience; but the chunk size and scheduling priority for long requests need stress testing, because giving short tasks more execution opportunities may increase completion time for long ones. For sequences spanning multiple devices, communication overhead must be included in the accounting: sharding relieves per-device memory pressure but does not guarantee lower end-to-end latency.
A useful serving dashboard should at minimum separate three phases: queuing, prefill, and decode. If queue time grows, check admission and queue policy first; if prefill time climbs steeply with length, examine attention computation, input organization, and prefix reuse; if output slows mid-stream, look at historical KV reads, concurrent batching, and cross-device communication. Tracking TTFT, decode speed, peak memory, and high-percentile latencies by input-length bucket says far more about production readiness than a single average throughput number.
6. Rollout: Prove Task Benefits First, Then Expand Length and Traffic
The most valuable validation is not stuffing the window with irrelevant text but building comparison sets that distinguish good solutions from bad ones. Pick a batch of real tasks and, under identical output requirements, compare three paths: providing the full material directly, retrieving relevant fragments before answering, and extracting candidate evidence first then supplementing surrounding context. For tasks requiring only a single rule check, short context may be faster and easier to audit; for tasks that must combine evidence from multiple places, full context is worth the extra cost.
Quality tests should vary evidence position, the number of distractor documents, and the distance between pieces of evidence. For example, place the exception clause that determines the conclusion at the beginning, middle, and end respectively, and check whether the model cites the correct passage; add documents with similar names but different versions to see if the model confuses their scope of applicability; include cases where the material is genuinely missing, to verify the model can state clearly that evidence is insufficient. When evaluating, don’t judge only whether the answer reads fluently—verify cited sources, coverage of key evidence, and whether conclusions exceed what the material supports.
Performance tests should cover at least three scenarios: cold cache, stable prefix hits, and mixed long-short traffic, while recording timeouts, truncations, and degradations. When resource limits are reached, you can prompt users to narrow the material scope or switch to extracting evidence in segments and then aggregating. If a request has been truncated, say so explicitly—never present results from partial material as a full review conclusion.
Ultimately, million-token context should be treated as a capability enabled per task, not the default configuration for every request. Use attention-structure changes to reduce per-position cache burden, sequence-compute optimizations to control interaction cost, prefix caching to eliminate redundant work, and scheduling to protect service stability under mixed loads. Only when evidence utilization on real tasks improves—and TTFT, tail latency, and resource cost remain within acceptable ranges—has expanding the context window delivered genuine engineering value.
