Hybrid State Cache Refactoring: 3x Prefill Throughput Improvement

    This article explains why hybrid architectures that alternate full attention layers with linear layers make prefix caching more complex, and how to refactor the cache into two coordinated paths. It covers the semantic differences between KV cache and recurrent state, dual-pool separation with unified logical prefix addressing, snapshot placement strategies, copy-on-write lifecycle management, and tiered caching across GPU memory, host memory, and distributed storage. Readers will also find practical guidance on measuring reuse patterns, tracking percentile latency, load testing under eviction, and closing the observability loop.}

    1. Introduction: Agent Workloads Are Pushing Caching to Its Limits

    Multi-turn agent workloads, exemplified by AI coding assistants, are becoming the dominant source of pressure on inference serving. A request that looks ordinary — “fix this unit test for me” — often sits on top of dozens of tool calls and hundreds of file fragments fed back into the context repeatedly, easily pushing context length into the six-figure token range. Between any two of those requests, most of the prefix is identical: the system prompt, project conventions, the repository directory tree, and code blocks that have already been read.

    This means the performance bottleneck of an inference system is no longer in the decode phase, but in the prefill phase — how to avoid recomputing a long and highly repetitive prefix as much as possible. Over the past year, mainstream large models have largely shifted to hybrid architectures that alternate full attention layers with linear layers, trading a small number of global attention layers for a smaller cache footprint and faster decoding. But the caching problem did not get simpler; it changed shape. Where only one kind of object had to be cached, two states with completely different semantics must now be managed at the same time.

    This article addresses that tension directly, discussing the design essentials, common pitfalls, and engineering path for state caching under hybrid architectures.

    2. Why Hybrid Architectures Make Prefix Caching Harder

    2.1 Two states, two different semantics

    In a pure attention model, the cache has only one form: key-value pairs indexed by token position. It has a well-defined “prefix concatenation” property — as long as the prefix tokens match exactly, the cache can be reused directly, and truncating to any length still holds.

    Hybrid architectures introduce linear layers (state-space or linear-attention structures), whose cache is a fixed-size recurrent state. This brings two fundamental changes:

    • No arbitrary truncation: the state is a lossy compression of history. You cannot take “the cache for the first N tokens”; you can only take “a snapshot of the state as of step N.”
    • Writing destroys it: the state is updated in place. Once decoding continues, it is overwritten, so snapshots and restores must be explicit — otherwise a reuse attempt reads a value already polluted by a later request.

    2.2 Mismatched cache layouts

    The attention cache grows along the sequence dimension and is well suited to paged, block-based management. The linear state is a fixed-length tensor, more naturally organized by “layer + request.” Putting both into the same paged pool immediately produces two kinds of waste: fixed-length states get sliced into blocks and create internal fragmentation, while attention blocks create external fragmentation while waiting for state alignment.

    2.3 Prefix matching granularity is forced to get coarser

    Because the state can only be reused as a whole, the smallest unit of a cache hit degrades from “one block” to “one snapshot point.” If snapshot points are sparse, even a 90% identical prefix may produce no hit at all; if they are dense, metadata and copy overhead eat the gains. Where to place snapshot points is the core decision in hybrid cache design.

    3. Refactoring Approach: Split “One Cache” into “Two Coordinated Paths”

    The workable design principle is to decouple management of the two states, then bind them together through a unified logical prefix view.

    3.1 Dual pools with unified logical prefix addressing

    1. Logical prefix (prefix_id, token_len)
    2. ├── KV pool: block_table, shareable and truncatable at block granularity
    3. └── State pool: state_table, reused as a whole at snapshot granularity

    On a lookup, first run a longest-common-prefix probe to get the hit length L. Then align L down to the nearest snapshot point S: on the attention side, reuse the incremental blocks after S; on the state side, load the snapshot at S directly. This preserves fine block-level granularity while satisfying the all-or-nothing constraint of the state.

    3.2 Snapshot placement strategy

    A more robust engineering practice is to place snapshots at structural boundaries rather than at fixed intervals: the end of the system prompt, the end of the tool definitions, each conversation turn boundary, and the end of a file read result. These positions are naturally the high-probability branch points for subsequent requests, giving high hit rates with a manageable number of snapshots. A lightweight heuristic can help: only materialize a snapshot once a prefix has been hit by a second request, avoiding useless snapshots during cold start.

    3.3 Lifecycle and copy-on-write

    State snapshots must be treated as immutable objects, combined with reference counting and copy-on-write: a branching request clones first and then continues the recurrence, so the shared snapshot stays clean. For eviction, attention blocks suit LRU, while state snapshots are better scored by “branch heat + remaining live turns,” because a snapshot from an active session is worth far more than one from a single-shot request.

    4. Tiered Caching: Put Capacity at the Right Level

    GPU memory alone cannot cover the reuse window of agent scenarios. A sensible tiering is: keep the hottest attention blocks and state snapshots in GPU memory, use a host memory pool for hundreds of GiB of warm data, and use distributed storage for long-tail prefixes shared across nodes.

    Three engineering points matter:

    1. Overlap transfer with computation: state snapshots are small and attention blocks are large, so they should be scheduled differently — let small blocks arrive first and trigger computation while large blocks stream in.
    2. Metadata first: the global prefix index stays resident in memory, so hit determination must not depend on data movement completing.
    3. Consistency conventions: snapshots must carry an architecture identifier and a layer-configuration fingerprint, verified before cross-node reuse to prevent mixing different model configurations.

    Under real workloads such as agent trajectory replay, the gains from this refactoring show up mainly on the prefill side: on the hit path, a large amount of prefix computation is skipped, throughput reaches several times that of the original design, and p90 time-to-first-token drops significantly. The gains hold after attaching a large host memory cache, because the reuse window stretches from seconds to the length of a session.

    5. Implementation Advice and Validation

    • Quantify the reuse structure first: measure prefix repetition rate, branch point distribution, and snapshot density on real trajectories before choosing a strategy, rather than setting parameters by intuition.
    • Use percentiles for metrics: averages hide the long tail, and p90/p99 time-to-first-token is what agents actually experience.
    • Include eviction in load tests: hit-rate decay at full capacity is more informative than numbers from an idle system.
    • Close the observability loop: hit rate, snapshot lifetime, cross-node transfer volume, and state pool fragmentation rate — all four are required.
    • Work with platform capabilities: use a container platform to host elastic inference replicas, object storage and distributed caches for state persistence, and log and monitoring services to close the tuning loop.

    6. Conclusion

    Hybrid architectures did not eliminate the caching problem; they upgraded it from one-dimensional block management to two-dimensional coordinated state management. Whoever can put attention blocks and linear states into a unified prefix view, and extend the reuse window from GPU memory to host memory and distributed storage, will gain several-fold prefill throughput on multi-turn long-context workloads. The same approach applies to inference service optimization practices on Baidu AI Cloud.