Redesigning Hybrid State Caching to Improve Agent Prefill Throughput
Hybrid architectures that combine full attention layers with linear recurrent layers reduce KV cache pressure during decoding, but they introduce new caching challenges during prefill—especially for Agent workloads with long prompts, multi-turn history, and frequent branch rollbacks. This article explains why hybrid state caching needs a holistic redesign rather than a smaller KV cache, breaks down the layered design of prefix indexing, KV paging, linear state snapshots, and scheduler coordination, and walks through pseudocode covering allocation, commit, and snapshot restore. It also analyzes the main sources of prefill throughput gains and provides practical guidance for deploying this design in Agent systems, including checkpoint granularity, copy-on-write branching, and key metrics to monitor.
1. Background: Why Hybrid Architectures Still Need a Cache Redesign
Hybrid architectures that mix “full attention layers + linear recurrent layers” assign different responsibilities to each layer type. Full attention layers preserve the expressive power needed for long-range dependencies and precise retrieval, while linear recurrent layers perform incremental computation with a fixed-size recurrent state. This reduces memory-access pressure during decoding and significantly shrinks the traditional KV cache. For workloads such as chat, code generation, and tool calling, this structure typically offers better decoding throughput and lower memory footprint.
However, Agent workloads amplify a different bottleneck: prefill. Agent requests typically carry long system prompts, tool definitions, format constraints, multi-turn history, tool return results, and branch rollback records. In a single request, the proportion of tokens that genuinely require new computation may be low—much of the content consists of reusable prefixes or history. Meanwhile, in a hybrid architecture, the cache is no longer just KV data; it also includes the recurrent state of the linear layers. If you manage it with the single-layer KV cache mindset, three problems arise:
- High state initialization cost: Linear layer state must be updated sequentially token by token and cannot simply be concatenated like KV entries. Prefilling from scratch re-computes large amounts of stable prefix.
- Mismatched lifecycles between KV and state: The KV of full attention layers can be paged in blocks, while linear layer state is a monolithic snapshot. If the two are managed separately, restoration can easily suffer version misalignment.
- Frequent Agent branching and rollback: Tool calls, reflection retries, and parallel branches create many short-lived sessions, driving up cache fragmentation and invalidation costs.
Therefore, redesigning hybrid state caching is not simply about shrinking the KV cache. It means treating “paged KV cache + linear state snapshots + prefix indexing + scheduler coordination” as a single, cohesive design. The roughly threefold prefill throughput improvement mentioned in public technical discussions should be understood as a directional result under this class of workloads and specific benchmarks; actual gains depend on the model’s layer ratio, context length, batching strategy, and cache hit rate.
2. Load Characteristics of Agent Prefill
To design the cache, you first need to understand the structure of Agent requests. A typical Agent request can be abstracted as:
[system prompt and safety constraints] + [tool schemas] + [conversation history] + [tool returns] + [current instruction]
The first few segments are highly stable, conversation history grows with each turn, tool returns are usually short but follow a fixed format, and the current instruction is the shortest. The main prefill costs are concentrated in repeated computation over long prefixes, KV writes, linear state updates, and padding waste caused by heterogeneous lengths within a batch.
Agent workloads have three additional characteristics:
- High prefix reuse: Multiple turns within the same session share the system prompt and most of the history, making them ideal for prefix caching.
- Frequent branching and rollback: The same history may spawn multiple candidate actions, requiring state restoration from a checkpoint rather than a fresh prefill.
- Large length variance within batches: Parallel tool calls mix long-context restoration requests with short incremental requests in the same batch; poor scheduling hurts throughput.
The cache design goals should therefore be explicit: reduce repeated prefill tokens, lower state restoration latency, reduce KV and state memory fragmentation, improve batch utilization, and guarantee state consistency.
3. A Layered Design for Hybrid State Caching
A practical hybrid state cache can be organized into four layers:
- Prefix index layer: Indexes system prompts, tool schemas, history hashes, and model versions to determine the reusable range.
- KV paging layer: Serves only the full attention layers, managing KV blocks in fixed-size pages with reference counting, shared mapping, and on-demand reclamation.
- Linear state snapshot layer: Stores checkpoints for the linear recurrent layers, with snapshots bound to token positions, layer versions, and prefix keys.
- Scheduler coordination layer: Exposes cache hit information to the batch scheduler so that restoration, prefill, and decoding can overlap in a pipeline.
The key principle is “logically unified, physically separated”: KV and linear state differ in physical storage, but they share the same prefix key, version number, and commit order. Only when both are committed at the same checkpoint can restoration avoid problems like “KV arrived but state did not” or “state is stale while KV is fresh.”
4. Pseudocode: From Allocation to Commit
The following pseudocode describes the core flow, focusing on prefix lookup, paged allocation, state updates, asynchronous commit, and snapshot restoration.
class HybridStateCache:def __init__(self, kv_pages, state_store, prefix_index):self.kv_pages = kv_pages # paged KV cache for full attention layersself.state_store = state_store # state snapshots for linear recurrent layersself.prefix_index = prefix_index # index from prefix keys to checkpointsdef begin_request(self, req):key = build_prefix_key(model_version=req.model_version,system_prompt_hash=hash(req.system_prompt),tools_hash=hash(req.tools),history_hash=hash(req.history))hit = self.prefix_index.lookup(key)if hit and hit.version == req.model_version:return RestorePlan(kv_blocks=hit.kv_blocks,state_snapshot=hit.state_snapshot,prefix_len=hit.token_len)return AllocatePlan(key=key)def prefill(self, plan, new_tokens, layer_schedule):for chunk in chunk_tokens(new_tokens, chunk_size=256):kv_slot = self.kv_pages.allocate(chunk)state_slot = self.state_store.ensure(plan.request_id)for layer in layer_schedule:if layer.type == "attention":self.kv_pages.write(layer, kv_slot, chunk)else:self.state_store.update(layer, state_slot, chunk)# Commit KV and state at the same checkpoint in order to avoid version misalignmentself.commit_async(kv_slot, state_slot, token_pos=plan.next_pos)def snapshot(self, request_id, key):state_snap = self.state_store.snapshot(request_id)kv_blocks = self.kv_pages.ref_blocks(request_id)self.prefix_index.insert(key, state_snap, kv_blocks,token_len=self.state_store.position(request_id))def restore(self, restore_plan):# Map shared KV pages and restore the linear state snapshotself.kv_pages.map_shared(restore_plan.kv_blocks)self.state_store.restore(restore_plan.state_snapshot)
This pseudocode highlights three engineering points: the prefix key must include the model version; KV pages use shared mapping rather than copying; and state snapshots and KV blocks are committed at the same logical checkpoint. The scheduler can run KV mapping and state deserialization in parallel during the restore phase, shortening time-to-first-token.
5. Main Sources of Throughput Gains
Prefill throughput improvements typically come from the following combined effects:
- Reduced repeated computation: Once a prefix hits, only new tokens are computed; long system prompts and tool schemas are no longer prefilled repeatedly.
- Lower state initialization overhead: Linear state is restored from the nearest checkpoint, avoiding token-by-token updates from scratch.
- Fewer KV writes and less fragmentation: Paged sharing reduces duplicate KV blocks, while reference counting and reclamation policies reduce memory fragmentation.
- Better batch utilization: With cache-hit awareness, the scheduler can mix restoration requests with short incremental requests in a batch, reducing waiting on long requests.
- Overlapped commit and compute: Asynchronous commit of KV pages and state snapshots hides part of the write-back overhead behind subsequent computation.
It is worth emphasizing that the threefold improvement does not come from a single optimization. It is the combined result of prefix hit rate, state restoration speed, paging quality, and batch scheduling. If the hit rate is low or branching is excessive, the gains drop significantly.
6. Putting It into Practice in Agent Systems
In an Agent system, a recommended rollout order is:
- Normalize prefixes first: Keep system prompts, tool schemas, and output format templates stable; avoid injecting meaningless timestamps or random IDs into the prefix.
- Set checkpoint granularity: Create snapshots at fixed token intervals or tool-call boundaries, balancing restoration speed and storage cost.
- Use copy-on-write for branch rollback: Candidate branches share the parent checkpoint’s KV pages, and state snapshots are copied on demand, preventing branch explosion.
- Monitor key metrics: Prefill tokens/s, time-to-first-token, prefix hit rate, state restoration time, KV page utilization, intra-batch length variance, and snapshot memory usage.
- Run stress tests: Cover combinations of long system prompts, multi-turn history, parallel tool calls, frequent rollbacks, and heterogeneous batch lengths.
Risk control matters just as much: state snapshots must carry version numbers and position information; quantized or compressed snapshots require numerical error evaluation; cache invalidation policies must prevent stale state from being reused; and caching of safety constraints and tool schemas must be protected from pollution by malicious requests.
7. Conclusion
Hybrid architectures shift part of the KV cache burden to linear recurrent state, but Agent workloads make cache management during prefill far more complex. The core of hybrid state cache redesign is to unify KV paging, linear state snapshots, prefix indexing, and scheduler coordination under a single checkpoint semantics, improving throughput by reducing repeated prefill, enabling fast restoration, and cutting fragmentation. For Agent systems that require long prompts, multi-turn reuse, and branch rollback, this is a more sustainable optimization path than simply scaling up batch sizes. In real deployments, benchmark against your own workloads, treat publicly reported performance multiples with caution, and give consistency, rollback capability, and observability the same weight as throughput.
