Hybrid State Caching for Faster AI Agent Inference in Practice
This article explains why AI agent workloads need a different caching approach for hybrid-architecture language models, which combine full attention layers with linear recurrent state layers. It covers a unified cache block structure that reuses attention and recurrent states together, prefix indexing, state checkpoints, tiered storage across GPU memory, CPU memory, and remote nodes, and the metrics to track. It also reports prefill throughput and latency results from tests on real coding-agent traces, along with the conditions that affect those gains.
1. Why Agent Workloads Need Hybrid State Caching
AI agent systems for intelligent programming, automated task execution, and complex question answering share three traits:
Context length keeps growing
A single task may include the user’s request, conversation history, tool call results, code files, error logs, and intermediate reasoning. As the number of turns grows, the input often expands from a few thousand tokens to tens of thousands or more.Requests reuse prefixes heavily
An agent repeatedly sends the same system prompt, project notes, directory structure, tool definitions, and previously confirmed context. Between two requests, usually only the last short segment changes.Generation is highly interactive
An agent does not produce its full answer in one pass. It cycles through understanding the task, calling a tool, reading the result, reasoning further, and calling another tool. As a result, time to first token, prefill efficiency for each round, and cache hit rate all directly affect user experience and overall throughput.
Traditional pure-attention models usually store the Keys and Values needed for past attention in a KV cache. For a fixed prefix, this cache can be reused directly, which reduces repeated computation. Hybrid-architecture models, however, also include linear recurrent layers, state space layers, or other modules that maintain a running state. The history in these modules does not fully take the form of standard KV pairs. The object being cached therefore changes from a single KV cache to a combination of several kinds of state.
This is the core engineering challenge of hybrid models in agent workloads: the system must save, locate, restore, and reuse linear-layer states correctly, not only cache attention results.
2. How Hybrid Architectures Change Cache Management
A hybrid architecture combines different layer types in one model. Full attention layers capture relationships between any two positions well. Linear or recurrent state layers keep long-sequence information at a lower cost.
One inference pass can be abstracted as follows:
Input sequence├── Attention layers: generate or read K/V states└── Linear state layers: update recurrent states↓Output next token
The two kinds of state have different properties.
1. Attention cache depends on position
For attention layers, the cache usually maps one-to-one with sequence positions. When new input arrives, computation can continue from the existing prefix. If a request changes only the suffix, the Keys and Values for the prefix can still be reused.
This cache has a clear drawback, though. The longer the sequence, the more data it stores, and memory pressure in GPU and host memory rises quickly.
2. Linear state works like a recursive result
Linear layers usually do not store the full Key and Value for every past position. They compress earlier information into a recurrent state. This state can be smaller than a full attention cache, but each update depends on the previous one:
state[t] = update(state[t-1], input[t])
If computation resumes from a middle position, the system must use the correct preceding state. Saving only the final state cannot support concatenating arbitrary prefixes. Saving the full state at every position, however, removes the storage advantage of a linear structure.
3. The two kinds of state must stay in sync
A forward pass in a hybrid model typically passes through both attention layers and linear state layers. Even if the attention cache hits, computation can produce wrong results when the linear state does not sit at the same sequence boundary.
The cache system should therefore treat the following information as one unit:
- model layers;
- sequence prefix range;
- attention KV blocks;
- linear-layer states;
- positional encoding or related position information;
- cache version and model configuration;
- the session or task that the request belongs to.
In short, a cache hit cannot be confirmed by checking only whether a text segment has appeared before. The system must also confirm that all related states can be restored correctly at the same position.
3. Main Performance Bottlenecks in Agent Workloads
1. Repeated prefill consumes a lot of compute
In each round, an agent usually reads the same system prompt, tool descriptions, and project background. If every round runs prefill from the beginning, the GPU repeats the same computation again and again.
In long-context scenarios, the prefill stage can require far more computation than the generation stage. Even when a single generation step is fast, repeated prefill still raises end-to-end latency.
2. State reconstruction can still happen after a cache hit
Some traditional cache systems are designed only for attention KV. After a hybrid model request matches a prefix, the system may still need to recompute linear-layer states or rescan the input from an earlier position. This leads to a situation where the cache appears to hit but delivers limited benefit.
Effective reuse requires restoring all of the following together:
Attention cache + linear recurrent state + position boundary
If any one part is missing, subsequent computation can fall back to a long prefill.
3. Trade-offs between GPU memory, host memory, and remote storage
Cache data does not have to stay entirely in GPU memory. A common tiered structure looks like this:
GPU memory: holds recent hot statesCPU memory: holds a larger shared cacheRemote storage: holds persistent state across processes or nodes
The tiers differ in important ways:
- GPU access is fast, but capacity is limited;
- CPU memory has more capacity, but data must cross the bus to reach the GPU;
- Remote storage has the most capacity, but network transfer and serialization add latency.
For this reason, a cache system should not optimize only for hit rate. It must also weigh state size, transfer cost, and restore time.
4. Core Design of Hybrid State Caching
1. Use a unified cache block model
Split long sequences into logical blocks of fixed or roughly fixed size. Each block links both the attention cache and the linear state information.
The structure can be represented as follows:
CacheBlock {prefix_identity // prefix content or its digeststart_position // start positionend_position // end positionattention_payload // attention-layer cacherecurrent_state // linear-layer stateposition_metadata // position informationmodel_revision // model configuration version}
With this design, the cache scheduler does not need to manage two fully separate indexes. It can look up, migrate, evict, and validate data at the block level.
2. Use a layered prefix index
The index can be organized by model version, session context, prefix block, and state type. When a request arrives, the system first finds the longest reusable prefix, then confirms that every state in the matching blocks is complete.
The logic can be expressed in pseudocode:
candidate = lookup(model_revision, prefix_digest)while candidate exists:if attention_state_valid(candidate)and recurrent_state_valid(candidate)and position_is_contiguous(candidate):reuse(candidate)continue_matching()else:stop_reuse()compute_remaining_suffix()
The key goal is not simply to find the longest matching text prefix. It is to find the longest prefix whose states can be verified.
3. Set checkpoints for linear states
Linear states depend on the order of updates, so checkpointing suits them well. The system can save a complete state every few logical blocks and store only the necessary incremental information in between.
When a request resumes from a given position, the system first loads the nearest checkpoint, then replays a small number of later blocks. This balances storage cost against restore time.
The checkpoint interval should not be fixed across all workloads. For agents that call tools frequently or whose context changes a lot, denser checkpoints work better. For stable system prompts and project background that rarely change, a larger interval is usually enough.
4. Validate state consistency
When restoring from cache, the system should check the following conditions:
- whether model weights and configuration match;
- whether tokenization rules match;
- whether positional encoding parameters match;
- whether the positions of adjacent cache blocks are contiguous;
- whether the attention state and linear state belong to the same prefix;
- whether any state was truncated during migration or write-back.
For critical workloads, store a content digest and a state digest for each cache block. A digest does not expose the original content, but it lets the system quickly detect when the cache has been reused incorrectly.
5. Why Prefill Throughput Can Improve by an Order of Magnitude
When an agent request shares a long common prefix, the cache system can cut repeated computation substantially. The original flow looks like this:
Full context↓Run the entire prefill again↓Start generation
The optimized flow looks like this:
Common prefix → restore from cacheChanged suffix → run incremental prefill only↓Start generation
When the common prefix accounts for most of the input, the GPU can focus its compute on the new content. In this case, the gain in prefill throughput comes mainly from avoiding repeated computation, not from kernel optimization alone.
In tests on real coding-agent traces, one hybrid state caching approach reached up to roughly 3x prefill throughput compared with a conventional inference service on a high-end data center GPU. It also cut p90 time to first token by up to about 80%. These results depend heavily on request length, the share of repeated prefixes, cache capacity, scheduling policy, and hardware transfer efficiency. They should not be read as the same gain for every workload.
6. Tiered Caching and Cross-Node Reuse
When a single machine does not have enough GPU memory, the cache can extend to CPU memory and cross-node storage.
1. GPU tier
The GPU tier holds states for requests that are running now or accessed often. Its main goal is to reduce restore latency. Because GPU memory is limited, the system should prioritize:
- requests currently being generated;
- frequently used common prefixes;
- linear states that are expensive to restore;
- small, frequently accessed cache blocks.
2. CPU tier
The CPU tier suits a larger shared cache. Transfers between the GPU and CPU should use batched operations where possible, and the system should avoid frequent small copies.
If a state block must move back and forth between the GPU and CPU repeatedly, transfer overhead can cancel out the compute savings from caching. Hot and cold tiering based on access frequency helps prevent this.
3. Cross-node tier
Cross-node reuse fits cases where several inference instances share stable prefixes. The implementation must address:
- synchronizing cache indexes across nodes;
- managing state versions;
- network transfer and compression;
- conflicts between concurrent reads and writes;
- graceful degradation when a node fails.
Cross-node cache should not become a hard dependency of the inference path. If a remote state read fails, the request should fall back to recomputation instead of blocking the entire agent task.
7. Evaluation Goes Beyond Throughput
A complete evaluation of hybrid state caching should track at least the following metrics.
1. Time to first token
Time to first token shows how long users wait. Track p50, p90, and p99 rather than only the average.
2. Prefill throughput
Measure cache hits and misses separately. Record the input length, the share of common prefix, and the time spent restoring state.
3. Cache hit rate
Track these rates separately:
- text prefix hit rate;
- attention state hit rate;
- linear state hit rate;
- full state hit rate.
Only a full state hit means the main computation for that prefix can actually be skipped.
4. State restore cost
Measure the time to restore state from GPU memory, CPU memory, and remote nodes. Include serialization, deserialization, transfer, and validation in the total.
5. Correctness
Caching must not reduce output consistency. Run the same inputs with caching enabled and disabled, then compare the generated results, tool call arguments, and stop conditions for unexpected differences.
8. Practical Recommendations for Deployment
First, analyze real agent traces. Measure common prefix length, request intervals, context growth rate, and tool call frequency. Without a workload profile, it is hard to set cache capacity and checkpoint intervals sensibly.
Second, separate the cache manager from the model executor. Define five clear responsibilities: lookup, restore, write, eviction, and validation. This keeps scheduling logic from being tightly coupled to model kernels.
Third, optimize stable prefixes first, such as system instructions, tool definitions, and project-level context. Address frequently changing intermediate results afterward.
Fourth, set capacity limits, lifetimes, and security isolation policies for the cache. Agent context may include source code, business data, and user input, so cached content must follow access control and data cleanup requirements.
Fifth, build observability. At minimum, record cache hit rate, full state hit rate, restore time, GPU utilization, CPU utilization, cross-node traffic, and the number of degraded requests. Only with this data can you confirm that the performance gains are real.
Conclusion
Hybrid-architecture models combine full attention with linear state mechanisms. This shows promise for decoding efficiency and cache size. It also moves inference systems from managing a single KV cache to coordinating multiple kinds of state.
For long-context agents, the most effective optimization is not simply adding cache capacity. It is redesigning the cache system around four goals: states can be located, prefixes can be reused, restores can be verified, and tiers can be scheduled. A unified cache block, linear state checkpoints, tiered storage, and cross-node reuse can reduce repeated prefill, lower time to first token, and improve overall throughput for complex multi-turn tasks.
Looking ahead, cloud platforms such as Baidu AI Cloud continue to improve GPU, CPU memory, distributed storage, and inference scheduling capabilities. Hybrid state caching may become an important part of the infrastructure for long-context agents.
