Optimizing State Caching in Hybrid Architectures: Tripling Prefill Throughput

    This article examines why prefix caching becomes difficult in hybrid architectures that alternate full attention layers with linear or state layers, and why prefill often becomes the bottleneck for long-context coding agents. It outlines a layered caching abstraction based on unified addressing with separated storage, dual-granularity reuse, distinct lifecycle and eviction policies, and multi-tier storage with prefetching. It also covers practical engineering considerations such as metrics, replay validation, capacity planning, distributed consistency, and observability, along with realistic expectations for prefill throughput and TTFT improvements.

    1. Background: New Caching Challenges in Hybrid Architectures

    In model designs over the past two years, a hybrid architecture that alternates full attention layers with linear or state layers has become a common approach. The motivation is straightforward: full attention layers handle global information exchange and preserve long-range dependency modeling, while linear layers—such as various linear attention and gated state space structures—replace the growing key-value cache with a fixed-size recurrent state, reducing memory usage and improving decode-phase throughput.

    However, these gains show up most clearly in single-turn, short-context benchmarks. Once the workload shifts to something like a coding agent, the picture becomes more complex:

    • Contexts are extremely long: repository-level code and multi-turn tool call results keep accumulating.
    • Prefixes are highly repetitive: system prompts, project structure, and historical patches are submitted repeatedly within the same session.
    • Requests arrive in bursts: multiple sessions run concurrently, and prefix sharing forms a tree rather than a linear chain.

    Prefix caching in pure attention models uses key-value blocks as the unit of reuse, which naturally fits block-level hashing. Hybrid models, however, carry two kinds of state at the same time: a key-value cache that grows with length and a recurrent state that is independent of length. Their lifecycles, addressing schemes, and migration costs are completely different. Reusing one caching strategy for both leads to lower reuse rates, inaccurate scheduling decisions, and wasted memory and host memory bandwidth.

    2. Bottleneck Analysis: Why Prefill Falls Short for Long-Context Agents

    Time to first token (TTFT) is determined by the prefill phase. In multi-turn agent workloads, prefill computation is roughly proportional to the number of new tokens multiplied by the context length, while repeated prefixes should be skipped directly by the cache. In practice, four issues typically cause the expected gains to be lost:

    1. Granularity mismatch: using fixed token blocks as cache keys makes it impossible to split and reassemble hybrid states losslessly.
    2. Coarse hit detection: only checking whether the prefix is identical ignores the difference in reusable boundaries between state layers and attention layers.
    3. High swap-in and swap-out cost: state objects are small but semantically tightly coupled, so arbitrary eviction can force recomputation of an entire prefix.
    4. Fragmented multi-tier storage: GPU memory, host memory, and remote storage operate independently, lacking unified addressing and lifecycle management.

    The hit detection logic can be abstracted as follows:

    1. def resolve_prefix(tokens, block_size=256):
    2. # Compute fingerprints block by block and find the longest reusable prefix
    3. matched, pos = 0, 0
    4. while pos + block_size <= len(tokens):
    5. key = fingerprint(tokens[pos:pos + block_size])
    6. if key not in cache:
    7. break
    8. matched += block_size
    9. pos += block_size
    10. # Return the length that can be skipped and the tail that needs recomputation
    11. return matched, tokens[matched:]

    The real complexity in production systems is that a separate “reusable boundary” must be maintained for the state layers, avoiding mismatches where the attention portion hits but the state portion is invalidated.

    3. Core Design: A Layered Caching Abstraction for Hybrid States

    When redesigning this kind of cache, the industry has generally converged on a few shared principles that can serve as a reference framework for implementation.

    3.1 Unified Addressing, Separated Storage

    Build a unique fingerprint for each prefix and attach two payload descriptors: a list of attention key-value blocks, and a state snapshot with its corresponding length. Addressing is unified while storage is separated, so the scheduler deals with a single logical object.

    3.2 Dual-Granularity Reuse

    • Coarse granularity: an entire prefix (system prompt, project context) hits directly, skipping all computation.
    • Fine granularity: partial block-level hits within a long prefix, with the incremental tail recomputed.

    Because the state layers are length-independent, they are well suited to being persisted periodically as checkpoints at key positions, reducing the number of snapshots.

    3.3 Separate Lifecycle and Eviction Policies

    Key-value caches should be evicted at block level using LRU under memory pressure; state snapshots are small but expensive to rebuild, so they should have longer residency and higher retention priority. If both share one queue, the result is often the reverse of what you want: cheap items are kept while expensive ones are dropped first.

    3.4 Multi-Tier Storage and Prefetching

    GPU memory serves as tier one, large host memory as tier two, and distributed storage as tier three. The key is prefetching based on predicted request arrivals: patterns such as session resumption and branch retries are highly regular in agent workloads, so the states and key-values of candidate prefixes can be moved into tier-one storage in advance.

    4. Implementation Considerations

    • Metrics: focus on five core metrics—p50/p90 TTFT, prefill token throughput, cache hit rate, and GPU memory usage per request—to avoid letting averages hide the long tail.
    • Replay validation: replay real session traces rather than synthetic short requests, so the true cost of prefix-tree reuse and swap-in/swap-out is exposed.
    • Capacity planning: host memory caching needs bandwidth evaluation, not just capacity, because the prefill phase is bandwidth-sensitive.
    • Distributed consistency: cross-node reuse requires clear versioning and invalidation semantics to prevent reading stale state and producing abnormal output.
    • Observability: instrument cache objects to record hit tier, migration time, and recomputed length, making continuous tuning easier.

    5. Sources of Gains and Realistic Expectations

    Public technical explorations show that, when replaying real coding agent traces on high-end accelerator cards, redesigning the hybrid state cache can bring prefill throughput to several times that of a general-purpose inference framework, with a substantial drop in p90 TTFT. The gains persist after adding host memory caching on the order of hundreds of gigabytes, and can extend to cross-node reuse. It is worth emphasizing that the exact multiplier depends heavily on model structure, the distribution of context lengths, and session concurrency patterns, so engineering evaluation should be based on measurements from your own workloads.

    For teams using compute and storage capabilities from Baidu AI Cloud, the adoption path can be summarized as: run inference services on a container platform, store state snapshots in object storage or distributed file storage, track cache hit rates and tail latency through the monitoring and alerting system, and gradually turn multi-tier caching from an optional optimization into infrastructure for long-context agent services.