Hybrid Architecture Cache Redesign: Up to 3x Higher Prefill Throughput

    As open-source large models increasingly adopt hybrid architectures that combine full-attention layers with linear layers, inference engines face a new caching challenge: managing both KV caches and fixed-size state matrices. This article explains why prefix caching breaks down under hybrid architectures in multi-turn coding agent workloads, and walks through a practical redesign covering dual-pool cache management, checkpoint placement, longest-prefix matching, eviction strategy, tiered storage, and cross-node reuse. It also covers evaluation methodology, common pitfalls, and deployment recommendations, including benchmark results showing up to 3.14x prefill throughput improvement and an 88.4% reduction in p90 time-to-first-token under prefix-heavy workloads.

    1. Why Hybrid Architectures Have Become a Common Choice

    Over the past couple of years, open-source large language models have increasingly adopted a hybrid structure combining full-attention layers with linear layers. In a standard Transformer, the attention layer stores key-value (KV) pairs for every token, so the cache grows linearly with sequence length. Linear attention and state space models instead compress all historical information into a fixed-size state matrix, which means per-step computation and memory usage during decoding are essentially independent of context length.

    The typical hybrid approach is to keep one full-attention layer every few layers, with linear structures filling the rest. The full-attention layers preserve precise long-range retrieval, while the linear layers handle the bulk of sequence modeling. Together, they strike a balance between decoding speed and memory footprint. For long-context serving, this trade-off is usually more cost-effective than a pure-attention design.

    However, this creates a new problem on the inference side. The cache type shifts from a single KV cache to two distinct types — KV and state — with different lifecycles and management requirements.

    2. The Caching Challenge Posed by Multi-Turn Coding Agents

    A coding agent’s typical workflow looks like this: read code, call a tool, receive the output, reason again, and call another tool. Every request carries the entire conversation history, system prompt, tool definitions, and file contents from all previous turns. Adjacent requests share a highly repetitive prefix, with only new content appended at the end.

    This is exactly where prefix caching delivers value. If the prefix of a new request has already been computed, the inference engine can reuse the existing intermediate results and skip that portion of the prefill computation. Prefill latency scales roughly proportionally with input length, and it dominates total cost in long-context scenarios — so cache hit rate directly determines time-to-first-token (TTFT).

    For pure Transformer models, the situation is relatively straightforward. The KV cache is divided into fixed-size blocks by token, and each block depends only on the content before it. As long as prefix blocks match, they can be reused block by block — the more blocks that match, the more computation is saved.

    Hybrid models break this assumption. A linear layer’s state is a holistic compression of the entire history; it cannot be sliced into independent segments like “the state from token 1 to token 512,” because a state is only meaningful at a specific position within a complete sequence. In other words, a linear layer’s state can only be reused starting from a concrete position, and it must correspond exactly to all the content preceding that position.

    This creates three problems:

    1. Inconsistent reuse granularity: KV can be matched block by block, while state can only be matched at specific positions. The two must align at the same position to hit together.
    2. Different size characteristics: State size is independent of length, but the KV of full-attention layers still grows with length — so snapshot size is dominated by the full-attention layers.
    3. Different eviction units: Evicting a KV block versus evicting a state snapshot has very different implications for hit rate and recomputation cost.

    The table below compares the two cache types:

    Dimension KV Cache in Pure Transformers KV + State Cache in Hybrid Architectures
    Reuse unit Fixed-size token blocks Block-level KV plus position-aligned state snapshots
    Hit condition Matching prefix blocks Matching prefix plus a state snapshot at the corresponding position
    Footprint behavior Grows linearly with length Linear-layer portion is fixed; full-attention portion grows
    Management challenge Block allocation and eviction Synchronizing two cache types; choosing snapshot positions

    3. Decoupled Management and Checkpoint Design

    A viable approach to these problems is to manage the two cache types separately while linking them through a shared prefix index.

    3.1 Dual-Pool Structure

    • KV block pool: Manages key-value blocks of full-attention layers at a fixed size, following the common practice of paged memory management.
    • State snapshot pool: Stores the complete state of linear layers at specific positions, with each snapshot recording its corresponding token position and prefix hash.

    The two pools are allocated and reclaimed independently to minimize interference. Snapshots and KV blocks are associated through the same prefix hash, and both must reside at the same position for a hit.

    3.2 Checkpoint Placement

    Saving a state snapshot for every token is infeasible — the storage overhead would be unacceptable. In practice, checkpoints are placed only at the following positions:

    • Block boundaries: Aligned with KV block size for easy concatenation.
    • Conversation turn boundaries: Natural split points in multi-turn agent requests; the next turn’s prefix will very likely extend from here.
    • After long tool outputs: Tool responses are typically long, so saving a snapshot afterward avoids recomputing the entire output on the next turn.

    Checkpoint density is a trade-off. Too dense, and storage consumption grows; too sparse, and hit points become rare, leaving many reusable prefixes unexploited.

    3.3 Longest-Prefix Matching

    When a new request arrives, the system walks the prefix index to find the longest reusable position. A valid hit point must satisfy two conditions simultaneously: the KV blocks at that position are fully present, and a usable state snapshot exists at that position. If KV exists but no state does, the system must fall back to an earlier checkpoint.

    Illustrative code (logic demonstration only, not the interface of any specific system):

    1. def find_reusable_prefix(tokens, index):
    2. best = None
    3. for node in index.walk(tokens): # Walk the prefix tree segment by segment
    4. if node.kv_ready and node.state_snapshot is not None:
    5. best = node # Record the longest reusable position
    6. if best is None:
    7. return 0, None # No reusable prefix; compute from scratch
    8. return best.position, best

    After a hit, the engine resumes prefill from best.position, computing only the newly appended tokens.

    3.4 Eviction Policy

    Cache space is limited, so the system must decide what to evict. Useful scoring factors include:

    • Recency and frequency of access
    • Space occupied by the entry
    • Recomputation cost of the prefix — longer prefixes are more expensive to recompute
    • Whether longer successor prefixes depend on it

    In practice, a snapshot and its successor prefixes are often evaluated as a unit, so that evicting a snapshot doesn’t orphan the longer prefixes built on top of it.

    4. Tiered Storage and Cross-Node Reuse

    GPU memory on a single machine is limited and fills up quickly in multi-turn long-session scenarios. Tiered storage extends available cache capacity:

    1. GPU memory: Lowest latency, smallest capacity. Holds actively used KV blocks and snapshots.
    2. Host memory: Larger capacity, accessed over the host-device interconnect. Suitable for prefixes from recent sessions.
    3. Distributed storage: Largest capacity, highest latency. Suitable for cross-node sharing and long-term retention.

    Taking an external CPU cache as an example, the number of cacheable entries can be estimated as follows:

    Number of snapshots ≈ cache capacity ÷ size per snapshot

    The size of a single snapshot depends on the number of model layers, the number of full-attention layers, the number of KV heads, the data type, and the prefix length. For a cache capacity of 512 GiB, you must first compute the snapshot size based on your actual model configuration to derive a concrete entry count — empirical rules of thumb don’t transfer directly.

    4.1 Prerequisites for Cross-Node Reuse

    The biggest risk of reusing state stored on other nodes is a false hit. The cache index key should include at least:

    • Model identifier and weight version
    • Tokenizer version and vocabulary
    • Arrangement of linear and full-attention layers
    • Data type and quantization configuration
    • Tensor parallelism and pipeline parallelism partitioning

    Any mismatch on these items should be treated as a different cache. Otherwise you risk reusing states with mismatched shapes or values, producing errors that are extremely hard to debug.

    4.2 Transfer vs. Latency

    Cross-node transfer requires comparing transfer time against recomputation time. When transferring a snapshot takes noticeably longer than re-prefilling locally, remote reuse loses its purpose. The scheduling layer should therefore record the benefit of each hit and use it to decide whether remote caching is worthwhile.

    5. Evaluation Methodology

    The effectiveness of cache optimization depends on the workload, so metrics and testing methods should be defined before evaluation.

    5.1 Core Metrics

    • Prefill throughput: Input tokens processed per unit time; reflects compute resource utilization.
    • Time-to-first-token (TTFT): Focus on P50, P90, and P99 — tail latency has a greater impact on interactive experience.
    • Cache hit rate: Measured by tokens rather than requests, as it better reflects actual savings.
    • GPU and host memory usage: Track KV blocks and snapshots separately.
    • Recomputed token count: A direct measure of computation saved by caching.

    5.2 Workload Construction

    Replay real multi-turn session traces rather than randomly generated requests. The prefix reuse patterns, tool output lengths, and turn distributions in real traces determine how much caching can help. Random requests tend to distort benefit estimates.

    5.3 Controlled Experiments

    The control group should use identical hardware, model weights, batch sizes, and scheduling parameters, with only the cache management strategy swapped out. If the baseline’s default configuration differs from the optimized setup in other parameters, the conclusions are unreliable.

    The original study replayed real coding-agent session traces on a next-generation data-center GPU and reported prefill throughput up to approximately 3.14x that of a mainstream open-source inference engine baseline, with p90 TTFT reduced by up to 88.4%. These figures come from specific workloads and configurations, and peak gains typically occur in scenarios with high prefix reuse. Under workloads where prefixes barely repeat, the improvement shrinks significantly.

    6. Common Pitfalls

    1. Treating linear-layer state as ordinary KV. Slicing state into blocks produces meaningless fragments, and outputs after a hit may diverge from a full computation.
    2. Setting checkpoints too densely or too sparsely. Too dense exhausts cache space; too sparse misses large amounts of reusable prefix.
    3. Looking only at average throughput. Averages can mask worsening tail latency, and the user experience of multi-turn agents is often defined by the tail.
    4. Ignoring the eviction cost of long prefixes. Short prefixes are accessed frequently, but once a long prefix is evicted, recomputation is expensive. The eviction policy should account for this explicitly.
    5. Generalizing from a single test result. Cache benefits depend heavily on prefix reuse rate and should be revalidated on your own real traffic.

    7. Deployment Recommendations

    • Measure before optimizing: Profile your workload’s prefix reuse rate and turn distribution before deployment. If reuse is low, hybrid-architecture cache optimization offers limited value.
    • Align chunking parameters: Keep checkpoint intervals, KV block size, and prefill chunk size in integer-multiple relationships to reduce concatenation and boundary-handling overhead.
    • Isolate versions: After a model upgrade or a change in quantization, clear or isolate old caches to prevent false hits.
    • Build monitoring: At minimum, record hit rate, eviction counts, snapshot write latency, and remote read latency, so you can quickly diagnose tail-latency regressions.
    • Plan tiered capacity: Estimate the capacity needed at each tier based on concurrent session counts and average prefix length, rather than looking only at per-GPU memory.