Restructuring KV Cache Costs for Million-Token Contexts

    As AI agents take on long-horizon tasks, the bottleneck of long context is shifting from compute to the key-value (KV) cache. This article breaks down cache costs into capacity, bandwidth, scheduling, and training, and explains three optimization paths: redesigning attention architectures for smaller caches, compressing and reusing caches through quantization and prefix sharing, and treating the cache as a first-class resource in inference scheduling. It also covers observability metrics, the real limits behind "wish-style" one-shot code generation, and a practical adoption checklist.

    1. Why the Long-Context Bottleneck Is Shifting from Compute to Cache

    Over the past two years, most discussions about long context focused on “how much can fit”—that is, the maximum context window a model supports. But once agents began handling real tasks, the question quickly became “does it still run fast enough, and can we afford it after everything is stuffed in?” A long-horizon agent that makes repeated tool calls and keeps reading documents and code repositories can easily accumulate a history beyond one million tokens in a single session. At that point, the resource under real pressure is no longer the floating-point operations of matrix multiplication, but the key-value cache that every layer must store, reuse, and move around.

    The cost can be broken down into four parts:

    • Capacity cost: the KV cache grows linearly with sequence length, while the number of layers, attention heads, and head dimension jointly determine the cache size per token.
    • Bandwidth cost: generating each new token requires reading the entire history cache again, making memory bandwidth the main constraint during decoding.
    • Scheduling cost: multi-turn sessions, parallel requests, and prefix sharing turn cache allocation, reuse, and recycling into a complex resource management problem.
    • Training cost: the attention overhead and memory footprint of long-sequence training determine whether a model can be adapted for long context within an acceptable budget.

    Sparse attention only addresses the compute portion of the first item; the global cache still has to be stored and moved over the long term. The right approach to long-context optimization is therefore to “systematically rewrite the cost curve” rather than tune a single knob. In practice, three paths are usually advanced in parallel: redesigning the attention structure to shrink the cache itself, compressing and reusing the cache to reduce data movement, and reworking the inference system to improve cache hit rates and throughput.

    2. Architecture Layer: Making the Cache Inherently Smaller

    The first path subtracts from the model structure. Mainstream approaches in the industry include: using fewer but wider attention heads to reduce the number of cache heads; adopting grouped-query attention so that multiple query heads share the same set of key-value heads, shrinking the cache to a fraction of its original size; introducing a hybrid layout of sliding-window and global attention, so that the vast majority of tokens only participate in computation within a local window while a small number of global tokens carry cross-segment information; and sharing caches across layers to avoid repeatedly storing similar representations.

    These changes come at a cost. Local windows weaken the precision of long-range dependencies, and shared caches may reduce representational capacity. As a result, they usually need to be combined with position-encoding extrapolation strategies and continued pre-training on long text to keep the model stable on extremely long inputs. To judge whether an architectural change is worthwhile, three metrics are recommended: cache bytes per token, accuracy on long-document retrieval tasks, and per-token latency during decoding.

    The trade-offs of a representative structure can be expressed as follows:

    1. Cache size ≈ layers × KV heads × head dimension × sequence length × bytes per value
    2. Optimization directions: fewer KV heads, smaller head dimension, lower precision, shorter effective sequence length

    3. Cache Layer: Compression, Quantization, and Prefix Reuse

    The second path compresses the existing cache without changing the structure. There are three common techniques. The first is quantization, which lowers the cache from half precision to a smaller bit width, trading controllable accuracy loss for a multiple gain in capacity. The second is sparsification and eviction, which uses attention scores to decide which history entries are worth keeping, turning “store everything” into “keep by importance.” The third is low-rank or latent representation compression, which projects the keys and values into a lower-dimensional space for storage and restores them when needed.

    Reuse is more cost-effective than compression. Real agent workloads contain a large amount of repeated prefixes: the same system prompt, the same code repository context, and the same long document are fed into the model over and over. Stably retaining the cache of these prefixes and sharing it across requests can significantly dilute the cost of each individual request. In practice, pay attention to the design of the cache key: include the model version, prompt template, and tool definitions in the key to avoid a sharp drop in hit rate caused by version drift.

    1. # General design idea for a prefix cache key (illustrative)
    2. def cache_key(model_ver, system_prompt, tools_schema, doc_hash):
    3. return hash((model_ver, system_prompt, tools_schema, doc_hash))
    4. # On a hit, skip prefix prefill and only compute the new content incrementally

    4. System Layer: Scheduling the Cache as a First-Class Citizen

    The third path is often underestimated: whether the inference system treats the cache as a manageable resource. High-throughput serving usually requires a multi-tier cache hierarchy—a high-bandwidth cache inside the device, a memory pool on the host side, and a persistence layer based on object storage or a distributed file system—forming tiers from fast to slow. The request scheduler must be cache-aware and preferentially route requests to instances that already hold the corresponding prefix; the batching strategy must trade off throughput against time-to-first-token; and the eviction strategy must dynamically balance memory pressure against reuse gains.

    Observability is equally critical. At a minimum, collect four metrics: cache hit rate, cache eviction rate, the share of time spent in the prefill stage, and cache bytes read per request. Without these metrics, it is hard to verify whether any cost-reduction measure actually works. In terms of deployment, if a container platform hosts the inference service, you can combine monitoring, alerting, and logging services to establish a baseline, then gradually roll out new cache strategies.

    5. Capability Boundaries: The Real Constraints Behind the “Wish-Style” Experience

    Recently, many developers have found that by simply describing requirements in natural language, a model can produce fairly complex interactive programs—such as runnable 3D scenes or racing-style mini-games—in one shot, an experience that feels like “wishing and it comes true.” This leap in experience mainly comes from three overlapping factors: long context lets the model hold the requirements, constraints, and reference code at the same time; cache and scheduling optimizations make the cost of multiple iterations affordable; and reinforcement during training on interactive programs and tool calls has clearly raised the probability of getting it right in one pass.

    But the boundaries must be stated clearly. First, generating complex programs in one shot still depends on how clearly the requirements are described, and the rework rate remains high under vague requirements. Second, an extremely long context is not the same as lossless memory; the position of key information and the amount of distracting content both affect retrieval accuracy. Third, cache compression and quantization may cause quality fluctuations in low-resource scenarios and need A/B validation per business. Fourth, pricing, quotas, and deployment thresholds are operational matters and should be based on official announcements rather than third-party accounts when planning capacity.

    6. Adoption Checklist

    • Establish a baseline first: measure the context-length distribution and prefix repetition rate of real sessions to determine whether the bottleneck is compute or cache.
    • Then choose a path: structural redesign offers the largest gains but takes the longest, cache compression comes next, and system scheduling shows results fastest, so they can be pursued in parallel.
    • Validate with metrics: use hit rate, time-to-first-token, and cost per request as a unified acceptance standard.
    • Keep a fallback: any cache strategy should support one-click rollback to avoid quality fluctuations caused by version upgrades.
    • Pay attention to compliance: long context involves more data residency, so data lifecycle and access control policies must be defined.

    Overall, the competition in long context has shifted from “how large is the window” to “how low is the cost per token.” Reconstructing the attention structure, cache representation, and inference scheduling as a whole is the key to making million-token contexts truly usable—and the smooth experience of “wish-style programming” is the natural result of this systematic optimization at the application layer.