KV Cache Optimization for Million-Token Context Agents: Architecture, Cache, and System Design
This article breaks down a practical approach to KV cache optimization for long-horizon agents with million-token context windows. It explains why the bottleneck has shifted from attention computation to KV cache capacity, transfer, and lifecycle management, then walks through three coordinated layers: a causal encoder-decoder architecture that splits a 40-layer backbone into two 20-layer modules, a cache stack combining context encoding compression, sparse/sliding-window attention, low-precision primary cache, and bounded replay, and system-level practices for capacity planning, batching, cache reuse, and observability. It also covers precision fallback, cache lifecycle management, capability boundaries, and four evaluation metrics for validating whether compression actually improves concurrency, latency, and throughput without hurting accuracy.
1. Problem Definition: The Bottleneck in Long-Horizon Agents Has Shifted
Before discussing any optimization approach, it is worth fixing the problem boundary. Early long-context research focused on “how fast is the computation”—that is, whether the complexity of attention could be reduced from quadratic. Sparse attention, sliding-window attention, and linear attention do significantly cut floating-point operations, but in real workloads like agents, the bottleneck quickly moves elsewhere.
The reason is that an agent’s behavior pattern is completely different from one-shot long-document question answering:
- Context grows continuously: multi-turn tool calls keep appending retrieval results, page content, and log fragments to the context;
- History is reused repeatedly: the same system prompt, tool definitions, and already-read documents are read again in every subsequent turn;
- Every step requires re-decoding: reasoning and planning are generated token by token, and the decode phase is extremely sensitive to bandwidth.
Put together, the real cost center becomes the capacity, movement, and lifecycle management of the KV cache. The larger the cache, the more GPU memory it occupies and the fewer concurrent sessions you can run; the longer the cache, the more bytes each attention read must move, and decode throughput is easily bottlenecked by memory bandwidth. Therefore, a usable long-horizon solution must reduce three types of cost at the same time: compute cost, storage cost, and transfer cost. Optimizing only one of them usually gets punished on another.
2. Specs First: Anchor Every Design Tradeoff with a Set of Constraints
A common engineering mistake is to discuss mechanisms first and add metrics later, which makes it impossible to tell whether an optimization actually works. A safer approach is to fix a set of verifiable specs first, then let the mechanisms satisfy them. A typical target shape can be abstracted as:
- The backbone is a mixture-of-experts (MoE) architecture with parameter counts in the hundreds of billions;
- An additional conditional memory module is attached to carry reusable long-term knowledge, and is not counted in the backbone parameter budget;
- The context window limit reaches the million-token level;
- Input supports mixed text and images, and output is autoregressive text generation;
- Encoding and decoding use asymmetric activation: the number of parameters activated per token during prefill is significantly smaller than during decode.
The last point is often overlooked but very important. Prefill is compute-intensive and parallelizable; decode is memory-access-intensive and serial. The two phases have different resource profiles, and optimizing both with the same activation size inevitably wastes one and starves the other. Asymmetric design lets each phase approach its own optimal operating point.
On the cache side, the target can be quantified as: compress the global KV to hundreds of bytes per token, roughly a quarter of the previous generation, and reduce the persistent cache to about one-eighth. With these numbers in place, every mechanism below can be validated or falsified.
3. Architecture Layer: Split the Network Along Depth into Encoder and Decoder
The mainstream approach moves from a pure decoder-only structure to a causal encoder-decoder form: split the 40-layer backbone evenly along depth into two 20-layer modules, where the front segment reads the full prompt only during prefill, and the back segment no longer looks back at the full history layer by layer.
The mechanism can be understood like this:
Input prompt x_1 ... x_n↓ First 20 layers: causal encoder (runs only in the prefill phase)Final hidden state H_20├─ Linear projection → global KV entries C^l (one set of weights per decode layer)├─ Linear projection → compression weights Z^l└─ Combined with the most recent n_win tokens → reconstruct local sliding-window KV↓ Last 20 layers: decoder (generates token by token)Output
The global representation of the l-th decode layer can be expressed as:
C^l = H_20 · W^l_KV # global KV entriesZ^l = H_20 · W^l_Z # compression weights
The direct benefit is that prefill complexity drops from O(N·L) to roughly O(N·L/2 + n_win·L/2). When the context length N is much larger than the window n_win, prefill computation is nearly halved. A deeper benefit is representation reuse: the full prompt only needs to be “understood” once, its semantics are fixed in H_20, and all subsequent decode layers draw on it through lightweight projections instead of each rereading the raw tokens. For agent scenarios, this means the encoding cost of high-reuse content such as system prompts and tool definitions is amortized to nearly zero.
4. Cache Layer: Stack Four Techniques Rather Than Rely on a Single Trick
Compression is not done by one trick. Instead, four types of techniques stack across different dimensions, each attacking a different source of waste:
- Context encoding compression: map the raw token sequence into a more compact representation to reduce the number of entries;
- Sparse/sliding-window attention: keep full precision within the local window, and retain only summary-style representations outside it;
- Low-precision primary cache: store the global KV at around 4 bits, trading precision for capacity;
- Bounded replay: roll and recompute sliding-window content under a fixed upper bound to avoid unbounded window growth.
The relationship among the four is multiplicative, not additive. Lowering precision alone causes accuracy loss; adding sparsity alone still keeps a large number of entries; replay alone cannot compress global semantics. Only when stacked can the global KV fall to hundreds of bytes per token while pushing the persistent cache to a lower level.
Two supporting pieces are needed in engineering. The first is a precision fallback strategy: keep higher precision for numerically sensitive layers or channels with obvious outliers to avoid accumulated quantization error. Sketch of the logic:
def pick_dtype(layer, kv_stats):# Keep high precision for layers with abnormal value distributions or in sensitive positionsif layer in SENSITIVE_LAYERS or kv_stats[layer].outlier_ratio > 0.05:return "fp16"return "fp4"
The second is cache lifecycle management: distinguish three classes of cache—“discardable,” “compressible,” and “must persist”—and combine them with prefix reuse so that the same system prompt shares the same cache page across multiple sessions.
5. System Layer: Make Algorithmic Gains Actually Land in Throughput
Even the best compression scheme will have its gains eaten by the system if scheduling is poor. At deployment, at least four issues must be handled:
- Capacity planning: estimate GPU memory needs as “bytes per token × context length × concurrent sessions,” leaving headroom for fragmentation and temporary buffers;
- Batching strategy: when prefill and decode are mixed in a batch, long-context requests easily block short ones, so tiered queues or disaggregated deployment are needed;
- Cache reuse: prefix-tree matching turns the cache of common prefixes into hits and reduces repeated prefill;
- Observability: instrument cache hit rate, bytes moved per step, time to first token, and decode-phase throughput separately, so you can tell whether the bottleneck is compute or bandwidth.
In a cloud implementation, it is common to combine a container platform to host inference services, object storage to hold models and long-cycle session snapshots, a message queue for request tiering and peak shaving, and logging plus monitoring/alerting to cover the metrics above. The emphasis here is on general capability categories; specific choices should be decided by load-testing results for your own workload.
6. Capability Boundaries and Evaluation Recommendations
The boundaries must be stated honestly. The encoder-decoder split relies on the premise that “history can be encoded in one pass,” so for tasks that require exact token-by-token backtracking over very long histories, the compressed representation may cause information loss; low-precision cache carries similar risk for numerically sensitive tasks; and a million-token context is an upper limit, not a default operating point—beyond the effective window, gains diminish while costs rise linearly.
When evaluating this kind of solution, it is recommended to fix four comparisons: maximum concurrent sessions on the same hardware, time to first token for long context, per-token time in the decode phase, and accuracy change on the target task. Only when all four do not degrade can the compression be considered truly successful. Ultimately, the core insight of long-context optimization is that the goal is not to save GPU memory, but to shift all three cost curves—compute, storage, and transfer—downward at the same time. This requires coordinated design across the architecture, cache, and system layers, not any single-point trick.
