12.5 Long Context Serving
A model accepting a long request has passed only an input-contract check. The serving system still needs memory capacity, predictable latency, recoverable state, and evidence that the model can use the supplied information. Think of a long request as a large job entering a busy workshop: dividing it into smaller pieces changes scheduling fairness, but does not remove the work.
1. Budget the State the Architecture Actually Stores
For a uniform attention stack, the logical KV payload is
Here is batch size, cached tokens per sequence, the number of attention layers, the KV head count, head dimension, and bytes per stored scalar. The leading 2 counts keys and values. Query heads determine attention computation but must not replace KV heads in a GQA memory estimate.
For a hypothetical 32-layer model with 32 query heads, 8 KV heads, , BF16 storage, and one sequence, 4,096 tokens occupy 0.5 GiB and 131,072 tokens occupy 16 GiB of logical KV payload. Using 32 KV heads would make the estimate four times larger. These are accounting examples, not a named model’s supported context limits.
Accounting-helper limitation: The standard-library example below is smoke-tested for integer arithmetic and input validation. It is not an allocation or capacity test. It excludes parameters, activations, temporary buffers, page/scale metadata, fragmentation, graph pools, collectives, and checkpoint/recovery overhead. Hybrid stacks require a layer-by-layer KV plus recurrent-state inventory; sharding and replication determine per-device storage.
def kv_payload_bytes(*, layers, kv_heads, head_dim, tokens,
batch=1, bytes_per_value=2):
values = (layers, kv_heads, head_dim, tokens, batch, bytes_per_value)
if any(type(value) is not int or value <= 0 for value in values):
raise ValueError("All dimensions and byte widths must be positive integers")
return 2 * layers * kv_heads * head_dim * tokens * batch * bytes_per_value
# Hypothetical uniform GQA model, BF16, one sequence.
size = kv_payload_bytes(layers=32, kv_heads=8, head_dim=128, tokens=131072)
print(size / 2**30) # 16.0 GiB of logical KV payload
Prefill often has high arithmetic intensity; small-batch dense decode often has low arithmetic intensity. Neither label is universal: sequence length, batch size, attention sparsity, quantization, expert communication, and kernel implementation can move the bottleneck. Profile the intended workload rather than declaring one phase entirely compute-bound or the other entirely bandwidth-bound.
2. Streaming Stability Is Different from Full-History Recall
StreamingLLM retains initial attention-sink tokens with a recent window to stabilize streaming in its tested settings [1]. Fixed retained state does not preserve arbitrary evidence discarded outside the window. A stable loss curve is not proof of full-history comprehension.
YaRN modifies RoPE scaling to extend useful context in its evaluated models [2]. It does not create an infinite context window or guarantee extrapolation. Validate retrieval, evidence integration, and generation at the target length, position distribution, and output budget.
3. Chunking Controls Interference, Not Total Work
Sarathi studies chunked prefills interleaved with decode [3]. Smaller chunks can reduce the time existing requests wait behind a new prompt, but kernel efficiency and the long request’s TTFT may worsen. Chunked attention must still account for prior-prefix keys; timing independent square matrix multiplications is not a faithful serving simulation.
Measure TTFT and inter-token latency at p50/p95/p99 under an arrival trace, alongside queue age, prefill backlog, tokens/s, and rejection rate. State admission limits and deadlines before a load test. Compare goodput—requests meeting the latency and correctness contract—not only peak throughput.
4. Disaggregation Adds a Transfer and Ownership Contract
Splitwise and DistServe investigate separate prefill and decode resource pools [4] [5]. Hardware choice follows measured capacity, bandwidth, compute, and interconnect needs; “decode uses cheap GPUs” is not a universal rule.
A useful lower-bound model is , where is actual transferred bytes and achieved bandwidth. Startup, packing, congestion, synchronization, and scheduling add overhead. Halving payload does not necessarily halve end-to-end latency.
Declare who owns each cache version and when the handoff commits. The receiver verifies request/prefix identity, model/tokenizer/template hashes, position offsets, cache layout/dtype, and completion before decoding. Recompute or reject on mismatch; do not attach a cache merely because its tensor shape matches. Quantization changes both wire size and numerical behavior and needs task-level validation.
5. Context Capacity Is Not Reasoning Quality
As of 2026-10-18, Gemini 4 Argon’s API specifies a unified input-and-output window of 1,048,576 tokens, with 65,536 default synchronous maximum output and a distinct long-decode path [6]. A maximum output allowance cannot be added on top of a full input window. Admission should reserve the requested output budget under the exact endpoint contract.
The October 15 LURCH preprint characterizes long-context difficulty through evidence scope, evidence dispersion, and reasoning depth, using questions with evidence and reasoning graphs [7]. Its findings concern the evaluated setup; these properties are useful evaluation axes, not a universal capacity law.
An engineering test matrix should vary those axes at fixed token length, then vary length while holding the task structure constant. Include an oracle-evidence condition to separate retrieval from reasoning, and measure citation correctness and abstention. A successful needle lookup is insufficient for a dispersed multi-step synthesis task.
6. Scheduling Illustration and Release Gate
The animation shows ordering choices using invented units, not hardware measurements or a predicted speedup. Change strategy and replay to inspect where existing decode work can run.
P: prefill · D1–D3: existing decodes · KV: state handoff · New: new request decode
In this schedule, existing decodes wait for the large prefill.
2026-10-18 · Generation method: hand-authored teaching schedules in invented units. These are not hardware measurements or speedup predictions. Disaggregation also adds a resource pool.
Release only after long-context quality, tail latency, memory peaks, overload behavior, cancellation, and cache-handoff recovery meet predeclared slice gates. Keep a known-good serving configuration, canary new scheduling/cache policies, and rehearse a rollback that also invalidates incompatible state. The next chapter examines how compression changes this resource budget.
Quizzes
Quiz 1: Why must a GQA KV estimate use KV heads rather than query heads?
Multiple query heads share each key/value head. Using the query count overestimates the stored payload; execution and memory dimensions are different.
Quiz 2: Why can chunking improve decode latency while worsening a long request’s TTFT?
Interleaving gives existing decodes opportunities to run, but inserts other work before the long request finishes and can reduce kernel efficiency. The tradeoff depends on load and chunk size.
Quiz 3: Does a stable windowed stream prove recall of an early fact?
No. The fact may have been evicted. Streaming stability and retention of arbitrary distant evidence require different tests.
Quiz 4: Why does halving KV transfer bytes not guarantee halving request latency?
Startup, congestion, conversion, synchronization, compute, and queueing remain. The payload-over-bandwidth term is only part of the critical path.
Quiz 5: Why compare dispersed and localized evidence at the same token length?
It separates the difficulty of finding and combining evidence from raw context size. Equal token counts can hide very different reasoning demands.
References
- Xiao, G., et al. (2023). Efficient Streaming Language Models with Attention Sinks. Paper.
- Peng, B., et al. (2023). YaRN: Efficient Context Window Extension of Large Language Models. Paper.
- Agrawal, A., et al. (2023). SARATHI: Efficient LLM Inference by Piggybacking Decodes with Chunked Prefills. Paper.
- Patel, P., et al. (2024). Splitwise: Efficient Generative LLM Inference Using Phase Splitting. Paper.
- Zhong, Y., et al. (2024). DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving. Paper.
- Google. (2026). Gemini 4 Argon API model contract. As of 2026-10-18. Documentation.
- Qin, S., et al. (2026). Beyond Context Length: Characterising the Difficulty of Long-Context Reasoning. October 15 preprint. Paper.