Reducing KV Cache Costs for Long-Context LLMs: From Architecture to System Design

    As LLMs evolve from single-turn Q&A into long-horizon agents, KV cache becomes a major bottleneck in inference systems. This article examines the three cost categories of KV cache (storage capacity, data movement, and system transfer), explains how to compute the baseline KV cache size, introduces the Causal Encoder-Decoder architecture that lets only half the network process the full prompt, and reviews four cache compression techniques—architectural sharing, importance-based sparse attention, FP4 quantization, and sliding-window bounded replay—along with the system-level design considerations required for production deployment.

    1. Long-Horizon Agents Make KV Cache the Bottleneck

    As large models move from single-turn Q&A to long-horizon agents, the bottleneck of inference systems shifts. Previously, optimization focused on compute, and sparse attention plus sliding-window attention already relieved part of that pressure. But agents need to maintain contexts of millions of tokens, call external tools frequently, and revise their reasoning across multiple turns. The lifecycle of the KV cache is therefore dramatically extended: it is written once, then stored for a long time, read repeatedly, and moved between GPU memory, host memory, and storage.

    This lifecycle introduces three types of cost:

    Cost type Typical manifestation Key metrics
    Storage capacity As context grows, the global KV footprint grows roughly linearly with length GPU memory usage, context length a single GPU can hold
    Data movement During decoding, generating each token requires reading all historical KV HBM bandwidth utilization, output tokens per second
    System transfer During multi-instance scheduling, KV offload, and cross-node migration, KV volume consumes network and PCIe bandwidth PCIe or network throughput, migration latency, time-to-first-token (TTFT)

    All three costs must be considered together. If memory is saved but data movement is no faster, decoding is still slow. If movement is faster but prefill compute doubles, TTFT may exceed the business limit.

    2. First, Calculate the KV Cache Size

    Before evaluating any compression scheme, compute the baseline with this formula:

    KV bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element

    The factor of 2 accounts for the two tensors, K and V.

    Take a hypothetical configuration: 60 layers, 8 KV heads, head dimension 128, BF16 (2 bytes per element). Each token then occupies about 245,760 bytes, roughly 240 KB. A 1M-token context requires about 246 GB (decimal units) for a single copy of the KV cache. This already exceeds the memory of most single GPUs, so compression is essential.

    This example only illustrates the order of magnitude; it does not represent any specific model. When evaluating compression, count bytes before and after compression using the same methodology, and record the number of layers, heads, precision, and sequence length.

    3. Causal Encoder-Decoder: Let Only Half the Network Read the Full Prompt

    One architecture-level cost-reduction idea is to replace the pure decoder-only structure with a Causal Encoder-Decoder (CED). Take a 40-layer Transformer and split it along depth into two segments:

    • The first 20 layers form the causal encoder, which runs only during prefill, reads the full prompt sequence, and outputs a condensed global representation.
    • The last 20 layers form the decoder, which no longer reads the raw prompt. Instead, it reuses the encoder’s final-layer hidden state H₂₀. For decoder layer l, layer-specific linear projections generate global KV entries and compression weights:
    1. C^l = H_20 · W^l_KV # Global KV entries
    2. Z^l = H_20 · W^l_Z # Compression weights

    The decoder also reconstructs local sliding-window KV from the most recent tokens to capture fine-grained local dependencies.

    Complexity needs a precise statement. In a standard decoder-only model at prefill, every layer’s attention operates over the full sequence, and the attention term is proportional to the square of sequence length N. With CED, only the first half of the layers process the full sequence; the second half mainly handles the global representation and windowed KV. Therefore, the number of layers performing full-sequence attention is halved. When N is much larger than the window length n_win, the cost of full-sequence attention is roughly halved.

    However, total model compute also includes linear layers, the MLP, and decode-stage overhead, so total compute is not necessarily halved. Measure it in practice.

    Dimension Decoder-only CED
    Source of global KV Stored independently per layer Projected from a shared hidden state
    Layers with full-sequence attention at prefill All layers About half the layers
    Training difficulty Mature, standard pipeline Requires joint training of asymmetric activations and the compression mechanism
    Short-context benefit No extra projection overhead Extra projection parameters may offset saved compute
    Applicability General Requires dedicated model-side design; cannot be applied directly to existing models

    4. Four Techniques for Cache Compression

    Architectural changes address the compute problem. The storage problem is usually solved by stacking four techniques.

    1. Architecture-level sharing: Global KV is generated from a shared hidden state, avoiding each layer storing its own full historical KV.
    2. Importance-based sparse attention: The source text refers to this class of methods as “CSA-like mechanisms.” Ordinary sparse attention selects positions by fixed patterns (e.g., local windows or fixed strides). This class of methods estimates the importance of each KV entry for subsequent generation and keeps only critical entries. Its effectiveness depends on the quality of the importance estimation. The source text does not give the full name or reference of this mechanism, so it is described here only by function.
    3. Low-precision quantization (FP4 for the bulk KV): Store the main KV as 4-bit floating point, while retaining a small number of high-precision entries as anchors to compensate for quantization error. This requires quantization-aware training; otherwise, long-range dependencies degrade noticeably.
    4. Sliding-window bounded replay: KV inside the window does not reside in GPU memory permanently and is reconstructed at a bounded compute cost when needed. This trades extra compute for memory.

    The four techniques differ in effect and cost, and each must be validated separately:

    Technique Main effect Main cost or risk Metrics to validate
    Architecture-level sharing Reduces redundant storage Requires model structure changes and retraining Perplexity and downstream-task gap vs. baseline
    Importance-based filtering Reduces retained KV entries Dropping critical entries by mistake Hit rate on long-document exact retrieval
    FP4 quantization Reduces bits per element Precision loss; needs quantization-aware training Long-range dependency task scores
    Window replay Reduces resident GPU memory Adds reconstruction compute Decode throughput and per-token latency

    The source text gives several specific figures: global KV at about one quarter of the previous generation, persistent KV at about one eighth, and about 890 bytes per token. Since these figures do not specify model configuration, precision, sequence length, or measurement methodology, this article does not treat them as general conclusions. Readers should measure on their own models and record at least: bytes per token before and after compression, test sequence length, accuracy metrics (e.g., long-document localization tasks), TTFT, and TPOT (time per output token).

    5. Supporting Design at the System Level

    Compression is only the prerequisite. Production deployment also requires the following checklist.

    • Disaggregated prefill and decode deployment: The two stages have different bottlenecks. Prefill is compute-intensive; decode is bandwidth-intensive. They can be assigned to independent instance groups and scaled separately according to their own queue lengths.
    • Tiered KV storage: Keep the KV of hot sessions in GPU memory, recent sessions in host memory, and historical sessions in storage. The table below shows starting parameter examples, which need to be adjusted according to your workload