Heterogeneous KV Cache Consistency Design for Long-Context Inference
This article explains why traditional prefix caching breaks in long-context, mixed-attention LLM inference and presents a consistency design based on five distinct cache state types. It covers separating the allocator and matcher responsibilities, a four-layer hit verification process, four state machine constraints, and practical deployment guidance for tiered caching and observability. Readers will learn how to treat KV cache as a correctness component rather than a pure performance optimization, avoiding silent quality degradation caused by incomplete or mismatched cache states.
1. The Starting Problem: Why Prefix Reuse Fails in Long-Context Scenarios
In inference serving, prefix caching has long been treated as a pure performance optimization. A high hit rate means duplicate prefill work is avoided; a low hit rate merely wastes compute and does not affect output correctness. This assumption largely holds for traditional dense attention models, because the key-value state for any segment of token history is self-contained. As long as the hash matches, the entire segment can be moved over and reused for further computation.
However, once the context length reaches the million-token scale and the attention structure becomes a mix of multiple mechanisms, this assumption is no longer safe. The cache is no longer a single object but a collection of states with different shapes, lifecycles, and recovery conditions. A hash hit only proves that the token sequence is identical; it does not prove that all states corresponding to that sequence are ready. If downstream computation simply resumes based on the hit result, hidden errors such as a missing tail, a missing window, or missing routing indices can occur. These errors usually do not throw exceptions. They only show up as degraded generation quality or semantic drift, making them extremely difficult to diagnose.
Therefore, long-context inference serving must elevate the cache from a performance optimization to a correctness component in its design.
2. Five Cache State Types: Shape, Lifecycle, and Recovery Conditions
A heterogeneous cache must explicitly track at least the following five types of objects, each with independent decision logic:
- Compressed KV history: Produced by the full-history compression path, typically at block granularity. Recovery depends on the complete placement of compressed blocks.
- Uncompressed tail: The most recent tokens are kept at original precision. Its length varies with configuration, and recovery requires the tail to be contiguous and not evicted.
- SWA window: Valid only within a fixed window. History outside the window does not participate in computation, and recovery requires the window to cover the current generation position.
- Indexer state: The indices and selection results required for sparse routing. If this state is out of sync with the history, requests may be routed to the wrong subset.
- On-disk prefix: A prefix swapped out due to insufficient GPU memory. After a hit, it must be asynchronously migrated back, creating an intermediate state of “hit but not ready.”
From an engineering perspective, it is recommended to define a unified state descriptor structure for each type of object, making four fields explicit: whether it exists, whether it is complete, whether it is restorable, and the recovery cost. Do not express this with a single boolean hit flag:
# Illustration: cache block descriptor (not tied to a specific implementation, only expressing design points)class BlockDesc:token_range: tuple[int, int]kind: str # compressed / tail / swa / indexer / diskcomplete: bool # whether the block is fully placedrestorable: bool # whether recovery conditions are metrestore_cost: int # migration or recomputation cost, used for scheduling decisions
3. Separating the Allocator and the Matcher
A traditional allocator does only two things: find free blocks to write new tokens, and compute hashes for existing prefixes to match them. Under a heterogeneous cache, both responsibilities must be extended.
On the allocation side, the current shape of each token segment must be recorded; otherwise, it becomes impossible to determine later whether a segment is in compressed or original form. On the matching side, the matcher cannot return only the hit length. It must also return the set of states for the matched segment and hand the decision to a verification layer. The following pseudocode is usable:
def match_prefix(tokens):hit_len, states = hasher.match(tokens) # only indicates the sequence is identicalif not verify(states, tail_pos=len(tokens)):return 0, {} # fall back to a miss and recomputereturn hit_len, states
The key principle is: separate matching from verification, and treat a verification failure as a miss. It is better to compute more than to compute incorrectly.
4. Four-Layer Hit Verification
- Block-granularity alignment verification: A compressed block must be available as a whole block. A partial block is treated as unavailable.
- Operator and binary interface consistency verification: Different attention paths require different state layouts. Mixing across versions must be rejected.
- Multi-cache-group state intersection verification: Under mixed attention, multiple groups of states must be intersected. If any group is missing, the whole entry is unavailable.
- Byte-level hardware alignment verification: Before reuse across devices or precisions, alignment and layout consistency must be confirmed.
5. Four State Machine Constraints and Consistency Checks
- Admission cap: Limit the number of concurrent swap-in and swap-out tasks to avoid a migration storm.
- Five-way state routing: Route each object type through a different recovery path. Unified handling is prohibited.
- Timing consistency between checking and use: Add a lock or version number between hit determination and state reading to prevent the state from being evicted before it is read.
- Static topology constraint: If graph-capture-based execution optimization is used, dynamic migration must not change the already-captured static shapes.
6. Implementation Recommendations
Build a tiered cache on container platforms and object storage, use monitoring and alerting to track three curves: hit rate, fallback rate, and recomputation time, and retain state snapshots in the logging service for later review. If you use relevant general capabilities from Baidu AI Cloud, they can serve as the foundation for cache tiering and observability, while the cache state machine itself still needs to be built within the inference framework.
