Hybrid Architecture State Caching Refactor: Tripling Prefill Throughput

    This article explains why KV caches designed for pure attention models break down in hybrid architectures that combine full attention with linear layers. It examines the workload characteristics of coding agents, the semantic conflict between fixed-size states and mutable prefixes, and a three-tier caching design based on paged KV caches, sparse state snapshots, and replay logs unified through content-based addressing. It also covers scheduling, capacity planning, tiered storage, cross-node reuse, and the expected performance gains.

    1. Background: Hybrid Architectures Are Mainstream, but Caching Is the Bottleneck

    Over the past year, the structure of open-source large models has shifted noticeably. “Constant-state” computation paradigms represented by linear attention, gated delta rules, and state space layers are increasingly combined with traditional full attention layers, forming a hybrid stack of “full attention + linear layers.” The motivation is straightforward: full attention provides precise global retrieval, while linear layers trade a fixed-size recurrent state for lower decoding cost and a smaller cache footprint.

    The problem is that most engineering-side caching systems were built around the key-value cache (KV Cache) of pure attention models. When both types of state coexist in a model, the original prefix caching assumptions no longer hold, which shows up in three ways:

    1. Different state shapes. The KV cache is a “history collection” that grows linearly with sequence length, while a linear layer’s state is a “fixed-size snapshot” that is repeatedly overwritten and updated.
    2. Different reuse semantics. KV caches can be stitched together segment by segment along a token prefix, whereas a state snapshot can only be read as a whole and cannot be resumed from an intermediate position.
    3. Different invalidation propagation. Once a prefix forks, the KV cache only needs to append entries after the fork point, while a state snapshot must replay the entire history to produce a correct result.

    In workloads such as AI coding tools, all three issues are amplified at once: a single session often spans dozens of turns, context repeatedly appends code snippets and tool results, prefixes overlap heavily but fork frequently, and the cache hit rate directly determines actual throughput during the prefill stage.

    2. Workload Characteristics: Why Coding Agents Are the Most Cache-Sensitive

    Coding agent trajectories have several stable characteristics that cache designers should focus on:

    • Extremely long, monotonically growing prefixes: system prompts, repository structure, and historical patches keep accumulating, with new content mainly appended at the tail.
    • Dense branching: retries, rollbacks, and multi-option comparisons derive multiple successor paths from the same prefix.
    • High proportion of tool results: logs, compiler output, and retrieval snippets are large, making repeated transfer and repeated computation expensive.
    • Latency sensitivity: time to first token (TTFT) directly affects the interactive experience, and TTFT is determined almost entirely by the prefill stage.

    Therefore, a caching solution should not be evaluated on average throughput alone; tail percentile latency matters more, especially p90 TTFT.

    3. The Core Conflict: Fixed States vs. Mutable Prefixes

    Putting both types of state into the same cache pool immediately exposes a structural contradiction: the KV cache supports “incremental by position,” while state snapshots only support “overwrite as a whole.” If the block-matching strategy designed for pure attention is reused as-is, two typical forms of waste appear.

    The first is repeated replay. When the hit point falls in the middle of a sequence, the system can only restart computation from the nearest complete state snapshot, discarding the intermediate segments that were already computed.

    The second is snapshot redundancy. To guarantee resumability at any position, engineering practice tends to persist state snapshots densely, but snapshots are not small, so cache capacity gets consumed by large numbers of “intermediate states” while the truly high-frequency prefixes get evicted.

    Illustrative pseudocode shows the difference:

    1. # Pure attention: blocks can be stitched; a hit resumes from the break point
    2. def reuse_kv(prefix_blocks, cached_blocks):
    3. hit = longest_match(prefix_blocks, cached_blocks)
    4. return cached_blocks[:hit] # the remainder is computed and appended normally
    5. # Hybrid architecture: states cannot be stitched; load the whole snapshot and replay
    6. def reuse_hybrid(prefix_tokens, snapshots):
    7. snap = nearest_snapshot(snapshots, prefix_tokens)
    8. return replay(snap.state, prefix_tokens[snap.pos:]) # the tail still needs recomputation

    This comparison points to the solution direction: optimizing caches for hybrid architectures is essentially a controllable tradeoff between “snapshot density” and “replay length,” rather than simply applying prefix matching.

    4. Design Approach: Tiered State Caching with Unified Addressing

    A widely accepted refactoring direction is to split the cache into three layers and bind them together with unified addressing.

    The first layer is a paged KV cache, managed in fixed-length pages, responsible for precise reuse of full attention layers, with support for reference counting and on-demand eviction.

    The second layer is a sparse state snapshot layer that saves linear layer states only at key positions (such as turn boundaries, before and after tool calls, and branch points), avoiding the capacity waste caused by uniform, dense persistence.

    The third layer is a replay log layer that stores the incremental information sufficient to reconstruct state from the nearest snapshot, so that “hit but no snapshot hit” cases can also be resumed at low cost.

    The key to unified addressing is computing a stable content fingerprint for each prefix and encoding “page index + snapshot position + replay offset” into the same key space. A sketch of the structure:

    1. cache_key = hash(parent_fingerprint, chunk_content, layer_group)
    2. entry = { kv_pages, snapshot_ref, replay_offset, ref_count, last_access }

    This way, the scheduler does not need to care which layer a piece of state comes from; it only queries, counts, and evicts by a unified key.

    5. Scheduling and Capacity: Keeping Hit Rate and GPU Memory Usage Under Control

    Once the cache is tiered, the real engineering difficulty becomes policy, which can be set along four dimensions:

    • Snapshot trigger policy: primarily turn boundaries and branch points, supplemented by an upper bound on the token interval since the last snapshot, balancing hit rate and capacity.
    • Eviction policy: combine least recently used with reference counting, and raise the weight of prefixes shared across multiple branches to avoid mistakenly evicting hot prefixes.
    • Prefetch policy: based on the append pattern of session history, move pages and snapshots likely to be hit in the next turn into the fast tier ahead of time.
    • Replay parallelization: split replay into parallelizable inter-layer segments and overlap them with the computation of new tokens to hide recomputation cost.

    For capacity planning, use “number of active sessions that can be held × average prefix per session” as the baseline, then reserve a certain proportion for the snapshot layer; when GPU memory is tight, compress snapshot precision or reduce snapshot density first, rather than sacrificing the hit capability of the paged cache.

    6. Tiered Storage and Cross-Node Reuse

    When a single machine’s GPU memory cannot cover active prefixes, a multi-level system combining memory pools, local high-speed media, and remote object storage is needed, together with a cache cluster capable of high-throughput reads. Key engineering points include:

    1. Hot/cold tiering: hot pages stay in GPU memory, warm data goes to the memory pool, and cold data lands in remote storage, with automatic migration by access frequency.
    2. Consistency constraints: state snapshots and page caches must be version-aligned, and fingerprints and model versions must be verified on cross-node reuse to avoid silent errors from mixing different weights.
    3. Transfer optimization: batch, compress, and pipeline transfers to overlap cross-node read latency with local computation.
    4. Observability: use hit rate, replay length distribution, p90 TTFT, and cache eviction reasons as core metrics, and connect them to a general logging service and monitoring/alerting system for continuous tuning.

    7. Implementation Advice and Expected Gains

    Roll out along a progressive path: first unify addressing and metric definitions, then introduce sparse snapshots and replay logs, and finally extend to multi-level storage and cross-node reuse. Each step should be validated by replaying real multi-turn trajectories rather than relying only on synthetic benchmarks.

    In principle, the gains of this kind of refactor concentrate in three areas: first, eliminating full recomputation after a mid-sequence hit directly raises prefill throughput; second, turning repeated computation of long prefixes into cache reads significantly compresses the TTFT tail; third, unified addressing improves reuse rates across sessions and nodes, so scaling yields higher hit rates rather than linearly growing cost. For agent scenarios such as AI coding, code review, and long-document analysis, this caching perspective often determines the actual service experience more than further optimizing operators.