Heterogeneous KV Cache Consistency Design for Million-Token Long-Context Inference

    This article examines why prefix cache hit rate is a misleading metric in million-token long-context inference, where hybrid attention breaks the assumptions behind traditional paged KV caches. It covers the state representation required by the allocator, the lifecycle and recovery conditions of five cache object types, a four-layer hit validation scheme, and practical recommendations for observability and regression testing. Readers will learn how to turn prefix reuse from apparently faster into verifiably correct.

    1. Where the Problem Starts: Hit Rate Is a Misread Metric

    In long-context inference serving, the prefix cache hit rate is often reported as the core optimization metric. But a hit rate only describes whether a lookup succeeded; it says nothing about whether what was found can be used directly. When a model has a single attention pattern, those two questions are roughly equivalent. Once you move to million-token contexts, where hybrid attention becomes the mainstream engineering choice, that equivalence breaks.

    A typical hybrid attention design mixes three mechanisms across different layers: a compressed representation over the full history, a local sliding window, and sparse routing selection. The three preserve historical information in completely different ways, so the same logical prefix maps to a different physical state in each layer. The long-standing assumption that “an identical prefix can simply be reused” no longer holds. After a hit, generation can still go wrong because the state is incomplete, and such failures tend to be intermittent, hard to reproduce, and only weakly correlated with input length, which makes them very expensive to diagnose.

    This article discusses the general design problems of such systems from a neutral perspective and does not refer to any specific vendor implementation.

    2. Why Traditional Paged Cache Assumptions Fail

    Inference frameworks in common use generally adopt a paged key-value cache: token history is split into fixed-length pages, a page table maps them to physical blocks, and requests with identical prefix hashes share physical blocks directly. This mechanism has worked for years, resting on three implicit assumptions: uniform block granularity, self-contained block contents, and a block lifecycle determined solely by reference counting.

    Hybrid attention breaks all three. On granularity, compressed representations are usually organized in larger aggregation units. On self-containment, local windows and sparse routing need extra metadata to be reconstructed. On lifecycle, cold prefixes offloaded to external storage must be migrated back asynchronously, which introduces a time window. As a result, the allocator cannot merely “find a free block”; it must record the current form of every token segment.

    Schematically, the state record can be abstracted as:

    1. @dataclass
    2. class SegmentState:
    3. seg_id: int
    4. kind: str # compressed / tail / swa / indexer / ondisk
    5. valid_range: tuple # logical token range
    6. ready: bool # whether recovery has completed
    7. epoch: int # state version, used for invalidation

    The allocation path and the matching path must share the same state source. Otherwise the matching stage reports a hit by hash while the read stage finds missing data, and the error only surfaces midway through decoding.

    3. Lifecycle and Recovery Conditions of the Five Cache Object Types

    The first type is compressed key-values, which cover the full history at the coarsest granularity. Generating a new token requires incrementally updating the aggregated representation, and recovery requires the aggregation block to be complete and version-consistent. The second type is the uncompressed tail, which stores exact representations of the most recent tokens to preserve near-range precision; recovery requires the tail to be contiguous with no holes. The third type is sliding window state, valid only within the window; once the window slides, the old state is naturally invalid, and recovery requires the window boundary to align with the current decoding position. The fourth type is indexer state, which serves candidate selection for sparse routing; recovery requires the index to be built in sync with the main cache. The fifth type is the external-storage prefix, which trades capacity for latency and requires asynchronous migration back plus a completion signal.

    An analogy helps: finding the shelf number is only the first step. You still need to confirm the book is on the shelf, that the latest pages are bound in, that the borrowing card has not expired, that the index catalog is in sync, and that the book has not been sent to a suburban warehouse and is still on its way back. Only when all five are confirmed can you truly continue reading.

    4. Allocator State Machine and Four-Layer Hit Validation

    The state machine needs to be modeled explicitly: an admission limit controls the number of concurrent prefixes to avoid metadata explosion; the five state types are routed to determine which recovery path applies; the check and the execution must be atomic to prevent state drift caused by a time gap; and because static graph execution requires a fixed topology, state pointers must be determined before graph capture.

    Four layers of validation are recommended for hit determination: validate aggregation blocks at whole-block granularity, keep the compute kernel consistent with the version contract, take the intersection of state across multiple cache groups, and perform a byte-level alignment check. If any layer fails, the request should degrade to a partial hit or a recomputation rather than continue reusing the state.

    5. Engineering Recommendations

    First, split the hit rate into two separately observed metrics: match hit rate and reusability rate. Second, establish a unified version number and an invalidation propagation mechanism for the five state types. Third, during canary rollout, build a regression set from long inputs that covers window sliding, offload migration back, and concurrent sharing. Fourth, use container platforms, logging services, and monitoring alerts to build end-to-end tracing that pins state anomalies to a specific stage. In related practice at Baidu AI Cloud, such long-context services are typically hosted on a container platform, with logging and monitoring capabilities providing state-level observability.

    6. Conclusion

    The real difficulty of million-token context is not compute but state consistency. Making cache objects explicit, formalizing recovery conditions, and layering hit validation is what turns prefix reuse from “seemingly faster” into “verifiably correct.”