KV Cache Optimization for Million-Token Contexts: A System-Level Approach

    This article explains why KV Cache becomes the bottleneck when agent workloads scale from thousands to millions of tokens, and how to address it across three layers: architecture, caching, and system design. It covers attention variants, external memory, single-pass structures, cache compression, reuse and eviction, tiered storage, scheduling, and observability, along with current capability boundaries and a staged rollout plan for reducing cost per token.

    1. Why Long Context Starts With Caching

    When AI agents take on long, multi-step tasks, context length often grows from a few thousand tokens to the million-token range. Model size is only a surface metric. What actually determines whether a system can ship is the key-value cache (KV Cache), which is read and written repeatedly on every inference pass. Its size scales with sequence length, number of layers, and number of attention heads, so under long context and high concurrency it squeezes GPU memory capacity, memory bandwidth, and scheduling headroom at the same time.

    The resulting cost structure has three parts:

    • Prefill computation before the first token is produced.
    • Read bandwidth consumed by traversing the entire cached history for every generated token.
    • Duplicate cache occupancy caused by multi-turn conversations and tool calls.

    The engineering goal is usually defined as reducing the number of cache bytes and cache accesses per token without a noticeable loss in quality.

    2. Architecture: From Attention to Conditional Memory

    The first lever is the attention structure. Common approaches include grouped-query attention, sliding windows, and sparse attention. They share the same objective: each query no longer has to interact densely with every historical key-value pair. Replacing dense attention with a sparser, more localized variant (the attention upgrade referred to in the source material falls into this category) can bring complexity on long sequences down from quadratic to close to linear.

    The second lever is conditional memory. Part of the factual, reusable knowledge is moved out of the context window and turned into external memory that is retrieved on demand, so the backbone network only keeps fragments strongly related to the current subtask. The effect is equivalent to trading lookup for computation, at the cost of adding a retrieval path and consistency maintenance.

    The third lever is single-pass structure. In conventional designs, some modules need multiple forward passes or deep iteration to converge. With a single-pass design, latency becomes more predictable and the module is better suited to being treated as a concurrent execution unit by an upper-level scheduler.

    One point deserves emphasis: backbone parameters and external memory parameters should be counted separately. Summing the two produces a total parameter count that does not equal the compute actually activated per forward pass, which is the most common misreading when evaluating this class of models.

    3. Cache Layer: Compression, Reuse, and Eviction

    Cache optimization reduces to three orthogonal paths.

    • Compression: low-rank projection of keys and values, quantization (8-bit or lower), or importance-based pruning, all of which cut byte count directly.
    • Reuse: requests sharing an identical prefix share the same cache. Typical cases are a fixed system prompt, fixed tool definitions, and repository context.
    • Eviction: a retention policy for historical fragments, where content outside the sliding window is downgraded or dropped based on relevance.

    A sketch of the cache key design follows. The core idea is to include the reusable prefix in the key so prefill is not repeated:

    1. def cache_key(model, prefix_tokens, tools_schema, quant_bits):
    2. h = hashlib.sha256()
    3. h.update(prefix_tokens) # stable prefix: system prompt, repo notes
    4. h.update(tools_schema) # any tool definition change must invalidate
    5. h.update(f"{quant_bits}".encode())
    6. return h.hexdigest()

    One engineering caveat: quantization changes the numerical distribution, so hit-rate metrics must be tracked alongside quality evaluation. Otherwise a silent regression appears in which hit rate goes up while answer quality goes down.

    4. System Layer: Scheduling, Tiered Storage, and Observability

    Once a single request’s cache reaches tens of gigabytes, the problem shifts from algorithms to systems.

    1. Tiered storage: hot data stays in GPU memory, warm data moves down to host memory, cold data lands in object storage or a distributed cache, with migration driven by access frequency.
    2. Batching and scheduling: split prefill and decode into separate batches so long requests do not block short ones; set timeouts and concurrency limits for tool calls.
    3. Elastic scaling: the container platform scales inference replicas by queue length, message queues absorb traffic spikes, and logging plus monitoring track time to first token, cache hit rate, and cost per token.
    4. Asynchronous subtasks: the main agent hands retrieval, validation, and similar subtasks to faster execution units, reducing how long attention stays occupied.

    5. Capabilities and Limits

    Long context does not mean effective context. Retrieval tasks, cross-file code understanding, and multi-turn tool orchestration are relatively mature today. Global reasoning over very long documents, strict numerical computation, and strongly constrained format output still need external validation as a fallback. Evaluation should report quality, time to first token, throughput, and cost per million tokens together; a ranking on a single dimension is not enough to support a selection decision.

    6. Practical Recommendations

    Start with stable prefixes and cache reuse to capture deterministic gains, then introduce quantization and sparse attention, and only then consider external memory and custom scheduling. Build a rollback-capable evaluation baseline at each step, turning cost reduction into a measurable, reproducible engineering process rather than a one-off round of parameter tuning.