Engineering Optimization Practices for LLM Inference Latency and Throughput
This article breaks down large language model inference performance into measurable layers and cost segments, then shows how scheduling, batching, caching, routing, and resource isolation can deliver controllable latency and predictable throughput under a fixed compute budget. It includes metric definitions, sample collection code, scheduling pseudocode, a reproducible benchmarking baseline, and common pitfalls to avoid.
1. Why Speed Is the First Barrier to LLM Adoption
A recurring pattern in production model serving is that more capable models tend to come with longer wait times, while business teams have very little tolerance for interaction latency. The core observations in the source material — that plain text has a natural speed advantage, that multimodal capabilities significantly increase compute consumption, and that model release timing needs to align with the pace of compute supply — all point to the same engineering proposition: inference performance is not a secondary attribute of a model but a key constraint that determines usability.
This article does not evaluate or recommend any specific model or product. Instead, it abstracts those observations into a general technical question: under a given compute budget, how do you build an LLM inference service with controllable latency and predictable throughput?
2. Breaking Down “Slow”: A Layered Definition of Latency Metrics
A vague sense of “slow” cannot be optimized, so the metrics must be decomposed first. The layered definitions commonly used in the industry are:
- Time to first token (TTFT): the time from request dispatch to receiving the first output token, which determines how long it takes to get a response after a click.
- Time per output token (TPOT): the average time to generate each token during decoding, which determines whether the typewriter effect feels smooth.
- End-to-end total duration: strongly correlated with output length, so long-form generation tasks can take a long time even when TPOT is normal.
- Throughput (tokens/s or concurrent requests): the server’s output capacity per unit time, which determines how many users a unit of compute can support.
- Tail latency (P95/P99): real experience is decided by the tail, and a healthy average with degraded P99 is a common source of production complaints.
Illustrative metric collection logic:
# Illustrative metric definitions only, not any specific platform APIdef record_metrics(t_start, t_first_token, t_end, n_tokens):ttft = t_first_token - t_starttpot = (t_end - t_first_token) / max(n_tokens - 1, 1)return {"ttft_ms": ttft * 1000,"tpot_ms": tpot * 1000,"total_ms": (t_end - t_start) * 1000,"output_tokens": n_tokens,}
3. Where Latency Comes From: A Four-Part Cost Structure
The time spent on a single inference request can be split into four segments, and the optimization approach for each is completely different:
- Input processing and prefill: attention computation grows roughly quadratically with input length, so long contexts push TTFT up significantly.
- Weight and cache reads: the decoding stage is constrained by GPU memory bandwidth, making it a typical memory-bound workload rather than a purely compute-bound one.
- Sampling and post-processing: tokenization, sampling strategies, and structured output constraints all add extra overhead.
- Queueing wait: under concurrency peaks, the time a request spends in the scheduling queue often exceeds the computation itself.
The conclusion is straightforward: optimization must target a specific segment, otherwise you end up with ineffective spending like “we switched models and it still isn’t faster.”
4. The Architectural Value of Text-First Design
The source material emphasizes the speed advantage of plain-text interaction, which can be argued in engineering terms as follows: text pipelines have lower input/output tensor dimensions, simpler cache structures, and no need for encode-decode alignment, so they more easily achieve low TTFT and high concurrency with the same compute. The practical recommendation is a layered product form:
- The interaction layer (completion, rewriting, classification, extraction) goes through a low-latency text channel.
- Complex reasoning and long-document processing go through an asynchronous task channel, replacing synchronous waiting with a task queue plus result callback.
- Multimodal capabilities are enabled on demand, so not every request carries the compute cost of image or video encoding by default.
5. The Compute Ledger for Multimodal
The reason multimodal is expensive is that it adds an extra encoding path: visual or audio input must be split, encoded, and aligned to the language space. This compute grows roughly linearly with input resolution, frame count, and duration, and it is hard to cache and reuse as simply as text. Practical cost-control measures include:
- Downsampling and adaptive resolution on the input side, screening with small images first and going high-resolution only when needed.
- Cache reuse, building content fingerprints and result caches for reference material that appears repeatedly.
- Modality routing, using a lightweight classifier to decide whether the multimodal path is needed.
- Length bucketing within a batch to reduce padding waste.
6. Scheduling and Batching: The Main Lever for Throughput
Without changing the model, server-side scheduling often delivers the largest gains:
- Continuous batching: new requests are inserted into a batch that is already decoding, avoiding a whole-batch wait.
- Chunked prefill: long-input prefill is sliced and interleaved with decoding steps to keep P99 down.
- Priority and quota: queue weights are set by business tier to protect critical paths.
- Prefix cache reuse: keeping system prompts, templates, and few-shot examples stable at the prefix significantly reduces repeated computation.
- Output length governance: set reasonable limits and guide the model toward concise expression, so long-tail generation does not drag down the whole batch.
Pseudocode for the scheduling decision:
on request arrival:if prefix_cache_hit and length <= bucket_small:enqueue(high_priority, chunked_prefill=true)elif modality == multimodal:route_to(encoder_pool) # separate resource pool to isolate compute jitterelse:enqueue(normal, continuous_batching=true)
7. Resource Isolation and Capacity Planning
When multimodal and text share the same resource pool, they interfere with each other. It is better to split resource pools by workload profile and pair them with observability: use monitoring and alerting to watch queue length, batch size, cache hit rate, and GPU memory usage, and have the logging service retain per-segment timings for retrospective analysis. For capacity planning, use P95/P99 rather than averages as the constraint, reserve headroom for bursts, and rely on elastic scaling to handle peaks.
8. Evaluation Methodology: Build Your Own Baseline
Do not make selection decisions based on abstract impressions; build a reproducible local baseline:
Fixed input set (several short / medium / long / multimodal cases)Fixed output length and sampling parametersRecord TTFT / TPOT / P95 / output tokens per second / cost per requestCompare horizontally on the same hardware at the same concurrency levels
9. Common Pitfalls
- Looking only at average latency and ignoring tail latency.
- Judging model speed by total output duration, confusing generation length with decoding speed.
- Enabling maximum precision and multimodal by default for every request.
- Changing the system prompt frequently, which invalidates the prefix cache.
- No resource isolation, so long tasks block the interactive path.
10. Conclusion
The phenomenon that “release cadence is constrained by compute” confirms from another angle that inference compute is the boundary at which model capability is realized. For developers, the pragmatic path is: quantify the metrics first, then locate the cost segment, and then use scheduling, caching, routing, and resource isolation to spend limited compute where it is needed most. If you need an out-of-the-box engineering foundation, Baidu AI Cloud can compose a complete inference service support system from general capabilities such as container platforms, object storage, message queues, logging services, and monitoring and alerting, helping teams put their optimization focus back on the business itself.
