Consistency Design for Heterogeneous KV Cache in Long-Context LLM Inference

    This article explains why prefix cache reuse breaks in long-context LLM inference when models adopt hybrid attention, and how to restore correctness. It categorizes cache state into five types, upgrades the allocator and matcher to track cache shape and recoverability, and defines four layers of hit validation plus four non-negotiable consistency checks. Engineers will learn how to keep both performance and correctness in long-context serving.

    Consistency Design for Heterogeneous KV Cache in Long-Context LLM Inference

    1. Background: Why “Same Prefix” No Longer Means “Safe to Reuse”

    Prefix caching is a standard optimization in long-context inference serving. The traditional approach relies on paged attention: token history is split into fixed-size pages, a page table maps logical pages to physical GPU memory blocks, and requests with an identical prefix reuse existing blocks to skip redundant prefill. This assumption has run reliably on general-purpose inference frameworks for a long time, and it produced a widely accepted conclusion: a prefix hash hit means you can continue computing.

    A new generation of long-context models introduces hybrid attention, where different layers may use full-history compression, sliding windows, or sparse routing. This breaks the conclusion above. The reason is that the same token history is retained in a different “form” in each layer: some layers keep only a compressed summary representation, some keep only the most recent window, and some rely on reconstructable routing indices. As a result, the rule “same prefix → reuse cache directly” no longer holds.

    One principle must be stated first: hit rate is not a correctness metric. A hit only means “candidate blocks were found”; it does not mean “these blocks are sufficient for error-free continuation”. Treating hit rate as the primary signal of service health is the most common observability mistake in long-context serving.

    2. Five Cache States and Their Lifecycles

    The objects that must be explicitly tracked in a heterogeneous cache can be grouped into five types. Their lifecycles, recovery conditions, and hit criteria are completely different, so each must be modeled separately.

    1. Compressed KV: the compressed representation stored by full-history layers. Its lifecycle spans the entire sequence and stays valid as long as the sequence is active; recovery requires the compressed block to align strictly with the original token range.
    2. Uncompressed tail: the original KV kept to preserve near-range precision. Its length is limited, it slides forward as generation proceeds, and it cannot be reused while the tail is not yet “bound”.
    3. SWA window: sliding-window layers are valid only for the most recent W tokens. History beyond the window is meaningless to those layers, so hit criteria must include the window boundary.
    4. Indexer state: the indices and routing tables that sparse-routing layers depend on. If they are not synchronized, complete KV still cannot locate the blocks that should be read.
    5. On-disk prefix: history offloaded to external storage to break the GPU memory capacity limit. A hit requires migration back, and the data is in an “in-flight” state until that migration completes.

    An intuitive analogy: in an ordinary model, a cache hit is like looking up a shelf number and fetching the book directly. In a heterogeneous cache, after finding the number you must confirm five things: whether the book is on the shelf (compressed KV), whether the latest pages are bound (tail), whether the borrowing card has expired (SWA window), whether the index catalog is synchronized (indexer state), and whether the book was sent to a suburban warehouse and has not been returned (on-disk prefix). Only when all five are confirmed recoverable can you truly continue reading.

    3. Allocator and Matcher: From “Finding a Free Block” to “Recording the Form”

    A traditional allocation action only picks a free GPU memory block for new tokens to write into; a parallel matching action reports hits by hash. Once cache objects become heterogeneous, both actions must be upgraded:

    • The allocator must record the current form of each token segment (which state type it belongs to, which lifecycle stage it is in), not just the physical address.
    • The hit reported by the matcher must carry a recoverability conclusion; otherwise a downstream stage that trusts the hash hit and then reads data missing the tail, the window, or the routing will silently produce wrong output.

    Illustrative pseudocode:

    1. class Block:
    2. token_range: tuple[int, int]
    3. kind: str # compressed / tail / swa / indexer / ondisk
    4. state: str # ready / partial / inflight
    5. layer_group: int
    6. def match(prefix_hash) -> Hit:
    7. cands = hash_table.get(prefix_hash)
    8. for b in cands:
    9. if recoverable(b): # key point: not just hash equality
    10. return Hit(b)
    11. return Miss()
    12. def alloc(tokens, kind):
    13. b = free_list.take()
    14. b.kind, b.state = kind, "partial"
    15. record(tokens, b)
    16. return b

    4. Four Layers of Hit Validation

    To decide whether a prefix hit can really be used for direct continuation, it is recommended to stack four layers of validation:

    1. Whole-block alignment check: a compressed block must cover the corresponding token range as a whole; stitching half blocks is not allowed.
    2. Kernel consistency check: the operator version used when writing to the cache must match the current inference operator version, to avoid numerical semantics drift.
    3. Multi-cache-group state intersection: hybrid attention has multiple cache groups, and a hit must take the intersection of the states of all groups; if any group is unsatisfied, it degrades to a partial hit.
    4. Byte-level hardware alignment: the byte layout and alignment of a physical block must match the current device, otherwise reads are misaligned after migration back.

    5. Four Non-Negotiable Consistency Checks

    1. Admission limit: set an upper bound on the cache and migration bandwidth a single request can occupy, to prevent long-context requests from crowding out shared resources.
    2. Five-state routing: route different state types through different recovery paths; a single unified rule must not be used for all of them.
    3. Timing consistency between check and use: state may change between hit determination and actual read, so a version number or state pointer is needed to avoid “available at check time, already invalid at use time”.
    4. Static topology constraint: if graph-capture-based execution optimization is used, the cache topology must stay static; dynamic form changes must fall back to the regular execution path.

    6. Engineering Recommendations

    • Observability: display hit rate alongside “recoverable hit rate”, “degradation rate”, and “migration wait time”, to avoid being misled by a single metric.
    • Capacity: use object storage to carry on-disk prefixes, use a message queue to decouple migration tasks, and use a container platform to host elastic inference replicas.
    • Operations: use logging services and monitoring alerts to collect the five state types by dimension; when “high hit rate but abnormal output” appears, prioritize checking the state intersection and timing consistency.
    • Rollout: first run with partial-hit degradation, verify correctness, then gradually increase the reuse ratio.

    7. Conclusion

    Long context and hybrid attention move the caching problem from “space reuse” to “state consistency”. What engineering must truly guarantee is not the hit rate number, but that every hit can be proven recoverable. Only by fixing the five states, four validation layers, and four checks into the allocator and matcher logic can long-context scenarios achieve both performance and correctness.