Rebuilding State Caching for Hybrid-Architecture LLMs: Prefix Cache Practices
This article examines why conventional prefix caching breaks down for hybrid LLMs that interleave full attention layers with linear or state-space layers, where the cache contains both growing key-value blocks and fixed-size recurrent state snapshots. It explains the four main failure modes—state that cannot be chunked, mismatched hit and compute granularity, unbalanced memory hierarchy, and scheduling conflicts—then presents a redesign built on four principles: separate pools with unified addressing, aligned hit granularity, tiered capacity governance, and continuity-first scheduling. Engineering details, validation methodology, and the sources of the performance gains are covered for readers optimizing prefill on long-context, high-prefix-repetition coding workloads.
1. Background: New Bottlenecks Once Hybrid Architectures Go Mainstream
In the open-source LLM designs of the past two years, linear attention and state-space layers—incremental linear attention variants, gated recurrent structures, structured state-space sequence models—have been introduced in large numbers and stacked alternately with standard full attention layers, forming a hybrid “full attention + linear layers” structure. The motivation is clear: full attention layers preserve precise long-range retrieval, while linear layers replace the ever-growing key-value cache with a fixed-size recurrent state, reducing GPU memory usage and improving decode-phase throughput.
But the nature of the problem changes when the workload shifts from “single-turn question answering” to “multi-turn sessions of AI coding tools.” Coding workloads are characterized by very long system prompts and project context, code snippets and tool-call results that keep accumulating each turn, and prefixes that are highly repetitive within the same session. Here, system performance is no longer determined by decode speed but by the hit rate and reuse efficiency of the prefix cache—that is, by the prefill phase.
For pure attention models, the cache object is homogeneous key-value tensors that can be chunked, indexed by hash, and transferred across nodes. For hybrid models, the cache object is heterogeneous: part of it is key-value blocks that grow linearly with sequence length, and part is fixed-length recurrent state snapshots. The two kinds of objects differ completely in lifecycle, chunkability, and portability. Reusing cache strategies designed for pure attention therefore produces severe fragmentation and duplicated computation.
2. Why Traditional Prefix Caching Fails
2.1 State Cannot Be Chunked
A key-value cache can naturally be split into blocks of a fixed number of tokens, and any prefix can be addressed precisely. A recurrent state is a global summary in matrix or vector form; it corresponds to the overall semantics “from the beginning to the current position” and cannot be broken into independent small blocks for separate reuse. If caching happens only at block boundaries, the state can only be rolled forward again from the most recent hit point.
2.2 Mismatched Hit Granularity and Compute Granularity
Two requests may share 90% of a prefix, but the shared length is not an integer multiple of the block size. For a pure attention model, the unaligned remainder only requires computing a small amount of additional key-values; for a hybrid model, misalignment means the state must be recomputed in full, and most of the benefit is consumed.
2.3 Unbalanced Memory Hierarchy Design
State is small in size and high in reuse value, so it belongs in the fastest tier; key-value blocks are large and chunkable, so they belong in tiers with large capacity but higher latency. If both are placed in the same cache pool with the same eviction policy, the frequently reused state gets pushed out by large key-value blocks, creating a negative feedback loop where things get slower the more they are computed.
2.3 Scheduling and Batching Conflicts
Prefill is a compute-intensive operation. Splitting a long prefix into many small blocks and interleaving other requests amplifies kernel launch overhead, leaves matrix multiplications undersized, and lowers GPU memory bandwidth utilization, so actual throughput ends up lower than a single continuous computation.
3. Redesign: Treating State as a First-Class Cache Object
The core design principles can be summarized in four points: separate state from key-values, align hit granularity, govern capacity in tiers, and prioritize continuous computation in scheduling.
3.1 Pool Separation with Unified Addressing
Maintain two logical cache pools, each with its own index and eviction policy, but bind them at the session level through a unified prefix fingerprint, so a single lookup determines “where the key-value hit ends and where the state hit is.”
# Example: prefix hit resolution and reuse point selectiondef resolve_reuse_point(prefix_tokens, kv_pool, state_pool):kv_hit = kv_pool.longest_prefix(prefix_tokens) # block-level hitst_hit = state_pool.lookup(prefix_fingerprint(prefix_tokens))# Key: take the nearest position where both can be aligned, avoiding a full state recomputereuse = align_down(min(kv_hit.end, st_hit.position), BLOCK)return reuse, kv_pool.slice(reuse), state_pool.get(st_hit.id)
3.2 Checkpoints and Incremental Rollback
Write state snapshots (checkpoints) periodically at several fixed positions along a long prefix, and keep incremental records for a small number of “rolling intervals.” When the hit length falls between two checkpoints, roll forward from the nearest checkpoint instead of starting from zero. Checkpoint density must trade off write overhead against rollback length, and can be adjusted adaptively based on session length.
3.3 Tiered Caching and Hot/Cold Separation
A three-tier structure is recommended: a GPU memory tier holding the state and hot key-value blocks of currently active sessions; a host memory tier holding session-level state snapshots and warm key-value blocks; and an external cache or distributed storage tier holding cold data shared across sessions and nodes. Because state is small, it should stay in the higher tiers preferentially, while key-value blocks migrate between tiers at block granularity. For capacity governance, evict state based on session activity and use block-level LRU for key-values, so the two do not squeeze each other out.
3.4 Continuity at the Scheduling Layer
Group requests by the “longest reusable prefix” whenever possible, and schedule multiple turns of the same session together to reduce state switching; align the prefill chunk size with the cache block size so that each incremental computation exactly fills one cacheable unit and no tail fragmentation is left behind.
4. Implementation Notes
- Fingerprints and validation: The prefix fingerprint must include the model version, weight identifier, position offset, and sampling configuration to prevent incorrect reuse across versions; after a hit, perform sampling validation to prevent hash collisions from polluting semantics.
- Position encoding consistency: When reusing state, the position offset must be restored at the same time; otherwise a phase misalignment in rotary position encoding will noticeably degrade quality.
- State serialization: Fixed-length state suits a compact binary layout with zero-copy transfer, which eases cross-node migration; key-value blocks keep a block format that remains independently addressable.
- Observability: At minimum, collect prefix hit rate, state reuse rate, average rollback length, cache tier migration volume, prefill queueing time, and time-to-first-token percentiles (including p90/p99). Use these metrics rather than a single average throughput figure to judge whether an optimization actually works.
- Capacity and eviction coupling: When host memory or the external cache approaches its watermark, evict large cold key-value blocks first and retain state snapshots, because the latter are more expensive to recompute.
5. Where the Gains Come From and How to Validate
For long-context, high-prefix-repetition coding workloads, the gains from this design come from three places. First, it avoids full state recomputation, reducing duplicated work from “linear in prefix length” to “linear in the missed segment.” Second, tiering and hot/cold separation improve cache capacity utilization, so more sessions can be reused across turns and across nodes. Third, scheduling continuity improves operator efficiency in the prefill phase, directly improving throughput and the tail of time-to-first-token.
For validation, replay real session traces and construct three comparison groups: no cache baseline, key-value block caching only, and coordinated state-plus-key-value caching; measure each under three capacity configurations—GPU memory only, GPU memory plus host memory, and GPU memory plus host memory plus a large external cache. The metrics observed should include throughput, time-to-first-token percentiles, and output correctness consistency, ensuring that performance optimization does not come at the cost of generation quality. If an organization already has common infrastructure such as a container platform, object storage, a message queue, and monitoring and alerting, the state and key-value tiers can be mapped onto the corresponding categories, and end-to-end validation and canary rollout can be completed with the general-purpose storage and observability capabilities of platforms such as Baidu AI Cloud.
