KV Cache Reuse Under Agent Workloads: Why Cache Hit Rates Decide Cost, Latency, and Throughput

    As agentic applications shift from single-question answering to long-horizon execution, the structure of LLM inference workloads has changed fundamentally. This article analyzes KV cache reuse from an inference-serving perspective and explains why cache hit rates have become a decisive factor for cost, latency, and throughput. It covers the two defining traits of agent workloads—extremely high input-to-output token ratios and the dynamic loading of relatively static content—then examines why prefix-matching rules make cache reuse difficult and why hit rates stay low. Finally, it lays out concrete optimization paths across context engineering, cache mechanisms, session management, dynamic loading, and structured output, together with the metrics needed to guide these efforts.

    1. Introduction: How the Agent Boom Is Reshaping Inference Workloads

    Agentic applications have spread rapidly over the past while. Researchers, developers, and even non-programmers can now complete a wide range of tasks through AI coding tools or general-purpose agent platforms, such as:

    • Writing and debugging code;
    • Organizing and summarizing documents;
    • Automatically performing information retrieval, form filling, and other operations in a browser.

    The mechanics of many agents are not complicated. They use an LLM as the decision-making core and keep advancing through an “observe–think–call tools–observe again” loop until the task is complete or a termination condition is reached.

    After a month of intensive hands-on use, the most striking observation is that a single task often consumes one to two orders of magnitude more processing tokens than before. Behind this lies a real shift: in the agent era, the structure of LLM inference workloads has changed substantially, which makes a fresh look at efficiency necessary.

    This article breaks down these changes from an inference-serving perspective and focuses on answering three questions:

    1. What exactly has changed in the workload?
    2. Why is cache reuse the first thing affected?
    3. At which engineering layers should we respond?

    2. A New Workload Profile: Two Traits of Agents

    2.1 Extremely High Input-to-Output Ratios

    Definition. The input-to-output ratio is the ratio of input tokens to output tokens in a single call. The input side can be split into “uncached input” that must be recomputed and “cached input” that can be reused directly. In public technical talks about agents and in my own measurements, this ratio commonly reaches 100:1, and for long-document understanding or code-repository analysis tasks it can approach 1000:1.

    Compared with conversational workloads.

    Dimension Traditional conversational/writing workload Agent long-horizon task workload
    Input-to-output ratio per call ~2:1 to 10:1 ~100:1 to 1000:1
    Main input components The question itself, a few retrieved snippets, message history System instructions, tool definitions, skill docs, long-term memory, historical traces, tool return content
    Call pattern Mostly one question, one answer Multi-turn loops with accumulating intermediate results and observations
    Context evolution Usually appended turn by turn Both appending and trimming/reordering
    Main performance bottleneck Decode speed, concurrency Prefill compute, cache capacity and bandwidth
    Cost focus Output tokens Uncached input tokens

    Why the ratio is pushed so high. The size of the input side is determined by the structure of the agent itself:

    • System instructions and tool descriptions can run to thousands of tokens;
    • A single skill doc or business specification may reach tens of thousands of tokens;
    • Web page bodies, search results, logs, stack traces, and code snippets returned by tools are naturally verbose;
    • Across multi-turn loops, historical reasoning and observations keep accumulating.

    The output side is comparatively restrained: a single call often needs only a few hundred tokens of tool-call arguments or a brief judgment. A large amount of output must also go through structured parsing before it can be acted on, so the model tends to “think a lot and write little.”

    The input-to-output ratio matters because it directly determines the cost structure and where the bottleneck lies:

    • The cost center shifts. The effort of processing tokens and generating tokens can differ by a hundredfold. Generation is no longer the main concern; most of the cost lands on the input side.
    • The hardware bottleneck shifts. Traditional inference optimization centers on decoding: single-token decoding is constrained by memory bandwidth, its latency is relatively stable, and higher throughput comes mainly from batching. Long-context prefill, by contrast, quickly hits the compute ceiling in large matrix operations, and its per-token processing cost is clearly higher than decoding. In agent workloads, the GPU spends most of its time on prefill, and both batching and parallel splitting need to be redesigned around this characteristic.

    2.2 Dynamic Loading of Static Content

    Definition. Much of the content an agent needs to reference is “relatively static”: it does not change across conversation turns. Examples include the usage instructions of a mature skill, long-term memory, business documents and knowledge-base entries, and—in multimodal scenarios—images and audio/video clips. But the moment and position at which this content is written into the context are not fixed. That is what “dynamic loading” means.

    The dynamism comes from three kinds of uncertainty:

    • Uncertain timing. A skill doc is usually loaded only when the model decides to call that skill; it may or may not be used, and when it loads depends on the model’s in-the-moment decision.
    • Uncertain position. The same document may appear after the system message, in the middle of the conversation history, or right next to the latest tool result, depending on the context assembly strategy and retrieval results.
    • Uncertain form. The model may first browse a skill catalog and then load the full document on demand; multimodal material may also be injected in batches as the task progresses.

    This design fits the core needs of agents. Although the context window keeps growing, tokens remain expensive, and the attention computation cost grows with context length. On-demand loading effectively controls the context size of a single request and lets the model focus on information relevant to the current step.

    The cost, however, is passed on to the cache. The same relatively static content, when concatenated with other fragments at different times and in different orders, is hard to place at the same position in the token sequence—and may even fail to form a stable prefix.

    3. The Core Conflict: Cache Reuse Under Prefix-Matching Rules

    3.1 Why Cache Reuse Determines Cost

    In the pricing schemes of mainstream LLM services, input tokens for the same model usually carry two prices: uncached input tokens and cached (cache-hit) input tokens. In the published pricing of leading providers, the former typically costs only about one-tenth of the latter, though the exact ratio depends on each provider’s published figures.

    This price gap directly determines the size of the cost lever. In scenarios with a 100:1 or even 1000:1 input-to-output ratio, moving the vast majority of input tokens from “uncached” to “cached” can, on the input side alone, reduce theoretical cost to roughly one-tenth. The following minimal model quantifies this (all numbers are illustrative and only demonstrate the order-of-magnitude relationship):

    1. # Values are illustrative only, to show the order-of-magnitude relationship.
    2. # They do not represent any vendor's actual pricing.
    3. PRICE_MISS = 10.0 # Unit price of uncached input tokens
    4. PRICE_HIT = 1.0 # Unit price of cached input tokens
    5. PRICE_OUT = 30.0 # Unit price of output tokens
    6. def task_cost(uncached_tokens: int, cached_tokens: int, output_tokens: int) -> float:
    7. return (uncached_tokens * PRICE_MISS
    8. + cached_tokens * PRICE_HIT
    9. + output_tokens * PRICE_OUT)
    10. # A single task: ~100k input tokens, 1k output tokens, ratio 100:1
    11. # Before: skill docs and history are recomputed from scratch almost every time
    12. before = task_cost(uncached_tokens=100_000, cached_tokens=0, output_tokens=1_000)
    13. # After: 90% of input tokens hit the cache
    14. after = task_cost(uncached_tokens=10_000, cached_tokens=90_000, output_tokens=1_000)
    15. print(f"Before: {before:,.0f}")
    16. print(f"After: {after:,.0f}")
    17. print(f"Reduction: {1 - after / before:.1%}")
    18. # Sample output (illustrative):
    19. # Before: 1,030,000
    20. # After: 120,000
    21. # Reduction: 88.3%

    In this example, input-token utilization improves by 90% and overall cost drops by about 88%.

    Look at it the other way: when cache hits are insufficient, the waste is amplified by the same ratio. If a system instruction or specification document repeats in every loop turn, then even if it accounts for only ten percent of a single input, being uncached forces it to be re-prefilled every turn—effectively multiplying its compute cost by the number of loop turns. A single agent task often involves several to dozens of loop turns, and this kind of repeated overhead accumulates quickly.

    The performance gains are equally significant:

    • A cache-hit prefix needs no recomputation, so time-to-first-token drops;
    • Lower prefill compute cost means the same hardware can serve more concurrent sessions.

    3.2 Why the Hit Rate Is Low

    Mainstream context caching generally follows an exact-prefix-match rule: only tokens that are identical to the cached content starting from the beginning of the sequence can directly reuse the corresponding cache state. Causal attention dictates this strictness—the attention state at each position depends on all preceding tokens, so if any position in the sequence changes, the cached state for every subsequent position is, in principle, invalidated.

    Take a skill doc as an example. Suppose it has already been prefilled as part of the context, but in the next loop turn the model appends new tool results, and the system instructions or conversation history before the document may also be reorganized. As long as anything before it differs, the document’s own cache cannot be reused, and all of its tokens must be re-prefilled. Static content should be the ideal object for cache reuse, yet dynamic loading is exactly what breaks the stability it needs to serve as a prefix. Beyond this, two other common factors apply:

    1. Little content sharing across sessions. The cache is usually effective only locally within a service instance. Even if two users call the same skill doc, as long as the prefixes differ, they cannot reuse each other’s cache.
    2. Limited cache capacity and lifetime. Long contexts consume considerable cache space; when capacity is limited, high-frequency sessions evict the cache of low-frequency ones.

    4. Optimization Paths: Making Static Content Reusable Again

    4.1 Context Engineering: Keeping the Prefix Stable

    The most direct optimization is to make “static” content actually sit in a stable prefix at the design level. Three principles can be followed:

    • Stable to volatile. Arrange the context from top to bottom as system instructions, tool definitions, skills and specifications, long-term memory, conversation history, retrieval results, and the latest tool returns; content that changes less frequently goes closer to the top.
    • Append-first. In multi-turn loops, only append new content to the tail of the history; avoid inserting or reordering content in the middle. When you need to control context length, compress or trim old turns at the tail rather than rewriting the parts near the beginning.
    • Keep it byte-for-byte consistent. Inject the same content identically each time, including whitespace, line-break style, timestamps, and ordering. For example, sort the skill list by a fixed name order and sort retrieval results by a stable rule, to avoid needless invalidation from ordering jitter.
    1. import hashlib
    2. def build_prompt(system: str, skills: dict, history: list,
    3. memory: list, tool_results: list) -> str:
    4. # Stable region: changes only on version upgrade, validated as one block
    5. stable = [system]
    6. stable += [skills[name] for name in sorted(skills)] # fixed order, avoid jitter
    7. stable += [memory[i] for i in range(len(memory))] # memory appended by stable index
    8. stable = "\n\n".join(stable)
    9. # Volatile region: changes every turn, placed at the tail
    10. volatile = ["\n\n".join(history), "\n\n".join(tool_results)]
    11. # Use "did the stable region change" as a cache diagnostic signal
    12. stable_id = hashlib.sha256(stable.encode()).hexdigest()[:12]
    13. print(f"[cache-hint] stable-block-id={stable_id}")
    14. return stable + "\n\n" + "\n\n".join(volatile)

    The same rules apply to API calls. Some providers’ chat interfaces support marking cache positions within the message list. Developers can place system instructions, tool definitions, and long documents as a “fixed opening,” put the constantly changing tool results after them, and set a cache breakpoint next to the stable content.

    4.2 Cache Mechanisms: Explicit Breakpoints and Cross-Request Sharing

    A stable prefix is only the precondition; actually putting the cache to use also depends on the capabilities of the cache mechanism itself:

    • Explicit cache breakpoints. Allow developers to actively declare that “this content needs to be cached,” or to mark cache positions themselves. This suits large, frequently reused content such as system instructions and long documents.
    • Cross-request, cross-session prefix sharing. Manage the cache at the content level (for example, block-level indexing based on hashes or prefix trees), so identical prefixes appearing in different users’ or sessions’ requests can reuse each other. Skill docs, shared specifications, and knowledge-base entries have high overlap at the population level, and sharing them yields significant gains.
    • Prefix-aware instance affinity. Route requests that carry the same session ID or the same prefix hash to the same inference instance, so an established cache stays local and cross-instance recomputation is reduced.
    • Cache capacity and eviction policy. Reserve space for high-frequency stable blocks according to “block size × expected number of reuses,” and set a reasonable lifetime for long contexts. This requires observability to continuously track changes in the hit rate.

    4.3 Session Management: Multi-Turn Reuse and Request Merging

    Every agent loop turn must carry the history; if each turn waited for a full prefill, latency would accumulate linearly with the number of turns. Workable approaches include:

    • Incremental continuation by session ID. Some inference services support continuing a multi-turn conversation by carrying a session identifier, and the server reuses the previously computed prefix. The application side should ensure every turn carries the same identifier and that the prefix only grows and is never changed.
    • Merging redundant LLM calls. Combine multiple model calls in a “plan–execute–judge” flow that could be done in one pass into a single structured output. This reduces both the total token count and the number of prefix rebuilds.

    4.4 Decoupling Dynamic Loading from Caching

    If some content inevitably has to be loaded dynamically, try separating “decision” from “computation”:

    • Two-stage pattern. First use a lighter model or classification rules to decide whether a skill doc is needed; only when it is, hand it to the main model for full processing, so irrelevant content does not repeatedly enter the long context.
    • On-demand summarization. Generate a summary of a long document to keep resident in the context first, and expand the original text on demand when the model needs details.
    • External memory. Keep long-term memory outside the context and fetch it on demand through separate retrieval calls; the retrieval results themselves can also be cached.

    4.5 Structured Output Constraints

    Agent output is mostly tool-call arguments. Replacing “free generation + parsing + retry on error” with format-constrained decoding (such as a restricted JSON mode) reduces retries caused by formatting errors. A retry means the entire context is prefilled all over again; in scenarios with extremely high input-to-output ratios, the cost of a single retry is nearly equal to that of a brand-new complete request.

    5. Evaluation and Measurement: Making Optimization Data-Driven

    Optimizing cache reuse should not rely on gut feeling. It is worth establishing a set of baseline metrics:

    • Cache hit rate. The share of cache-hit input tokens among total input tokens; this is the single most core metric.
    • Average input-to-output ratio. Reflects the workload structure and also determines the size of the optimization lever.
    • Time-to-first-token and total task latency. Measure interactive responsiveness and task completion speed, respectively.
    • Total cost per task. Summed after pricing cached and uncached input and output separately.
    • Task success rate. Guards against over-trimming the context for the sake of caching, which would degrade agent performance.

    In a real inference service, these metrics can be continuously tracked through call logs, metric collection, and monitoring and alerting. A practical approach is to maintain a “size–reuse count–hit rate” profile for each type of skill doc, and use it to decide whether the content is worth keeping resident in the cache.

    6. Conclusion

    Agents move large models from “one question, one answer” to “long-horizon execution,” and the workload structure changes accordingly. The input-to-output ratio leaps from single digits to hundreds or even thousands, while skills, memory, and documents are dynamically assembled into the context. Under these two traits, cache reuse is no longer just an internal detail of the inference engine but a key design variable that simultaneously affects cost, latency, and throughput.

    For developers, there are three actionable starting points:

    1. Measure. Track the input-to-output ratio and cache hit rate of typical tasks to determine where to focus optimization.
    2. Stabilize the prefix. Reorganize the context on the principle of “stable first, volatile later,” avoiding meaningless content changes.
    3. Use the cache well. Enable caching capabilities and take advantage of session continuation, so highly repetitive static content is truly reused across multiple calls.

    From call logs and metric collection to monitoring and alerting, building an observability loop around the inference workload is the foundation that keeps these optimizations effective. In the agent era, where token consumption is rising sharply, whoever reuses existing computation more fully will be able to support longer and more complex tasks at lower cost.