Optimizing State Caching in Hybrid Architectures: 3x Prefill Throughput Improvement

    This article examines why hybrid architectures, which alternate full attention layers with linear or state-space layers, make prefix caching significantly more complex than in pure attention models. It explains the fundamental differences between attention KV states and fixed-size recurrent states, the three core conflicts these differences create, and four design principles for treating both state types as first-class citizens across addressing, matching, eviction, and transfer. The article also covers engineering considerations for schedulers, memory pools, observability, and cluster deployment, along with the sources of throughput gains and common pitfalls to avoid when serving long-context, multi-turn AI Agent workloads.

    1. Introduction: Agent Workloads Are Shifting the Focus of Inference Optimization

    Over the past two years, LLM inference optimization has centered on the decode phase: reducing the cost of generating each token and compressing memory usage under long sequences. However, as intelligent coding tools, code review assistants, and automated operations Agents have become widespread, workload characteristics have changed significantly. Requests are no longer “one question, one long answer,” but rather “dozens of tool calls, repeatedly feeding back the same very long context.”

    In these multi-turn, long-context scenarios, the metrics that truly determine user experience have become prefill throughput and p90 time to first token (TTFT). The reason is straightforward: after each tool call, the Agent must reassemble the conversation history, file snippets, and retrieval results into an input of tens of thousands or even hundreds of thousands of tokens, then recompute everything. If the prefix cache cannot be reused efficiently, users wait several seconds to tens of seconds every time they press Enter.

    At the same time, model architectures themselves are changing. A recent wave of models in the industry commonly adopts a hybrid architecture that alternates full attention layers with linear layers (linear attention/state-space layers), aiming for faster decoding and smaller cache footprints. But hybrid architectures introduce an easily overlooked side effect: their cache is no longer a single form, and prefix cache management is far more complex than in pure attention structures. This article addresses this general technical problem and systematically discusses the key design points of state caching under hybrid architectures.

    2. Root Cause: Why Hybrid Architectures Make Prefix Caching Harder

    2.1 The Fundamental Difference Between Two State Types

    A pure attention model has only one type of cache: key-value pairs (KV Cache) stored per layer and per head. Its memory footprint grows linearly with sequence length, and each token’s position is naturally addressable.

    A hybrid architecture has two types of state simultaneously:

    • Attention state: Also KV entries that grow with length, with a clear “one entry per token” semantic.
    • Linear layer state: Linear attention and state-space operators maintain a fixed-size recurrent state that compresses the entire history into a set of matrices/vectors, with a size independent of sequence length.

    This difference leads to a key conclusion: The two state types have completely different reuse granularity, invalidation conditions, and transfer costs, and cannot be handled with the same caching strategy.

    2.2 Three Specific Conflicts

    1. Granularity mismatch: KV can be truncated and reused by block, reusing as much as the prefix hits; recurrent state is “all or nothing”—if even one token in the middle differs, the entire compressed state is unusable.
    2. Complex invalidation determination: In hybrid layers, whether a prefix block can be reused depends on whether all linear layer states after that block are consistent, making the determination chain longer than in pure attention.
    3. Asymmetric swap-in/swap-out costs: Migrating KV blocks involves contiguous memory copies, while migrating recurrent states involves many small tensors and operator metadata, with metadata management overhead taking a high proportion.

    3. Design Approach: Managing “Hybrid State” as a First-Class Citizen

    To address the above problems, a proven direction is to stop treating the cache as an “appendage of KV” and instead redesign the cache abstraction so that both state types are explicitly modeled across four stages: addressing, matching, eviction, and transfer. This can be summarized in four design principles.

    Principle 1: Unified Addressing, Layered Description

    Establish a unified identifier for each prefix segment (for example, a block ID based on content hash), and separately record in its metadata the “coverage range of the attention portion” and the “snapshot location of the linear state.” A sample structure is as follows:

    1. @dataclass
    2. class PrefixEntry:
    3. block_hash: str # Content fingerprint for cross-request matching
    4. kv_blocks: list[int] # Physical block indices of attention state
    5. recurrent_snapshot: int # Handle to the linear layer state snapshot
    6. valid_len: int # Number of tokens this entry can safely reuse
    7. layer_mask: int # Marks which layers' states are ready

    The key lies in valid_len and layer_mask: they allow the system to express a “partially available” intermediate state, rather than being forced into an all-hit/all-miss binary choice.

    Principle 2: Layered Short-Circuiting in the Matching Process

    Prefix matching does not need to be completed at once. First use a lightweight fingerprint to locate candidate entries, then verify state consistency layer by layer; once a layer’s state is found to mismatch, immediately truncate subsequent verification to avoid unnecessary deep comparisons. This “layer-by-layer short-circuiting” can significantly reduce CPU-side scheduling overhead under long contexts.

    Principle 3: Cost-Weighted Eviction Strategy

    Traditional LRU only looks at access time. Under hybrid architectures, a “rebuild cost” weight should be introduced: rebuilding the attention state of a long prefix is expensive, while rebuilding a recurrent state snapshot has a relatively fixed cost. Therefore, the eviction score can be approximated as:

    1. score = hit_frequency * (α * kv_rebuild_cost + β * recurrent_rebuild_cost)

    Where α and β adjust the relative priority of the two state types within the memory budget. In practice, KV blocks of long prefixes should generally be given a stronger residency tendency.

    Principle 4: Separating Transfer and Storage

    Write the two state types to different media: keep state for frequently reused short prefixes in GPU memory; demote medium-hot prefixes to host memory; move long-tail prefixes to a large-capacity memory pool or distributed cache layer. Because recurrent states are small and semantically complete, they are well suited for cross-node reuse; KV blocks are better suited for parallel transfer at block granularity.

    4. Engineering Implementation Points

    4.1 Scheduler Modifications

    The objective function of prefill scheduling should shift from “maximizing single-batch size” to “maximizing the combined benefit of prefix hit rate and memory utilization.” Feasible approaches include: grouping requests that hit prefixes of different lengths to reduce redundant computation; adopting chunked prefill for the miss portion to avoid long requests monopolizing compute resources and causing queue jitter.

    4.2 Memory Pool and Capacity Planning

    It is recommended to define separate quotas for the two state types and support dynamic adjustment. If using large-capacity host memory as a second-level cache, attention must be paid to the size of pinned memory, the number of concurrent copy streams, and bandwidth limits; otherwise, swap-in/swap-out will become a new bottleneck.

    4.3 Observability

    Collect at least the following metrics: prefix hit rate, average reuse length, bytes of state swapped in/out, prefill queue wait time, and p50/p90/p99 TTFT. Without “average reuse length,” it is easy to misjudge a situation with a high hit rate but very short reuse as a successful optimization.

    4.4 Integration with General Cloud Capabilities

    In clustered deployments, container platforms can be used to orchestrate inference instances, object storage or distributed cache services can carry the persistence of state snapshots, and monitoring/alerting and logging services can track changes in hit rate and latency percentiles. These are all general capability categories; specific choices should be determined based on load testing tailored to your own scale.

    5. Analysis of Gain Sources: Why Throughput Can Multiply

    The improvement in prefill throughput does not come from a single technique, but from a triple superposition:

    1. Elimination of redundant computation: In multi-turn Agent workloads, historical context takes up a very high proportion, and a hit directly saves compute.
    2. Improved scheduling efficiency: Layered matching and short-circuit verification reduce the per-request metadata overhead on the CPU side, making GPU utilization more stable.
    3. Tail latency convergence: Chunked prefill and priority scheduling reduce queuing caused by long requests, and p90 improvements are often more pronounced than the mean.

    This also explains why gains remain substantial after integrating a large-capacity host memory cache: the second-level cache turns the binary “hit/miss” structure into a multi-level gradient, and long-tail requests no longer directly degrade into full recomputation.

    6. Practical Recommendations and Common Pitfalls

    • Pitfall 1: Only looking at average TTFT. Agent experience is determined by tail latency; be sure to use p90/p99 as the acceptance criterion.
    • Pitfall 2: Prioritizing hit rate over reuse length. Both should be monitored simultaneously to avoid fragmented hits.
    • Pitfall 3: Ignoring state consistency verification. Once hybrid layer states are mismatched, output quality silently degrades, which is harder to troubleshoot than a crash.
    • Recommendation: Start with real trace replay. Using recorded multi-turn tool call sequences for offline replay stress testing exposes cache design flaws better than synthetic short requests.

    7. Conclusion

    The hybrid architecture is a reasonable compromise between decoding efficiency and memory cost, but it shifts complexity to the cache layer. Treating attention state and recurrent state as two independent yet synergistic first-class resources, and designing separately across the four stages of addressing, matching, eviction, and transfer, is the key path to achieving a multiple-fold improvement in prefill throughput under long-context, multi-turn workloads like those of intelligent coding Agents. For engineering teams, first completing observability metrics and real trace replay capabilities, then gradually introducing multi-level caching, is the lowest-risk implementation sequence.