LLM Workloads in the Agent Era: Two Defining Traits and KV Cache Reuse Engineering
Over the past year, agentic applications with long-horizon planning and tool-calling abilities have moved from experiments into daily use—writing code, reading documents, driving browsers, and chaining multiple systems to accomplish a concrete task. A strong intuition emerges after sustained use: agents do not make large models "cheaper," they fundamentally restructure the workload, changing the compute distribution, state management, and billing model on the inference side. This article stays away from specific products and focuses on two quantifiable traits behind this workload shift, and the hard constraints they place on KV cache reuse rates and system design.
1. Trait One: A Sharp Prefill/Decode Imbalance
The phenomenon and its scale
In traditional conversational workloads, input and output sit at roughly the same order of magnitude, occasionally leaning slightly toward input. Agent scenarios are the opposite. A complete task typically runs a loop of “read context → decide → call a tool → observe and write back the result → decide again,” and every round feeds all prior history back into the context. As a result, the ratio of prefill tokens to decode tokens is pushed to empirical ranges like 100:1 or even 1000:1.
A long-horizon task’s token budget can be written roughly as:
Total cost ≈ Σ_i ( P_i + D_i )where P_i ≈ S_0 + Σ_{j<i} (A_j + O_j) // input length of round iD_i is usually only a few hundred to a few thousand // thinking + actions generated this round
When the number of rounds n reaches tens or hundreds, ΣP_i grows roughly quadratically while ΣD_i grows only linearly. This is the mathematical origin of the imbalance: it is a function of turn complexity, not single-turn complexity.
Why this shifts the center of system design
The decode phase is bounded by memory bandwidth and is memory-access intensive; the prefill phase is dominated by matrix multiplication and is compute intensive. When the workload moves from 1:1 to 100
- TTFT (time to first token) replaces TPOT as the primary experience bottleneck. Users wait for “when this round starts emitting tokens,” and first-token latency is almost entirely determined by prefill queuing and prefix-hit conditions.
- The compute-utilization curve changes. When decode dominates, you rely on large batches and continuous batching to amortize memory access; when prefill dominates, you must prevent long sequences from clogging the batching window and starving short requests. Common industry responses include chunking large prefills and interleaving them with decode requests in scheduling, or splitting the two workload types into separate resource pools and scaling each according to its own bottleneck.
- Cost and latency become more tightly coupled. Under token-based billing where input greatly exceeds output, any long prefix that “could have been reused but was recomputed” simultaneously raises the bill and the P99 first-token latency.
2. Trait Two: Dynamic Loading of Relatively Static Content
What makes agents effective is stuffing large amounts of relatively static knowledge into the context: skill descriptions and invocation specs, long-term memory and history summaries, project documents and interface definitions, retrieved fragments, and in multimodal scenarios, screenshots, audio, and video frames.
The key to “dynamic loading” is a triple uncertainty:
- Uncertain timing: which round needs which piece of knowledge is decided by the model itself;
- Uncertain content: retrieval results change as indexes update and data changes;
- Uncertain position: the same skill document may appear right after the system prompt one time, and be sandwiched between history messages and tool results the next.
By contrast, a traditional application’s prompt is assembled offline with a fixed structure. An agent’s context is assembled incrementally at runtime, which directly destroys the preconditions for cache reuse.
3. Root Cause: KV Cache Reuse Is Locked by Strict Prefix Matching
The constraint itself cannot be circumvented
Causal attention means the KV of the k-th token depends only on tokens 1..k. So whether a segment of content can be reused depends on whether all tokens before it are byte-for-byte identical. The reuse rate can be written as:
Reuse rate = LCP(prefix_A, prefix_B) / len(prefix_B)
LCP is the longest common prefix. Note two unforgiving properties of this definition: only the prefix can be reused; after the first differing token, everything downstream is invalidated.
So an 8000-token skill document, even if its content hasn’t changed by a single character, yields a hit benefit of 0 if a timestamped greeting is prepended to it. In long-document scenarios this waste is proportional, not fixed.
The pricing model amplifies the problem by an order of magnitude
Mainstream pay-as-you-go schemes commonly use a three-tier basis: input tokens that hit the cache, input tokens that miss the cache, and output tokens. The industry-standard approach makes the hit tier roughly an order of magnitude cheaper than the miss tier. Plugging that into the cost model:
Cost = C_in_miss · P_miss + C_in_hit · P_hit + C_out · DIf C_in_hit ≈ 0.1 · C_in_miss, and P_miss + P_hit = 100 · Dthen raising the P_hit share from 20% to 90% can cut total cost severalfold
The conclusion is direct: in workloads with a prefill/decode ratio above 100:1, the cache hit rate is not a performance detail but the primary cost variable. It deserves to be governed as a first-class metric, not tuned after the fact.
Common prefix breakers
- Injecting the current time, a random session ID, a user nickname, or a tenant ID into the system prompt;
- An unsorted tool list, or one that is dynamically added to and removed from based on availability, shifting the entire tool-declaration block;
- Unstable ordering of memory/skill retrieval results (tied scores, timestamp sorting, concurrent writes);
- Conversation history rewritten “in place” (compressing old messages, deleting intermediate turns, backfilling erroneous messages);
- Multimodal inputs arriving under different encodings/resolutions, inconsistent at the byte level;
- Placing volatile fields before stable fields (order reversed).
4. Practice One: Cache-Friendly Context Orchestration
The core principle in one sentence: layer by rate of change, with the more stable content placed further forward.
[Layer 0 | almost never changes] Role definition, output spec, safety constraints, tool declarations (sorted)[Layer 1 | low-frequency changes] Skill docs, domain knowledge, long-term memory (sorted by stable key)[Layer 2 | medium-frequency changes] Retrieved fragments, task context, user preference summary[Layer 3 | changes every turn] Conversation history, tool results, timestamps and other volatile metadata
Anti-patterns and their fixes, side by side:
# Anti-pattern: dynamic content pollutes the prefix, forcing a full recompute on every calldef build_prompt(tenant, skills, history):return f"""You are an assistant. Current time={now()}, tenant={tenant}Available tools={list(tools.keys())} # order varies with registration order{''.join(skills.values())} # order varies with retrieval scores{render_history(history)}"""# Fix: stable prefix + append-only history + stable sorting + volatile items placed lastSYSTEM = """You are an assistant. Follow the output spec and safety constraints.""" # constant; never interpolate time/IDTOOL_BLOCK = "\n".join(sorted(TOOLS)) # sorting guarantees byte-identical outputdef build_prompt(skill_hits, history):skill_block = "\n".join(s[1] for s in sorted(skill_hits, key=lambda s: s[0]))tail = "\n".join(render(msg) for msg in history) + f"\nCurrent time: {now()}"return f"{SYSTEM}\n{TOOL_BLOCK}\n{skill_block}\n{tail}" # volatile content only at the tail
Two accompanying disciplines:
- Append to history; never rewrite it. When compressing history, “freeze the old segment + append a summary as a new block” rather than replacing the original message—replacement invalidates everything after it.
- Add stable keys to retrieval results. Sort by document ID + version number rather than floating-point similarity; when scores tie, break ties by ID, otherwise concurrent writes cause ordering jitter.
5. Practice Two: Supporting System Capabilities on the Inference Side
No matter how well the application layer is built, the inference side must provide sufficient cache capacity and scheduling support.
- Cache pools and capacity tiering: prefix KV caches are typically tiered as VRAM → main memory → local/remote storage, with hot blocks kept in VRAM, warm blocks swapped out to main memory, and cold blocks sunk to object-storage-class media. Eviction cannot rely on LRU alone; once a long document is evicted, its rebuild cost far exceeds that of a short request, so weighting by “recompute cost × reuse probability” (LFU or cost-aware eviction is closer to optimal) is needed.
- Session-affinity routing: with multi-replica deployment, if consecutive requests from the same session land on different replicas, the cache is naturally invalidated. Consistent hashing on the session ID is the most direct step to improve the hit rate.
- KV footprint governance: attention structures like GQA/MQA, KV quantization, and some attention-mechanism designs essentially compress the “state that must be cached per token,” letting the same memory hold more prefixes and effectively raising the hit rate.
- Prefill and decode scheduling coordination: chunk long prefixes and interleave them with decode to avoid long prefills blocking short requests; workloads with extremely high prefill/decode ratios should also consider independently scaling the prefill resource pool.
- Asynchronous and batch tasks: for tasks like bulk document processing and offline code scanning, requests can be clustered by prefix and merged so identical prefixes are computed only once.
6. Practice Three: Turning the Hit Rate into an Observable Metric
Optimization must be measurable first. Instrument at least these metrics:
| Metric | Meaning | Optimization goal |
|---|---|---|
prefix_cache_hit_ratio |
Hit input tokens / total input tokens | Core cost metric |
avg_reused_prefix_len |
Average reused prefix length per request | Distinguish “short prefix” from “total invalidation” |
first_token_latency |
First-token latency P50/P99 | Experience metric |
prefill_tokens_per_request |
Prefill tokens recomputed per request | Locate context bloat |
cost_per_task |
Cost per task (not per request) | Business-level cost |
With avg_reused_prefix_len, you can distinguish two entirely different classes of problems: a low hit rate with a medium reuse length usually points to ordering jitter or metadata-insertion-position issues; a reuse length near 0 usually means something upstream keeps changing (a timestamp or session ID placed at the front). Putting hit rate, TTFT, and per-task cost on the same dashboard, combined with logging and monitoring/alerting for trend and anomaly detection, is what closes the loop.
7. Application-Layer Cost Controls
- Progressive disclosure: expose only the name and a one-line description of skills/tools first, and inject the full document once the model decides to call. This saves tokens and reduces interference from irrelevant content on attention.
- Context isolation: hand large-scale material processing to subtasks/sandboxed contexts and return only conclusions to the main context, avoiding intermediate steps occupying the window over the long term.
- Structured output: require compact formats like JSON/tables to reduce the decode overhead from decorative natural language.
- Model tiered routing: route simple classification, extraction, and format conversion to small models and complex planning to stronger models; control cost through capability tiers rather than a uniform tier.
- Task-level budget management: set token and turn limits for each agent task, paired with cost alerts, to prevent long-horizon loops from spiraling out of control.
8. General Recommendations for Cloud Deployment
Agent workloads typically exhibit the traits of “bursty traffic + long contexts + rich session state,” making them well suited to elastic scaling and canary releases of inference services on a container platform, using object storage for cold KV, model weights, and document indexes, using message queues to smooth peaks and decouple asynchronous tasks, and using logging and monitoring/alerting to build an observability loop for hit rate and cost. Baidu AI Cloud offers corresponding foundational capabilities across these general categories, but concrete selection and parameters should be based on your own workload profile and measured benchmarks, rather than copying someone else’s configuration.
Conclusion
The real change agents bring is this: the object of optimization shifts from “model calls” to “context engineering.” The prefill/decode imbalance makes prefill the primary cost item, and dynamic loading makes prefix matching the primary risk point. Together they push KV cache reuse to the top priority of system design. Teams that think this relationship through clearly and put it into practice as “stable prefix + append-only history + affinity routing + cost-aware caching” typically gain a unit-cost advantage under equal model capability—not an order-of-magnitude illusion, but a real severalfold difference.
