Optimizing Agent Caching and Prefill in Hybrid Architectures

    This article explores the complexities of prefix caching and prefill optimization for hybrid LLM architectures in AI agent scenarios. It covers the unified management of KV blocks and recurrent state snapshots, detailing design goals like unified cache keys, tiered granularity, multi-level hit evaluation, and cache-aware scheduling. Additionally, it provides runtime workflows, distributed engineering practices, and capacity planning strategies to maximize prefill throughput and reduce latency.

    1. Problem Background: Why Hybrid Architectures Complicate Prefix Caching

    In scenarios such as programming agents, code assistants, and automated operations assistants, requests are rarely simple one-shot queries. Instead, they involve multi-round, long-context workloads comprising system prompts, tool definitions, conversation history, file snippets, execution results, and retry branches. To balance decoding speed and VRAM usage, an increasing number of models adopt a hybrid architecture: “full attention layers + linear/recurrent state layers.” Full attention layers maintain a KV cache that grows with the context, while linear layers use fixed-size state vectors to summarize historical information. This structure is lighter during the decoding phase but introduces new complexities to prefix cache management.

    In traditional pure attention models, prefix caching revolves primarily around KV blocks: KV blocks with identical prefixes can be reused by block, and only the missed suffixes require reprefilling. Hybrid architectures are different. Linear or state layers do not store per-token KV; instead, they maintain a recurrent state dependent on the complete history. This state cannot be simply truncated by token blocks, nor can you restore only a portion of the KV without restoring the corresponding state, otherwise subsequent computations will be inconsistent with the original history. In other words, prefix caching is no longer just “KV block caching” but a joint cache of “KV blocks + state snapshots.”

    In multi-round agent workloads, this complexity is further amplified. System prompts and tool definitions are typically long and stable, conversation history continuously grows, and tool calls generate branches and retries. The same prefix might be shared across multiple sessions. If only KV is cached and the state is recomputed each time, prefill gains are limited. If a state snapshot is saved for every token, storage and transmission overheads will rapidly increase. For cross-node reuse, you must also handle issues like model versions, tokenizer versions, precision, adapters, positional encoding, and state consistency. Therefore, prefix caching in hybrid architectures requires redesigning cache granularity, hit evaluation, restoration workflows, and scheduling strategies.

    2. Design Goals: Unified Management of KV Blocks and State Snapshots

    A viable hybrid state cache management method should first treat the KV cache and the recurrent state as two representations of the same prefix, rather than two isolated systems. Its core design goals include:

    1. Unified Cache Key: The cache key should include at least the model version, tokenizer version, prefix token sequence hash, position range, layer type, precision format, and adapter identifier. Only when these elements match do the KV blocks and state snapshots become reusable. Otherwise, seemingly identical prefixes might cause semantic deviations due to version differences.

    2. Tiered Caching Granularity: KV is managed in fixed blocks, facilitating partial hits, eviction, and transmission; states are saved as checkpoints at fixed intervals, such as saving a complete state every N tokens. Denser checkpoint intervals mean shorter suffixes to recompute during restoration, but higher storage and write overheads. Sparser intervals save storage but increase tail recompute costs. Engineering trade-offs should be made based on workload length distribution, state size, and restore latency targets.

    3. Tiered Hits and Fallback Paths: A request might result in a full hit, a checkpoint hit, a KV-only partial hit, or a complete miss. A full hit allows direct restoration of state and KV; a checkpoint hit restores the latest state and available KV blocks, followed by incremental prefilling of the tail suffix; a KV-only hit still requires computing the missing state; a complete miss triggers a full prefill. Tiered hits allow the system to gain partial benefits even when the cache is incomplete, avoiding a binary all-or-nothing approach.

    4. Cache-Aware Scheduling: The scheduler should be aware of prefix hit conditions and prefill costs, batching requests with identical or similar prefixes, prioritizing the reuse of high-value long prefixes, and routing requests to nodes with higher cache hit rates. In agent scenarios, system prompts and tool definitions usually have high reuse value and should be given higher retention priority.

    3. Runtime Flow and Pseudocode

    At runtime, an incoming request first undergoes prefix planning: computing the prefix hash, querying the metadata service, and determining whether a complete state, checkpoint state, and KV blocks exist. If a checkpoint is hit, it restores the state and KV blocks, executing prefill only on the suffix after the checkpoint; if missed, it executes a full prefill and writes new KV blocks and state checkpoints according to policy. The abstract pseudocode below illustrates the control flow for logic purposes only and does not represent a real interface.

    1. function handle_request(req):
    2. plan = cache.plan(
    3. prefix_hash = hash(req.prefix_tokens),
    4. model_version = req.model_version,
    5. tokenizer_version = req.tokenizer_version,
    6. adapter_id = req.adapter_id
    7. )
    8. if plan.full_hit:
    9. state = cache.restore_state(plan.state_id)
    10. kv_blocks = cache.restore_kv(plan.kv_block_ids)
    11. return decode(state, kv_blocks, req.suffix_tokens)
    12. if plan.checkpoint_hit:
    13. state = cache.restore_state(plan.checkpoint_state_id)
    14. kv_blocks = cache.restore_kv(plan.kv_block_ids)
    15. state, kv_blocks = prefill_suffix(
    16. state,
    17. kv_blocks,
    18. req.tokens_after_checkpoint
    19. )
    20. cache.maybe_write_checkpoint(state, req.prefix_tokens)
    21. return decode(state, kv_blocks, req.suffix_tokens)
    22. state, kv_blocks = prefill_full(req.prefix_tokens)
    23. cache.write_kv_blocks(req.prefix_tokens, kv_blocks)
    24. cache.write_state_checkpoints(req.prefix_tokens, state)
    25. return decode(state, kv_blocks, req.suffix_tokens)

    The key to this workflow lies in “restore first, then increment, then write.” The restore phase must ensure position alignment between the state and KV blocks; the incremental phase only computes the suffix after the checkpoint, avoiding redundant computation of long system prompts; the write phase decides whether to save checkpoints based on access frequency, prefix length, and remaining capacity, preventing low-value prefixes from crowding out high-value cache space.

    4. Distributed and Tiered Cache Engineering

    Given the limited VRAM on a single machine, a large-capacity CPU memory pool can serve as a secondary cache, forming a tiered structure of “VRAM — Host Memory — Remote Storage.” State snapshots and KV blocks can be stored via content addressing, while the metadata service records prefix hashes, position ranges, versions, leases, and reference counts. For cross-node reuse, only the state snapshots and missing KV blocks are transferred, with compression or low-precision conversion applied to the transmitted data. Transmission and computation should be overlapped to prevent cache reads from becoming a new bottleneck.

    Public experimental scenarios indicate that when replaying real programming agent call traces on high-end accelerators, redesigning the hybrid state cache can boost prefill throughput up to approximately 3.14 times that of general inference engines, with p90 Time-To-First-Token (TTFT) latency reduced by up to roughly 88.4%. After integrating a 512GiB-level CPU cache pool, the benefits remain significant, supporting distributed storage and cross-node hybrid state reuse. These metrics demonstrate that the gains stem not only from single-point cache hits but also from the synergy of state checkpoints, KV block reuse, cache-aware scheduling, and tiered transmission.

    Engineering implementation also requires attention to consistency and isolation: when model or tokenizer versions change, leases and version numbers should invalidate old caches; in multi-tenant scenarios, cache keys must include tenant isolation dimensions to prevent information leaks caused by prefix hash collisions; state snapshots should feature checksums and automatically fall back to full prefill upon restoration failure; eviction policies should comprehensively consider prefix length, hit frequency, last access time, and rebuild cost, prioritizing the retention of high-reuse system prompts and tool definitions.

    5. Observability and Capacity Planning

    To verify the actual effectiveness of hybrid state caching, fine-grained metrics should be established: prefix hit rate, checkpoint hit rate, state restore duration, KV block restore duration, tail recompute token ratio, prefill throughput, TTFT p50/p90/p99, cache write amplification, cross-node hit rate, and fallback failure rate. Stress testing should cover short requests, long system prompts, multi-round tool calls, branch retries, and cross-node reuse workloads, avoiding the pitfall of only looking at average throughput while ignoring tail latency.

    For capacity planning, the state checkpoint interval is the core parameter. Overly dense intervals increase state write and storage costs, while overly sparse intervals increase tail recompute. The optimal interval can be estimated based on state size, average suffix length, and restore latency targets, with denser checkpoints set separately for high-value long prefixes. Cache writes should be asynchronous and rate-limited to prevent the prefill path from being blocked by write operations.

    At the deployment level, both self-hosted and cloud services can leverage general engineering capabilities. For example, you can use container platforms like Baidu AI Cloud for elastic scheduling, object storage to save cold cache snapshots, and logging and monitoring services for metrics collection and anomaly tracking. During implementation, it is advisable to gradually introduce cache-aware scheduling first, followed by enabling state checkpoints and cross-node reuse, continuously monitoring hit rates, tail latency, and cache costs to ensure that prefill throughput improvements translate into an enhanced end-to-end agent experience.