LLM Inference Optimization: Batching and Compute Scheduling Under High Concurrency
As large language model (LLM) API usage grows rapidly, inference services commonly face three types of pressure: increased Time to First Token (TTFT) caused by request queuing, insufficient token generation rates, and reduced cluster fault tolerance under high load. This article explores general engineering approaches to building and tuning inference services, detailing how to validate the effectiveness of each optimization across batching, memory management, operator fusion, scaling, and automated infrastructure changes.
As the volume of large language model (LLM) API calls grows rapidly, inference services typically face three types of pressure: increased Time to First Token (TTFT) caused by request queuing, insufficient token generation rates per unit time, and decreased cluster fault tolerance under high load. Rather than focusing on a specific product, this article explains how to build and tune inference services from a general engineering perspective and how to validate the effectiveness of each optimization.
1. Define Goals Before Optimizing
Performance optimization requires clear metrics upfront. Common metrics include Time to First Token (TTFT), Time per Output Token (TPOT), overall throughput (tokens/s), and request success rate. Different business scenarios have different priorities. Conversational applications focus heavily on TTFT, while offline batch processing prioritizes throughput and unit cost. Without clear goals, teams risk sacrificing certain metrics for others, making it impossible to determine if the optimization was successful.
2. Continuous Batching and Scheduling Parameters
Static batching requires waiting to fill a batch of requests, which increases queue time. Continuous batching allows new requests to join and completed requests to exit at each decoding step, thereby improving accelerator utilization. Taking inference frameworks like vLLM as an example, you can check key parameters in the following order during tuning:
- Maximum number of concurrent sequences (
max_num_seqs): Determines the number of requests that can exist simultaneously in the scheduler. - Maximum tokens per batch (
max_num_batched_tokens): Limits the scale of a single forward pass, preventing long requests from consuming all compute resources and slowing down short requests. - Queue timeout and priority strategies: Prevents tail requests from waiting indefinitely.
Modify only one parameter at a time and record the metric changes before and after the modification. Changing multiple parameters simultaneously makes it impossible to isolate which change produced the effect.
3. Memory Management and KV Cache
The bottleneck during the decoding phase is typically memory capacity and memory bandwidth. The KV Cache stores the key and value vectors of historical tokens, and its footprint grows with concurrency and context length. The footprint of a single request’s KV Cache can be estimated using the following formula:
KV Cache bytes = 2 × num_layers × num_kv_heads × head_dim × bytes_per_element × num_context_tokens
PagedAttention approaches this by dividing the KV Cache into fixed-size blocks and allocating them on demand, reducing memory fragmentation caused by pre-allocation. This method increases the supportable concurrency but makes scheduling and memory management logic more complex, so you need to verify the compatibility of the specific framework version with your hardware.
When troubleshooting memory issues, first estimate the total budget using the formula above: concurrency multiplied by average context length multiplied by the footprint per token. If the estimate approaches the available memory limit, you should reduce the maximum concurrency or limit the maximum context length, while retaining a certain safety margin.
4. Operator Fusion and Compilation Optimization
Inference engines can fuse multiple small operators into a larger one, reducing kernel launch overhead and intermediate memory read/writes. The benefits of fusion depend on the model structure, input shape, and hardware architecture; there is no universal speedup ratio. In practice, you should conduct A/B tests on the same model to confirm whether graph compilation is enabled and fusion rules are taking effect, covering performance across different input lengths. If a specific fusion actually slows down processing for a particular shape, a fallback path should be retained to allow that fusion to be disabled via configuration.
5. Elastic Scaling and Load Balancing
The load balancer needs to distribute requests to healthy nodes. The basis for scaling can be queue depth, wait time, and accelerator utilization. Scaling out incurs cold start costs; the time required for model loading and memory preheating depends on the model size and storage bandwidth. Therefore, scaling thresholds should include a margin to prevent new nodes from being unready when traffic arrives. When a node fails, it should be isolated and unfinished requests retried. The retry logic must ensure that the same request is not billed twice or produces duplicate outputs.
6. Stress Testing: How to Get Reliable Performance Numbers
A stress test report should specify the following conditions: model version, hardware model and quantity, framework version, input and output length distribution, concurrency, batching parameters, measurement tools, and statistical methods. Latency should report P50, P90, and P99 percentile values; reporting only averages can easily mask tail latency issues. Stress test requests should closely resemble the length distribution of production traffic, rather than using fixed-length synthetic requests. When calculating throughput, it must be clear whether it is based on input tokens, output tokens, or a combination of both.
Performance numbers lacking these conditions are neither reproducible nor easy to evaluate for other business scenarios.
7. Using Agents to Assist with Infrastructure Changes
LLM Agents can generate deployment scripts and adjust configurations, reducing repetitive manual operations. However, Agent operations must be constrained. A three-tier validation approach is recommended:
- Static checks: Verify syntax, configuration structure, and policy rules.
- Sandbox execution: Run in an isolated environment to confirm the configuration takes effect.
- Canary release: Run on a small number of real nodes and compare against baseline metrics.
The following sample code illustrates how to write a canary check. The thresholds are explicitly passed in via configuration rather than hardcoded:
# Example code: Thresholds passed via config by caller, and record sourcedef gray_check(metrics, baseline, cfg):latency_ok = metrics.p99_ms <= baseline.p99_ms * cfg.max_p99_regressionerror_ok = metrics.error_rate <= cfg.max_error_ratereturn latency_ok and error_ok
Beyond validation, the Agent also requires least privilege, complete audit logs, rollbackable change records, and manual approval before production changes. The results of each change should be archived for post-incident review and retrospective analysis.
8. Tiered Service and Pricing by Scenario
Different scenarios have vastly different requirements for latency and cost. Offline batch processing, such as data cleaning and corpus analysis, can tolerate longer queue times and is suitable for low-priority, high-throughput scheduling, utilizing idle compute capacity. Real-time chat and code assistance scenarios are more sensitive to TTFT and tail latency, typically requiring reserved capacity.
Tiered pricing should be based on actual resource costs and Service Level Agreements (SLAs), rather than applying a fixed multiplier. When publishing prices, you should also specify the billing unit, applicable regions, effective time, and the test conditions corresponding to the performance metrics.
9. Pre-Launch Checklist
- Stress test report includes complete test conditions and provides P99 latency and error rate.
- Memory budget estimated via formula with a reserved safety margin.
- Scaling thresholds and cold start times have been validated.
- Rollback plan has been rehearsed and can restore service within the agreed time.
- Monitoring covers queue depth, TTFT, TPOT, memory usage, and error codes.
Frequently Asked Questions
Q: How do I choose a batching strategy?
A: First determine the priority metrics based on business goals, then adjust the maximum concurrency and maximum tokens per batch, changing only one parameter at a time.
Q: How do I locate a memory bottleneck?
A: First estimate the KV Cache footprint using the formula, then use monitoring to check peak memory usage to determine whether it is primarily caused by concurrency or long contexts.
Q: What should I do if performance does not improve after optimization?
A: Check if the baseline environment is consistent, confirm whether the optimization configuration actually took effect, and verify that the test input distribution matches production traffic.
Conclusion
LLM inference optimization is the result of the combined effects of scheduling, memory, operators, and operations. A reliable approach is to define metrics first, adjust parameters one by one while recording results, validate the effects using stress tests that closely mimic production traffic, and finally deploy using a rollbackable strategy. Performance numbers are only valuable for reference when the test conditions are clearly documented.
