LLM Inference Performance Optimization for Long-Context Agentic Workloads
This article examines how to optimize inference performance for large language models serving long-context, multi-turn agentic workloads. It explains why traditional single throughput metrics are insufficient, outlines the constraints introduced by sparse activation models, and presents a measurement-first approach to bottleneck isolation. Key techniques covered include prefix caching, chunked prefill, continuous batching, quantization, and combined parallelism strategies, along with common pitfalls and guidance for running these optimizations on cloud infrastructure.
1. Why Agentic Workloads Are a New Battleground for Inference Performance
Traditional online inference has a relatively simple load profile: short inputs, short outputs, and independent requests. A new generation of applications built around AI agents has completely changed this profile. In a typical scenario, the first turn receives roughly fifty thousand tokens (including the system prompt, tool descriptions, historical documents, and retrieval results), followed by ten to fifteen additional turns within the same session, where each turn carries the entire prior context.
This type of workload has three structural characteristics:
- An extremely long prefill phase on the first turn: compute-intensive, constrained mainly by compute capacity and parallel efficiency.
- An incremental decode phase across subsequent turns: memory-access-intensive, constrained mainly by memory bandwidth and cache capacity.
- Monotonically growing context: the key-value cache accumulates with every turn, expanding both memory usage and the scope of attention computation in tandem.
For this reason, a single unified “tokens per second” metric is not enough to describe an entire session. In engineering practice, it is usually necessary to break the metrics apart: time to first token, prefill throughput, decode throughput, total session completion time, and peak memory usage per session. The hundreds of tokens per second throughput mentioned in the source material is essentially a decode-side optimization result under long-context, multi-turn conditions, not a single average number.
2. New Constraints from Extremely Large Sparse Activation Models
Flagship models often adopt a sparse structure with “a very large total parameter count but a small number of activated parameters per token.” This design reduces the computation per token but shifts the pressure elsewhere:
- Massive weight read volume: even if only a subset of experts is activated each time, all expert weights must still reside in memory, so capacity pressure does not decrease with the activation ratio.
- Routing imbalance: skewed expert load leaves some compute units idle while others queue up, so actual utilization falls well below the theoretical value.
- Communication amplification: expert parallelism turns what was originally local memory access into an all-to-all exchange across devices, making the network a hidden bottleneck.
- Cache expansion: under long context, the key-value cache can reach tens of gigabytes, competing with the weights for the same memory.
Together, these four points lead to one conclusion: the focus of inference optimization for sparse models is not “computing faster,” but “moving less, fitting more, and routing evenly.”
3. Bottleneck Identification: Measure First, Then Optimize
Any performance optimization should start from a reproducible baseline. The recommended minimal set of metrics is as follows:
# Illustrative metric collection logic, not tied to a specific platform APIdef collect_metrics(session):return {"ttft_ms": session.first_token_latency, # Time to first token"prefill_tps": session.prefill_tokens / session.prefill_time,"decode_tps": session.decode_tokens / session.decode_time,"kv_cache_bytes": session.kv_cache_allocated, # Cache usage"batch_size": session.batch_size,"expert_load_skew": session.expert_load_max / session.expert_load_mean,}
The identification method follows a “three-way isolation” principle:
- Isolate prefill from decode: load-test them separately so that long inputs do not mask the decode bottleneck.
- Isolate compute from memory access: compare throughput curves across different batch sizes. If throughput saturates quickly as batch size grows, the limit is usually bandwidth or cache capacity.
- Isolate single-card from multi-card: if single-card efficiency is acceptable but multi-card efficiency drops sharply, the problem usually lies in parallel partitioning and communication.
4. Key Optimization Techniques
4.1 Cache Reuse and Prefix Sharing
In agentic workloads, the system prompt and tool descriptions stay almost unchanged throughout a session. Pinning the key-value cache for this prefix in memory and reusing it across turns can significantly cut repeated prefill overhead. The engineering focus is cache identity and lifecycle management: use a content hash as the key, combined with reference counting and timeout-based eviction, to avoid memory that cannot be reclaimed after a session ends.
4.2 Chunked Prefill and Decode-Priority Scheduling
Splitting an extremely long input into fixed-size chunks and interleaving them with decode requests avoids decode stalls caused by a long request monopolizing compute resources. A common strategy is to set a resource floor for decode to keep interaction latency stable.
4.3 Continuous Batching and Dynamic Concurrency
Static batching forces short requests to wait for long ones. Continuous batching with iteration-level scheduling lets requests exit as soon as they finish and new requests join immediately, keeping effective concurrency high.
4.4 Quantization and Low-Precision Storage
Applying low-bit quantization to weights and low-precision storage to the cache is a direct way to relieve memory pressure. Note that quantization introduces accuracy loss, so layer-by-layer sensitivity evaluation should be done within a business-acceptable range rather than applying a one-size-fits-all global setting.
4.5 Combining Parallelism Strategies
Tensor parallelism reduces per-card weight pressure, pipeline parallelism improves device utilization, expert parallelism carries the sparse structure, and context parallelism distributes extra-long sequences. All four must match the network topology, and partitioning schemes with heavy communication should be placed within a high-bandwidth domain.
# Illustrative launch parameters, expressing configuration dimensions onlyserve --model <path> \--tp-size 8 --pp-size 2 --ep-size 8 \--max-num-seqs 64 \--enable-chunked-prefill \--kv-cache-dtype fp8
5. Supporting Capabilities for Cloud Deployment
When deploying these optimizations on the cloud, you typically just combine general-purpose capability categories: a container platform to host inference instances and elastic scaling; object storage to hold model weights and datasets; a message queue for request peak-shaving and asynchronous task decoupling; logging and monitoring with alerting for metric collection and baseline-versus-regression comparison; and a private network with high-bandwidth interconnect to ensure communication quality across multiple instances. Baidu AI Cloud provides exactly these general infrastructure categories for such scenarios; for specific parameters and specifications, refer to the official documentation.
6. Common Pitfalls
- Looking only at average throughput: averages hide the poor experience of long-tail sessions, so report both median and high-percentile latency.
- Blindly increasing concurrency: once concurrency exceeds cache capacity, frequent swapping occurs and throughput actually drops.
- Neglecting cache reclamation: in long-session scenarios, leaks accumulate and eventually show up as “performance degradation after running for several hours.”
- Quantizing everything at once: accuracy collapse often comes from a few sensitive layers, so evaluation must be done layer by layer.
7. Conclusion
Optimizing inference for long-context, multi-turn agentic workloads is essentially about rebalancing across four dimensions: compute, memory capacity, memory bandwidth, and network communication. The workable path is to first establish a clearly separated metrics system, then eliminate bottlenecks one by one through prefix cache reuse, chunked prefill, continuous batching, low-precision storage, and combined multi-dimensional parallelism, and finally run regression validation under real business traffic. Treating optimization as a continuous, iterative measurement discipline rather than one-time parameter tuning is what keeps service quality stable and predictable at throughput levels of hundreds of tokens per second.
