Hybrid-Architecture LLM State Cache Optimization: Accelerating Agent Workloads in Practice

    This article explains why hybrid architectures that combine full attention layers with linear layers make inference caching harder for coding, data analysis, and operations agents. It covers how KV cache and recurrent state differ, and how a unified cache index, tiered storage, agent-oriented scheduling, and performance metrics can address those differences. It also lists engineering considerations for deployment.

    As large language model applications move from single-turn question answering toward complex task execution, coding agents, data analysis agents, and automated operations agents typically need to repeatedly read historical context and generate new reasoning results after several rounds of tool calls. Compared with ordinary chat requests, these workloads have longer contexts, longer request durations, higher prefix repetition rates, and more volatile concurrency. As a result, the bottleneck of inference systems is often no longer matrix computation capacity alone. It is how efficiently context state can be stored, looked up, reused, and migrated.

    In recent years, hybrid architectures that combine full attention layers with linear layers have attracted growing attention. Full attention layers are good at modeling long-range dependencies. Linear layers use recurrent states or compressed representations to reduce computation and cache size during decoding. Combining the two can, to some extent, balance model quality, decoding speed, and GPU memory usage. However, this structure also turns cache management from a single KV Cache problem into a composite problem, in which KV cache and linear states coexist.

    1. Why Hybrid Architectures Fit Agent Workloads

    Traditional Transformer inference revolves mainly around the KV Cache. For context that has already been processed, the system can store the Keys and Values produced by the attention modules in each layer and reuse them in later generation steps. This avoids repeated computation. As long as the prefix content stays the same, a cache hit can significantly reduce prefill cost.

    Hybrid architectures are more complex. Full attention layers usually still need to store token-indexed Keys and Values. Linear layers may maintain an internal state that evolves as the sequence is processed. This state cannot always be sliced, concatenated, and reclaimed per token as simply as the KV Cache. It may depend on the accumulated results of earlier inputs, so it is more sequential and holistic in nature.

    In a coding agent, one complete task may include:

    1. System prompts and tool definitions;
    2. The user’s original request;
    3. Analysis generated by the agent;
    4. Multiple rounds of code reading, searching, execution, and test results;
    5. Logs, error messages, and intermediate artifacts returned by tools;
    6. Later rounds that refer back to earlier information.

    Much of this content stays the same across requests, such as system instructions, tool descriptions, project directory structures, and shared conversation prefixes. If the system can cache only the KV of attention layers and cannot reuse linear layer states efficiently, each request still has to reprocess a large amount of historical content. This weakens the benefit of caching.

    2. The Core Challenge: Two Types of State Cannot Be Managed the Same Way

    Cache optimization for hybrid architectures involves at least three key issues.

    1. Different State Granularity

    KV Cache lends itself to management in token blocks. The system can split continuous context into fixed-size blocks and use hashing or prefix indexing to determine which blocks can be reused.

    Linear states are usually tied to the cumulative process of an entire sequence. Copying them to every token position creates a large amount of redundancy. Saving only the final state, however, may not support forking from intermediate positions. The system therefore needs different splitting and reuse strategies for different layers.

    2. Different Dependency Relationships

    Attention cache entries can usually be located by their position in the context. Recurrent states have clear causal dependencies. Each later state builds on earlier states, so the order cannot be changed arbitrarily. When an agent executes branching tasks, the same historical context may lead to several different follow-up requests. The system must avoid sharing states incorrectly.

    3. Different Cache Lifecycles

    The KV data of a request may keep growing during generation, while a linear state may stay stable once a certain prefix has been processed. The creation, reading, eviction, and migration of the two types do not happen at the same time. If both are handled under one lifecycle, the system may waste GPU memory, copy data too often, or see lower hit rates.

    A more reasonable approach, then, is not simply to increase cache capacity. It is to build a “hybrid state cache” mechanism. Attention states and linear states are modeled separately, and a unified scheduler coordinates them based on request prefixes, layer types, and resource status.

    3. A Unified Cache Index for Broader Prefix Reuse

    One workable design is a unified state index for every context segment. The index should record not only whether a token block exists, but also the layer type of that block, the location of its state, the prefix it depends on, and its storage tier.

    For illustration, a cache entry could contain the following fields:

    1. CacheEntry {
    2. prefix_signature // Signature of the prefix content or structure
    3. token_range // Corresponding context range
    4. attention_state // Location of the attention layer cache
    5. recurrent_state // Location of the linear layer state
    6. parent_signature // Parent prefix this entry depends on
    7. storage_tier // GPU memory, host memory, or remote storage
    8. last_used // Time of most recent use
    9. ref_count // Current number of references
    10. }

    The key point is not the specific data structure. It is that both types of state sit within one traceable prefix relationship. With this structure, the scheduler can determine whether a request that hits part of the attention cache also has a complete, usable linear state. If the match stops at an intermediate position, the scheduler can decide whether to resume computation from the nearest valid checkpoint. When several requests share one prefix, the scheduler can also decide which states can be shared read-only and which must be copied.

    In practice, prefix signatures should be generated from stable content, such as system prompts, tool definitions, and historical messages that are confirmed not to change. Dynamic timestamps, random identifiers, or frequently changing logs should not appear before reusable prefixes. Otherwise, the cache hit rate will drop.

    4. Tiered Caching Is Key to Reducing Time to First Token

    Hybrid state caching usually needs to be managed across several storage media.

    GPU Memory Tier

    GPU memory offers the highest access speed, so it suits states that are being decoded, are about to be used in computation, or have the highest hit probability. Its capacity is limited, though, and it cannot hold every long-context task. The GPU memory tier should therefore prioritize active requests, hot prefixes, and the working set that is about to run.

    Host Memory Tier

    Host memory usually has more capacity than GPU memory. It can hold caches that are temporarily inactive but still have a high reuse value. Reloading states from host memory into GPU memory adds transfer overhead. The system needs to prefetch based on hit probability and request queuing time, so that compute resources do not wait for data.

    Distributed Storage Tier

    When several inference nodes need to share prefix states, distributed storage can extend the hierarchy. This tier suits caches with long lifetimes and wide reuse, such as common system prompts, stable tool descriptions, and shared context for large projects.

    Distributed caching does not mean that every state should move across nodes. For small states with low computation cost, recomputing may be faster than a network read. For large states with high repetition, remote reuse is more valuable. Decisions should therefore compare transfer cost with recomputation cost.

    5. Scheduling Strategies for Agent Workloads

    Requests from coding agents do not arrive evenly. After a tool call finishes, several new requests may follow within a short time. The inference system should optimize scheduling for this burst pattern.

    First, the scheduler can group requests by prefix signature. Requests that share a long prefix should be batched together to reduce repeated prefill. Second, state loading can overlap with model computation. While the GPU processes the current batch, a background thread can prefetch cache entries that the next batch may hit. Third, for several branch requests that share the same prefix, the system can use read-only sharing. When one branch creates a new state, the system performs copy-on-write.

    The scheduler should also distinguish the prefill stage from the decoding stage. Prefill depends more on high throughput and contiguous memory access. Decoding is more sensitive to per-step latency and scheduling jitter. If cache migration happens on the decoding critical path, users may notice clear stuttering even when overall throughput is high. State migration is therefore best scheduled before prefill or during batch transitions.

    6. How to Evaluate Performance Gains

    A cache optimization should not be judged by average throughput alone. Evaluation should also cover the following metrics:

    • Prefill throughput: the number of input tokens processed per unit of time;
    • Time to first token: the time from request submission to the first generated token;
    • p90 or p99 latency: the real experience of long-tail requests;
    • Cache hit rate: including full hits, partial hits, and cross-node hits;
    • State migration traffic: the data movement among GPU memory, host memory, and remote storage;
    • Recomputation ratio: the amount of context computation that is re-executed after cache misses;
    • GPU memory utilization: whether the cache squeezes space needed for model computation;
    • Concurrency stability: whether queuing or jitter appears under peak load.

    In public testing, when real coding agent traces were replayed, the hybrid state management approach reached up to 3.14 times the prefill throughput of a conventional inference framework. It also reduced p90 time to first token by up to 88.4%. These results show that the key to optimization is not only shrinking each state. More important is improving the completeness of prefix reuse and reducing repeated prefill and unnecessary data movement.

    When the system adds hundreds of GiB of host cache, the optimization benefits remain. This indicates that tiered caching has practical value for long-context scenarios. However, the actual gains depend on factors such as prefix repetition rate, request concurrency, context length, state size, network bandwidth, and eviction policy. They should not be extrapolated directly to every model or workload.

    7. Engineering Considerations for Deployment

    First, cached content must be strictly bound to the model configuration. If the vocabulary, positional encoding, layer structure, or inference precision changes, old cache entries may not be safely reusable.

    Second, the system needs a complete invalidation mechanism. When user permissions, project versions, or tool definitions change, related prefixes must be invalidated promptly. This prevents outdated context from being applied to new requests.

    Third, cache security boundaries must be enforced. Agent context may include code, secrets, business data, and tool outputs. When sharing across requests, tenants, or nodes, the system must apply isolation, encryption, and access control.

    Fourth, the overhead of managing small objects needs attention. If caches are split too finely, the cost of indexing, metadata, and scheduling rises quickly. If they are split too coarsely, the system loses some ability to hit partial prefixes. Block size should therefore be tested against the context structure and the actual hit distribution.

    Fifth, real traces should be collected first. Manually constructed long texts cannot fully reflect the branching, rollback, and tool-call patterns of agent requests. Only replaying desensitized real workflows can show whether a cache design actually improves end-to-end experience.

    Conclusion

    Hybrid architectures reduce decoding cost and cache pressure by introducing linear states. They also move inference systems from managing a single KV cache to coordinating several types of state. For long-context, multi-turn, and coding agent workloads, the most effective optimization path includes a unified prefix index, distinct handling of state granularity, tiered storage, cross-node reuse, and scheduling that hides the overhead of state migration.

    Future inference infrastructure should not be designed only around whether a model fits in GPU memory. It should also address how states flow among computation, storage, and networks. Systems that identify reusable prefixes more accurately, store hybrid states at lower cost, and prefetch them before requests arrive will be better positioned to deliver higher throughput and lower time to first token under complex agent workloads.