Managing State Caches for Hybrid-Architecture LLM Agents: From Principles to Deployment
This article explains how prefix caching works for hybrid-architecture LLM agents, which combine a KV cache with recurrent states from linear layers or state space models (SSMs). It covers how the two cache types differ, how to organize prefix checkpoints, when incremental reuse is valid, how to offload and restore cached state across nodes, how to benchmark cache performance, and what to check before and after deployment.
Why Hybrid Architectures Make Caching Harder
A pure Transformer model’s prefix cache holds only one type of object: the KV cache. When a new request matches a cached prefix, the existing KV blocks are concatenated with the new sequence. A hybrid model adds a second type of object: the recurrent state produced by linear layers or state space models (SSMs). The two state types differ in three ways.
The first difference is shape. The KV cache of full-attention layers grows linearly with sequence length, so every additional token takes up more storage. The state of a linear layer or SSM is a fixed-size matrix. Its size stays the same no matter how long the context is.
The second difference is lifecycle. KV blocks can be released one block at a time. A state matrix is a single unit. If the state at any position is overwritten, reuse from that snapshot is no longer valid.
The third difference is access pattern. KV is append-only, while linear-layer state is updated for every token. As a result, a reusable snapshot at a given position must contain both types of state. Neither one is enough on its own.
Multi-turn agent workloads amplify these differences. A coding agent appends tool call results on every turn. That part is append-only and cache-friendly. However, the following operations break the prefix and cause the hit rate to drop sharply:
- Context compression: replacing the conversation history with a summary invalidates the prefix from the compression point onward.
- Parallel tool calls: several branches share the same prefix, but their outputs arrive in different orders, so the following tokens no longer match.
- Dynamic content: fields that change on every request, such as timestamps or request IDs embedded in the system prompt.
Without unified scheduling, the framework allocates the two state types differently. This fragments GPU memory and increases state synchronization. It can also trigger frequent swapping between GPU memory and CPU memory, which slows down the prefill stage.
How the Two State Types Are Organized
One workable approach is to organize the cache as “prefix checkpoints.” Each checkpoint binds three things: a token boundary position, references to the KV blocks of all full-attention layers before that position, and snapshots of the states of all linear-layer or SSM layers at that position. Checkpoints are stored with a prefix hash as the key, which makes lookup fast.
KV data is stored in blocks. The block size must align with the page size of the inference framework. Otherwise, the blocks will contain holes. There is no universal optimal block size. Determine it by measuring the request length distribution in your own workload.
The state data takes one fixed matrix per layer per sequence. Its shape is determined by the number of attention heads, the head dimension, and the state dimension. For example, in a model with several linear attention layers, the total state size in bytes equals the number of layers, multiplied by the state size of one layer, multiplied by the number of concurrent sequences. You can calculate this number at configuration time, and it should be included in the GPU memory budget.
During prefill, you can allocate KV blocks and state buffers in one pass, sized to the estimated maximum length. This reduces fragmentation caused by repeated allocation. The cost is that the reserved memory may sit idle. The pre-allocation ceiling should be set from a percentile of request lengths, such as p95, rather than the longest possible length.
The following simplified logic finds the longest reusable prefix:
def find_reusable_checkpoint(tokens):# Start from the longest prefix and move down. Return the first exact match.for end in range(len(tokens), 0, -block_size):cp = checkpoint_store.get(prefix_hash(tokens[:end]))if cp is not None and cp.tokens_equal(tokens[:end]):return cpreturn None # No reusable prefix, so the whole sequence is prefilled again
Preconditions for Incremental Reuse
Incremental reuse does not hold in every case. You can compute only the new tokens when all of the following conditions are met:
- The prefix matches token for token. This includes the order and content of the chat template, the system prompt, and the tool definitions. A difference of even one byte produces a different hash.
- The snapshot position must fall on a token boundary and align with a KV block boundary. Otherwise, the state and the KV cache correspond to different positions, and the output will be wrong.
- The snapshot is read-only. After a consumer reads a snapshot, it should copy a working copy before writing, or use reference counting to protect the original snapshot.
- Branches are handled explicitly. When one prefix leads to several continuations, each branch forks its own copy of the state from the checkpoint. If there are many branches, estimate the cost of the fork copies separately.
- On a prefix mismatch, fall back to a full prefill. Do not try to splice a partially matched KV cache and state together. This approach easily produces results that look normal but are actually incorrect.
When the conditions are met, the incremental computation works as follows:
def incremental_prefill(cp, new_tokens):kv = cp.kv_blocks.extend(compute_kv(new_tokens)) # Full-attention layers only appendstate = cp.state.copy() # Linear-layer state starts from the snapshotfor tok in new_tokens:state = recurrent_update(state, tok) # Update the fixed-size state one token at a timereturn kv, state
The key point is that the state update of a linear layer is recurrent by design. As long as the starting point is correct, the amount of computation is proportional to the number of new tokens and does not depend on the length of the history.
Cross-Node Offloading and Restoration
The memory of a single node is limited. When some sessions are inactive for a long time, you can offload their checkpoints from GPU memory to a CPU memory pool. The source material mentions a CPU memory pool at the 512 GiB level. That figure is a configuration example. Your actual capacity should be estimated from the number of nodes, the number of concurrent sessions, and the snapshot size per session.
Offloading typically uses a least recently used (LRU) policy. A request scheduled to another node can pull the snapshot from the memory pool, restore it, and continue computing. Whether a pull is worthwhile depends on comparing transfer time with recomputation time:
- Transfer time = snapshot size in bytes ÷ effective network bandwidth
- Recomputation time = prefix length ÷ prefill throughput of the node
Offloading and cross-node reuse pay off only when the transfer time is clearly shorter than the recomputation time. Under network congestion, this comparison can flip. For that reason, the scheduler should read bandwidth metrics in real time instead of relying on a static threshold.
Before restoring a snapshot, verify four things: the model version, the weight precision (such as bf16 or fp16), the tensor parallel and pipeline parallel partitioning, and the dtype of the state matrices. If any of these differ, abandon the reuse and run a full prefill. The biggest risk of cross-node reuse is silent errors. When verification fails, log the failure instead of falling back quietly.
How to Measure Performance
The source reports a prefill throughput increase of 3.14x and a reduction of up to 88.4% in p90 TTFT. However, it does not disclose the name and version of the baseline framework, the GPU model and count, the batch size, the sequence length distribution, or the measurement methodology. Without these conditions, the two figures serve only as directional references. They cannot be applied directly to your own system.
When you run your own tests, fix the following conditions first, and then compare results with and without caching:
| Measurement | Method | What to Record |
|---|---|---|
| Baseline | The same model, with prefix reuse disabled in the inference framework | Framework and version, and whether chunked prefill is enabled |
| Workload | Replay of real agent traces | Turn count distribution, context length distribution, branch ratio |
| Prefill throughput | Input tokens processed per second | Batch size, concurrency, sequence length |
| TTFT | p50, p90, and p99 | Difference between request arrival time and first token output time |
| Cache hit rate | Ratio of cached input tokens to total input tokens | Reported separately by turn and by session |
| Peak GPU memory | Peak usage and fragmentation rate for each node | Pre-allocation ratio and actual usage ratio |
| Data transfer volume | Bytes copied between GPU and CPU | Number of offloads and restores |
Focus on the distribution, not just the average. The long tail of TTFT often comes from cache misses or snapshot restoration. An average hides these problems.
Troubleshooting Checklist
If results fall short after deployment, check the following items in order:
- Low hit rate: check the system prompt and templates for dynamic fields such as timestamps or request IDs, and move them outside the prefix.
- Steadily rising memory fragmentation: check whether the block size matches the request length distribution, and whether the pre-allocation ratio is too high.
- TTFT gets worse after offloading: check for network jitter and for extra synchronization points on the offload and restore path.
- Output differs from the non-cached result: check that the snapshot dtype matches the compute precision, and verify the tensor parallel partitioning.
- Abnormal results after a cross-node hit: check the model version and the checksums of the weight files on both nodes.
Deployment Checklist
Before going live, confirm each of the following:
- The inference framework, CUDA driver, and model weight versions are pinned and recorded in the deployment configuration.
- Memory alert thresholds are set from your own load test results, not copied from other deployments.
- Network bandwidth between nodes meets the snapshot transfer requirements, and real-time monitoring is in place.
- A fallback path exists. If the cache service fails, disable reuse and send all requests through a full prefill to keep the service available.
- The context compression strategy is designed together with the caching strategy. A compressed prefix should be stable, so that checkpoints are not rebuilt on every turn.
When This Approach Pays Off
The benefits of this design come mainly from workloads with stable prefixes and high reuse across turns. If each turn rewrites the context substantially, or if sessions share almost no prefix, the cache hit rate will be low. The extra memory and scheduling overhead may then outweigh the gains. Before you commit significant resources, replay real traces and examine the hit rate and TTFT distribution. This is usually the safer path.
