How to Systematically Reduce the KV Cache Bottleneck in Long-Context Inference: Co-Optimizing Compute, Storage, and Transfer

    Long-context agent workloads push KV cache sizes to hundreds of GiB per sequence, making compute, memory, and bandwidth simultaneous bottlenecks. This article explains how to estimate KV cache capacity, reduce computation through windowed and sparse attention, cut prefill costs with segmented encode-decode architectures, combine cache compression techniques such as cross-token merging and low-bit storage, and support these optimizations with tiered caching, prefix reuse, and prefill-decode disaggregation at the system level.

    1. Background: New Bottlenecks from Long-Horizon Tasks

    In single-turn question answering, the context is typically only a few thousand tokens, and both attention computation and cache overhead remain manageable. Long-horizon agents are different. They must retain large amounts of history within a single session, including user instructions, retrieved documents, tool outputs, and intermediate reasoning. The context can grow to hundreds of thousands or even millions of tokens, and the model repeatedly reads this history during generation.

    During autoregressive decoding, the model reads the Key and Value tensors of all previous tokens — the KV cache — every time it generates a new token. Because cache size scales linearly with sequence length, long contexts impose three types of cost at once:

    1. Compute cost: the theoretical complexity of attention depends on sequence length, and global attention grows rapidly on long sequences.
    2. Storage cost: the cache occupies accelerator memory or other storage media, and usage grows with the number of concurrent sessions.
    3. Transfer cost: every decoding step reads a large volume of data from memory, so bandwidth often becomes the limiting factor before raw compute does.

    Reducing computation alone does not solve storage or data movement. Compressing the cache alone may add extra computation. The design goal should therefore be to reduce all three costs simultaneously, rather than optimizing just one.

    2. Do the Math First: Estimating KV Cache Size

    Before applying any optimization, estimate the cache size. In standard multi-head attention, each token stores one K and one V per layer. Total cache size can be estimated as:

    Cache bytes = 2 × layers × KV heads × head dimension × bytes per element × sequence length × batch size

    The following code computes cache size with a set of assumed parameters. These parameters are for demonstrating the calculation only and do not represent the actual configuration of any specific model.

    1. def kv_cache_bytes(layers, kv_heads, head_dim, dtype_bytes, seq_len, batch=1):
    2. # Factor of 2 accounts for storing both K and V
    3. return 2 * layers * kv_heads * head_dim * dtype_bytes * seq_len * batch
    4. per_token = kv_cache_bytes(layers=40, kv_heads=8, head_dim=128, dtype_bytes=2, seq_len=1)
    5. total = kv_cache_bytes(layers=40, kv_heads=8, head_dim=128, dtype_bytes=2, seq_len=1_000_000)
    6. print(f"Per-token cache: {per_token / 1024:.1f} KiB") # 160.0 KiB
    7. print(f"One 1M-token sequence: {total / 1024**3:.1f} GiB") # 152.6 GiB

    The result shows that even with grouped-query attention reducing the number of KV heads, a single one-million-token sequence still requires over a hundred GiB of cache. Scaling hardware alone cannot support large-scale concurrent long-context serving; optimization must come from both model architecture and cache management.

    Two additional points matter when estimating. First, batch size scales the cache linearly. Second, real deployments also include paging overhead, alignment, and temporary buffers, so actual usage is usually higher than the theoretical value.

    3. Reducing Computation: Windowed and Sparse Attention

    Global attention requires every position to attend to all previous positions. Sliding window attention restricts each position’s attention to the most recent w tokens, changing computation from quadratic to linear in sequence length. Information outside the window must be recovered through other mechanisms.

    Sparse attention is another path. The model first uses a lightweight selection mechanism to pick a small set of relevant historical entries, then applies exact attention only to those entries. The effectiveness of this approach hinges on selector quality: if the selector misses critical information, no amount of precise downstream computation can recover it.

    Compute overhead is especially significant during prefill, since every token in the prompt must be processed. Choosing appropriate window and sparsity strategies can substantially reduce prefill time and, in turn, time to first token.

    4. Architectural Approach: Segmented Encoding and Decoding

    One noteworthy idea is to avoid having every layer read the full prompt. Concretely, the deep network is split along depth into two segments. The first half is the encoding segment, which reads the full prompt once during prefill and produces final hidden states. The second half is the decoding segment, which no longer reads the full prompt layer by layer. Instead, it projects the encoding segment’s final hidden states into global KV entries, while maintaining local KV only within a recent window at each layer.

    In this structure, the global representation is generated as:

    $C^l = H \cdot W^l_{KV}, \quad Z^l = H \cdot W^l_Z$

    where $H$ is the hidden state output by the encoding segment, $C^l$ is the global KV entry used by decoding layer $l$, and $Z^l$ is the corresponding compression weight. The projection matrices $W^l_{KV}$ and $W^l_Z$ are learned independently per layer.

    In simplified notation, let the total number of layers be $L$, the prompt length $N$, and the window length $n{win}$. If all layers apply global attention over the full prompt, prefill cost is roughly $O(N \cdot L)$. If only half the layers read the full prompt while the rest process only the window, the cost is approximately $O(N \cdot L/2 + n{win} \cdot L/2)$. When $N$ is much larger than $n_{win}$, prefill computation is nearly halved.

    The trade-offs of this design are clear. It changes the network’s information flow, requires retraining, and is sensitive to where the split is placed. Splitting too early leaves the encoding segment with insufficient representational capacity; splitting too late limits the compute savings. It is therefore better suited to models designed from scratch or retrained at scale, rather than as a simple patch to an existing model.

    5. Cache Compression: Stacking Multiple Techniques

    Reducing cache size usually requires combining several methods; a single approach is rarely sufficient. The table below summarizes common techniques and their trade-offs.

    Technique Primarily reduces Main cost Typical risk
    Windowed attention Compute, cache length Out-of-window info needs extra mechanisms Key information falls outside the window
    Cross-token compression Number of cache entries Lossy compression Degraded exact retrieval
    Sparse selective access Memory bandwidth Selector needs tuning or training Missing critical entries
    Low-bit storage Memory footprint, transfer volume Quantization error, needs custom kernels Numerical instability
    Segmented encode-decode Prefill compute Major structural change, training cost Sensitive to split position

    Cross-token compression merges the KV of several adjacent tokens into fewer entries. Merge weights can be fixed pooling or learnable weighting. This directly reduces the number of entries, but heavier compression means greater information loss.

    Low-bit storage compresses KV from 16-bit floating point to 8-bit or lower formats, typically with per-block scaling factors. Cache size and transfer volume decrease linearly with bit width. Note that Keys and Values often have different sensitivity to quantization error, so in practice they usually need to be calibrated separately.

    Keeping recent KV exact means the most recent tokens remain uncompressed while older history uses compressed representations. Recent tokens usually have the greatest influence on current generation, so preserving them reduces quality loss.

    Bounded replay limits how much history the model can re-read when needed. If the system allows unrestricted lookback, both cache and computation spiral out of control. Bounding replay length keeps worst-case overhead predictable.

    These methods can be stacked. Their individual savings multiply, so total cache size can drop substantially. But stacking also compounds error: quality losses accumulate at each step. Any combined scheme must therefore be validated through full evaluation, not just single-metric checks.

    6. System Support: Cache Tiering and Data Movement

    Architectural optimizations need system-level support, or their gains will not materialize. Common engineering practices include the following.

    Cache tiering. Hot data stays in accelerator memory, warm data in host memory, and cold data on local disk or object storage. A scheduler places data based on access frequency. Below is a simplified tiered cache example illustrating the basic logic of eviction and promotion:

    1. from collections import OrderedDict
    2. class TieredKVCache:
    3. def __init__(self, hot_capacity):
    4. self.hot = OrderedDict() # Hot data in accelerator memory
    5. self.cold = {} # Cold data in host memory or object storage
    6. self.hot_capacity = hot_capacity
    7. def put(self, session_id, block):
    8. self.hot[session_id] = block
    9. self.hot.move_to_end(session_id)
    10. while len(self.hot) > self.hot_capacity:
    11. old_id, old_block = self.hot.popitem(last=False)
    12. self.cold[old_id] = old_block # Should be offloaded asynchronously in production
    13. def get(self, session_id):
    14. if session_id in self.hot:
    15. self.hot.move_to_end(session_id)
    16. return self.hot[session_id]
    17. if session_id in self.cold:
    18. block = self.cold.pop(session_id)
    19. self.put(session_id, block) # Promotion may trigger further eviction
    20. return block
    21. return None

    The eviction policy in this example is least recently used. Production systems must also consider block-level granularity, prefix reuse, and session priority.

    Prefix reuse. In multi-turn conversations and agent tasks, the system prompt and historical prefix recur frequently. Reusing the cache for identical prefixes avoids redundant prefill.

    Prefill-decode disaggregation. Prefill is compute-intensive; decoding is memory-bandwidth-intensive. Scheduling them in separate resource pools makes it easier to optimize throughput and latency independently.

    Bandwidth estimation. Each decoded token requires one full read of the current cache. Assuming a 10 GB cache and 2 TB/s of effective bandwidth, reading the cache takes roughly 5 milliseconds per step in theory.