Unified KV and State Caching for Hybrid Architecture LLMs: Refactoring Prefix Caching with a Single Prefix Tree
Hybrid architectures that interleave full-attention layers with linear recurrent layers cut decode cost and push back the context-length memory wall, but they break the assumptions behind prefix caching. This article explains why KV cache is position-self-describing while a linear layer's recurrent state is a history accumulator, walks through the five engineering problems that follow (no random access into state, ref-counting versus in-place updates, tree-safe eviction, RoPE and interleaved layer layouts, distributed reuse), and presents a refactor that indexes KV blocks and state snapshots in one prefix tree with per-slot reference counting, copy-on-write state slots, sparse checkpoints, and L1/L2/L3 tiering. It also covers the scheduler-side prerequisites (prefix-aware routing, priority, chunked prefill, warm-up), why throughput gains and tail-latency gains come from different sources, an observability metric list, and the known limits of the approach.
1. Background: Hybrid Models Run Faster but Are Harder to Cache
1.1 The two layer types have different compute semantics
Linear attention, gated delta rules, and state-space sequence layers are now common in open-source large models. Vendors typically stack them with full-attention layers in an interleaved pattern: attention layers preserve exact long-range retrieval, while linear layers compress history at a constant memory cost. The benefit is clear — during decode, per-step compute is largely independent of sequence length, and cache memory no longer grows linearly with context, which pushes the long-context memory wall noticeably further out.
The cost, which is easy to overlook, is this: the two layer types represent “history” in fundamentally different ways.
- History in an attention layer = position-indexed Key/Value tensors. Naturally sliceable, concatenable, reference-countable, and quantizable.
- History in a linear layer = a recurrent state compressed into a fixed-size matrix. It carries no explicit information about “which token is at position i”; it is a functional dependency over all accumulated knowledge.
That single sentence is the root of every engineering difficulty that follows.
1.2 Why prefix caching is easy in pure-attention models
In a pure Transformer serving stack, prefix caching is nearly free. The shared prefix of a request is split into fixed-size blocks, looked up by block hash, and on a hit the corresponding KV pages are reused; the unmatched suffix is computed normally. Blocks can be reused whole or partially, shared across requests, reference-counted, and evicted to CPU or even remote storage.
Semantically, a KV page is read-only and position-self-describing: as long as you know where the page starts, you can splice it into a prefix of any length.
1.3 Hybrid models require rewriting that logic
Switch to a hybrid model and the chain of reasoning above breaks. You can reuse the attention KV blocks, but you cannot continue a linear layer’s history from a “suffix state.” A linear layer’s state is the result of recurrence accumulated all the way from position 0; there is no such thing as “the state as of token 4000.” Consequently:
- Hit detection degrades from page-level hashing to prefix-tree node-level matching.
- The unit of reuse shrinks from “any block” to “the entire prefix from the sequence start to some node.”
- The set of cache objects changes from one kind to two kinds that live and die together (KV blocks plus the state snapshot at the matching position).
If you simply reuse a pure-attention cache manager, the most typical outcome is: high hit rates on the KV side, full recomputation on the state side. And recomputing state requires serial block-by-block recurrence, so you end up doing the prefill work you were supposed to avoid, while stretching the request’s queueing delay.
2. Five Core Engineering Challenges
2.1 State cannot be randomly read: no position independence
Position self-description is what makes random access into KV pages possible; a linear layer’s state does not have this property. As a result, partial-prefix hits cannot degrade gracefully: either you hit node N and can reuse everything up to it completely, or you start recomputing after node M and must recompute the linear layer. The cache manager has to model this constraint explicitly rather than assuming “any position can be resumed.”
In practice, the answer is to maintain a state snapshot per prefix-tree node and to trade off between “store no intermediate state” and “store state checkpoints at fixed intervals” (see 3.1).
2.2 Paging and reference counting conflict with state semantics
Attention KV fits the standard paging mechanism cleanly: fixed-size blocks, reference counting, copy-on-write. A linear layer’s state is a single object updated in place, which conflicts with the model in which a block can be shared by multiple requests and appended to in place. Once two requests share the same prefix state and each appends its own generated tokens, they can no longer share one state object.
What is required: bring state objects under the same reference-counting and copy-on-write semantics. A hit clones the state (or clones it into a newly allocated slot), and append writes happen on the private copy. Cloning is not cheap — state is typically several tensors at hidden × head_dim scale — so this should be combined with slot-pool reuse and a “clone first, write later” deferred strategy rather than blind memcpy.
2.3 Safe eviction boundaries
KV blocks can be dropped freely under LRU. A linear layer’s state cannot: once dropped, every suffix that depends on it can no longer be reconstructed from scratch, because it encoded the information from the discarded prefix. Eviction must therefore be tree-safe:
- Dropping the state of node N invalidates its entire subtree and requires cascading marks.
- Conversely, keeping a deep node’s state while dropping an ancestor is a logical error. The computation result is unaffected, but the tree becomes internally inconsistent.
The implementation suggestion is to add state_valid and children_alive fields to each node, do cascading cleanup top-down during eviction, or adopt the conservative policy of “only evict state at leaves, preserve the path.”
2.4 Position encoding and the interleaved layer layout
“Position-independent” for linear layers refers to compute being independent of length, not to compute being independent of position — it still depends on the full recurrence from 0 to the current position. Two details follow:
- RoPE position bases must stay consistent. When reusing attention KV, renumbering the prefix positions misaligns the RoPE phase, producing a hit that computes the wrong result. Cache keys must bind to absolute position semantics, or the framework must guarantee consistency.
- Interleaved layer order affects snapshot contents. Because hybrid layers alternate, a state snapshot must record how far the prefix was cut and which layers are attention layers. Snapshots are therefore heterogeneous — some layers are KV tensors, some are recurrent state — and serialization needs to dispatch per layer type.
2.5 Distributed deployment and cross-node reuse
The size, type, and lifetime of hybrid state all differ from KV, and cross-node reuse amplifies the problems:
- State must be transferred between nodes, and network bandwidth becomes the bottleneck. This usually demands more aggressive quantization/compression of state than of KV (state’s sensitivity to precision differs from KV’s and needs to be calibrated by measurement).
- Multi-replica consistency: if the same prefix has a state copy on several nodes, you must decide which is authoritative. Otherwise different nodes can produce inconsistent continuations after a hit.
- Namespacing: a distributed cache must be keyed on model weight version + model ID + prefix fingerprint to avoid cross-model false hits. This can go wrong in pure-KV setups too, but the consequences are worse for hybrid state, since state is a numerically accumulated quantity and errors get amplified.
3. The Refactor: One Unified Prefix–State Cache
The core idea is to stop treating the KV cache and the state cache as two independent modules and instead index them together as a single hybrid cache: the index is a prefix tree, nodes carry both tensor types, and eviction, promotion, and transfer all go through one scheduler.
3.1 Data structures
@dataclassclass PrefixNode:token_hash: bytes # Chained hash of prefix content up to this node (bound to parent)parent: "PrefixNode | None"depth: int # Number of tokens represented by this nodekv_blocks: list[BlockId] # Attention-layer KV block references (shareable, ref-counted)state_slot: int | None # Linear-layer recurrent state slot (single instance, copy-on-write)state_valid: boolref_count: intchildren: dict[bytes, "PrefixNode"]# Whether a skippable state checkpoint is kept at the given intervalis_checkpoint: bool = Falseclass HybridCacheManager:def match(self, token_ids: list[int]) -> tuple[PrefixNode | None, int]:"""Return the longest fully reusable prefix node and match length(only up to positions where state_valid holds and KV is complete)"""node, matched = self.root, 0for i, tid in enumerate(token_ids):child = node.children.get(hash_prefix(node.token_hash, tid))if child is None or not child.state_valid:breaknode, matched = child, i + 1return node, matcheddef admit(self, token_ids: list[int], node: PrefixNode | None,kv_blocks: list[BlockId], state: Tensor) -> PrefixNode:"""Write the fully computed prefix back to the cache:KV goes through block references, state uses copy-on-write"""target = nodefor i in range(len(node_kvs(token_ids)) if node else 0, len(token_ids)):...# Key point: once the hit node is reused, append writes must land on a private state copyslot = self.state_pool.clone(node.state_slot) if node else self.state_pool.alloc()self.state_pool.copy_in(slot, state)self.state_pool.bump_ref(slot)return target
Four design points summarize the approach:
- Hit semantics are “whole prefix up to a node.” There is no promise of resuming from an arbitrary position.
- KV uses block-level reference counting; state uses slot-level reference counting plus copy-on-write.
- State and KV live and die on the same node, with cascading eviction.
- State checkpoints are stored sparsely at fixed token intervals (for example one every 1K–4K tokens), trading checkpoint hit rate for storage and transfer cost and turning “random access into state” into a tunable parameter.
3.2 Tiered storage: GPU memory → CPU memory → distributed/remote
- L1 (GPU): hot prefixes’ KV blocks and state, direct hits, zero-copy.
- L2 (CPU memory / local NVMe): warm prefixes. A hit requires H2D/D2H transfer, so refills should be gated on a benefit test — bytes moved versus expected compute time saved — rather than always refilled.
- L3 (distributed cache / object storage): cross-node sharing, keyed on prefix fingerprint + weight version. This can be built from general-purpose cloud building blocks: distributed caching, object storage, multi-replica inference services on a container platform, plus logging and monitoring/alerting for hit-rate observation, without building a storage layer from scratch.
Across tiers, the hybrid cache’s eviction policy should be more conservative than pure KV: state is more expensive than KV (costlier to recompute, slower to transfer, larger to clone), so state slots deserve their own quota and their own LRU rather than sharing one GPU memory budget with KV.
3.3 Scheduler-side prerequisites
Whether the cache delivers its benefits depends largely on the scheduler:
- Prefix-aware routing: requests from the same session or code repository should land on an instance that already holds the prefix. Otherwise hits only happen within a single node and cross-node benefit drops to zero.
- Priority ordering: requests with a prefix hit are enqueued first, reducing the impact of queueing on p90.
- Chunked prefill: splitting very long prefixes into chunks, combined with state checkpoints, balances “keep the compute saturated” against “keep latency controllable.”
- Warm-up and prefetch: in agent scenarios, “system prompt + tool definitions + repository snippets” are often highly stable and can be actively refilled at session start, turning first-token latency from “cold recompute” into “hit load.”
4. Why Throughput Can Multiply: Where the Gains Come From
In published results for this kind of unified refactor, replaying real long-context coding trajectories reaches prefill throughput on the order of several times mainstream baseline frameworks, with p90 first-token latency dropping by more than 80%. That magnitude is not mysterious; the gains come from four places:
- Eliminating repeated prefix computation. In multi-turn conversations, history accumulates turn after turn. A pure-attention framework can reuse KV; a hybrid framework that recomputes all state effectively repeats the history recurrence every turn. The unified cache drives this cost close to zero.
- Suppressing serialization blow-up. Linear-layer chunk recurrence is sequentially dependent and cannot be amortized with parallelism during recomputation. Removing it deletes the longest serial segment on the critical path, so the end-to-end latency improvement is markedly larger than the throughput improvement.
- Better memory-access efficiency. Keeping state resident in GPU/CPU memory reduces repeated weight reads and round trips of intermediate tensors, lowering bandwidth pressure under both decode-heavy and prefill-heavy mixed workloads.
- Tail-latency control. p90 TTFT is determined jointly by long shared prefixes, queueing, and cold caches. Prefix-aware routing plus warm-up refills attack exactly that long tail.
Worth noting: throughput and tail latency draw on different sources of gain — throughput comes from computing less, tail latency from waiting less. Tuning must therefore track these metrics separately rather than looking only at averages.
5. Practical Guidance and a Metric Checklist
5.1 Tuning for agent-style workloads
- Hold on to stable prefixes. System prompts, tool schemas, and project-level instructions are almost constants; give them a long TTL and exclude them from LRU eviction.
- Make cache affinity session-based, not request-based. Consecutive turns of the same session landing on the same instance typically makes an order-of-magnitude difference in hit rate.
- Choose state quantization carefully. State is a numerically accumulated quantity, so quantization error amplifies through the recurrence. Calibrate a precision-versus-quality curve offline first, then decide between fp16/bf16 and lower bit widths.
- Make the checkpoint interval configurable. A larger interval saves storage and transfer but increases recomputation on partial hits; a smaller interval does the opposite. Set it from real trajectory replay data, not guesswork.
5.2 Load testing and observability
| Metric | Meaning | Optimization lever |
|---|---|---|
| Prefix hit rate (token-level / request-level) | Cache effectiveness | Routing affinity, TTL, warm-up |
| State hit rate | Whether the hybrid cache is actually working | Checkpoint interval, state quota |
| State recomputed tokens | Work that was not saved | Tree-safe eviction, quota |
| H2D / D2H bytes moved | Whether L2 refills pay off | Benefit-test threshold |
| p50 / p90 / p99 TTFT | Tail latency | Routing, priority, warm-up |
| Prefill throughput (tokens/s) | Compute efficiency | Chunked prefill, batch scheduling |
| Cache slot fragmentation rate | GPU memory utilization | Slot pool, copy-on-write policy |
Recommended load-testing method: replay real multi-turn trajectories rather than synthetic repeated prefixes, since synthetic workloads overestimate hit rates. Also report results for cold-cache, warm-cache, and hot-cache starting points separately instead of showing only the best case.
6. Limitations and Outlook
A unified hybrid cache does not solve everything. Known boundaries include:
- Consistency between state and KV is a hard constraint. Any partial-hit optimization must guarantee that attention and linear layers are cut at the same position, or the results cannot be trusted.
- Namespaces must be isolated across models and weight versions. Otherwise you get silent “hit but semantically wrong” errors, which are more dangerous than a performance regression.
- Serialization and transfer overhead for heterogeneous tensors can become a new bottleneck in large-scale distributed deployments and must be designed together with quantization and compression strategies.
- Scheduling affinity depends on the layer above. The cache layer cannot decide on its own which instance a request lands on.
Three directions seem worth investing in next. First, make “random access into state” an explicit model-side design (for example, periodically refreshing state into an addressable form). Second, treat prefix hits as a first-class input to the scheduler, jointly optimizing with batching and parallelism strategy. Third, build session-level cache lifecycle management around the agent workload’s “stable prefix + high turn frequency” pattern.
In one sentence: the caching problem in hybrid architecture models is not “store one extra copy of state” — it is that the cache object changes from position-self-describing KV into history-accumulating state, so the cache’s index structure, eviction semantics, transfer strategy, and scheduling affinity all have to be redesigned around that fact. Put KV and state in the same prefix tree, manage state slots with reference counting and copy-on-write, and carry prefixes of different temperatures across a tiered storage hierarchy, and you can obtain several-fold prefill throughput and a significant tail-latency improvement without changing the model architecture.
