LLM Inference Optimization: A Practical Guide to Speed and Cost Reduction
This guide breaks down how to systematically improve large language model inference performance and reduce cost without sacrificing output quality. It defines the four metrics that shape user experience (TTFT, TPOT, throughput, and quality baseline), explains where inference cost actually goes, and walks through four main optimization paths: continuous batching, KV cache reuse and prefix caching, quantization and speculative decoding, and request routing. It also covers context engineering, cloud deployment foundations, benchmarking methodology, and common pitfalls, giving developers and enterprises a reusable framework for measurable Pareto improvements.
1. Introduction: Why Speed and Cost Must Be Discussed Together
The industry has recently seen a familiar kind of capability upgrade narrative: an AI coding tool and a general-purpose LLM service both claimed roughly 30% faster output and roughly 20% lower cost per call in a version release, along with clear gains in coding, logical reasoning, scientific computing, network security analysis, and robot control. Setting the specific products aside, these numbers point to a single engineering proposition: inference performance and cost are not two independent curves, but two projections of the same set of architecture decisions.
For developers and enterprise users, the real question is not “how much faster is this version,” but how four metrics — time to first token (TTFT), time per output token (TPOT), end-to-end throughput (tokens/s), and cost per million tokens — can be systematically improved under your own workload without degrading output quality. This article takes a neutral technical perspective and offers a reusable optimization framework.
2. Define the Metrics First: Four Numbers Decide User Experience
Any optimization must start from a measurable baseline; otherwise “30% improvement” is just marketing language. At minimum, fix these four:
- TTFT (Time To First Token): time from request dispatch to the first token received. This drives the subjective sense of whether the system “feels stuck.”
- TPOT (Time Per Output Token): average interval between tokens after the first one. This determines whether streaming output feels smooth.
- Throughput (tokens/s): total tokens produced by the system per unit time. This determines unit cost and the concurrency ceiling.
- Quality baseline: pass rate or accuracy on a fixed evaluation set, used to verify that optimization introduced no regression.
There is a clear tension among the four. Increasing batch size usually raises throughput and lowers unit cost, but pushes up TTFT. Shortening context and disabling parts of the chain of thought can cut cost significantly, but may reduce accuracy on complex reasoning. The right posture is therefore: set the quality red line first, then make Pareto improvements within it.
3. The Cost Model: Where the Money Actually Goes
The cost of a single call can be roughly abstracted as:
cost per call ≈ (input tokens × input price) + (output tokens × output price) + retrieval/tool call overheadsystem throughput ≈ concurrency × per-request generation ratecost per token ≈ infrastructure hourly cost / total tokens produced per hour
This yields three high-leverage conclusions:
- The input side is often the main cost driver. In long-document QA and codebase understanding scenarios, input tokens frequently account for more than 80% of the total, so compressing input pays off more than optimizing output.
- Output tokens are more “expensive” and slower. Generation is a memory-bound process, and token-by-token decoding inherently struggles to saturate compute, making generation efficiency the main battleground for speed.
- Utilization determines unit price. Idle time on GPUs and other accelerators is pure loss; improving effective batching and queueing efficiency is equivalent to a direct price cut.
4. Four Main Paths to Speed and Cost Reduction
4.1 Continuous Batching and Dynamic Batching
Static batching requires all requests in a batch to start and finish together, so short requests must wait for long ones, wasting resources badly. Modern inference frameworks generally use continuous batching: requests enter and leave the batch dynamically at the token level, and a slot is released immediately once a sequence finishes. Combined with chunked prefill, the prefill of a long input can be sliced and interleaved with decode steps, preventing long requests from blocking the queue and inflating everyone else’s TTFT.
# Pseudocode: core logic of the continuous batching schedulerwhile engine.running:batch = scheduler.form_batch(max_tokens=8192)# Slice long-input prefill to avoid blocking decodeprefill, decode = batch.split_by_stage()logits = model.forward(prefill, chunk_size=512)logits = model.forward(decode, kv_cache=engine.cache)engine.cache.update(batch.finished_mask) # Reclaim GPU memory promptlyscheduler.admit_waiting() # Admit new requests immediately
4.2 KV Cache Reuse and Prefix Caching
Autoregressive generation needs to cache historical Key/Value pairs, and this GPU memory footprint becomes enormous under long context. In practice, reuse can happen at three levels:
- Prefix caching: system prompts, tool definitions, and few-shot examples are often repeated identically across thousands of requests. On a cache hit, the prefill computation for this part can be skipped entirely, giving the most noticeable TTFT improvement.
- Session-level cache continuation: in multi-turn conversations, only the new turn is computed.
- Paged memory management: managing the KV cache with a page-table approach reduces fragmentation and lets larger batches coexist.
The practical key is to “put stable content first”: place invariant system instructions and knowledge snippets at the beginning of the prompt, and user input and variables at the end, to maximize the cache hit rate.
[Stable prefix: system instructions + tool schema + domain knowledge] ← cacheable[Semi-stable section: few-shot examples] ← cacheable[Variable section: current user question + context variables] ← recomputed each time
4.3 Quantization, Sparsification, and Speculative Decoding
- Weight quantization: converting FP16 weights to INT8/INT4 roughly halves memory usage or even reduces it to a quarter, making larger batches and longer context possible; validate accuracy loss against the quality evaluation set.
- KV cache quantization: yields clear benefits in long-context scenarios.
- Speculative decoding: a small draft model guesses several tokens at once, and the large model verifies them in parallel; if accepted, it advances multiple steps in one go. The TPOT improvement typically comes from “verifying multiple tokens in one forward pass,” with higher hit rates on templated output such as code completion.
4.4 Request Routing and Tiered Service
Requests differ enormously in their sensitivity to latency and quality, so a single uniform model inevitably wastes resources. A workable strategy is tiering:
| Request type | Routing strategy | Goal |
|---|---|---|
| Simple classification, format extraction | Small model or rules | Extremely low cost |
| Routine QA, code completion | Medium model + prefix caching | Balance latency and cost |
| Complex reasoning, solution review | Large model + longer thinking budget | Quality first |
Combined with a priority queue, you can reserve latency guarantees for paid or interactive traffic and schedule offline batch jobs during off-peak hours.
5. Context Engineering: The Most Underrated Cost Reduction Lever
Input tokens are a controllable variable. Four general practices:
- Retrieval snippet trimming: inject only passages semantically relevant to the question, controlling top-k and snippet length, and avoiding “stuffing in the whole document.”
- History compression: apply summary-style memory to long conversations, keeping conclusions and discarding process.
- Structure instead of verbose description: express constraints with tables and JSON schema, which is more token-efficient and less ambiguous than natural language.
- Output length constraints: explicitly bound format and length to avoid output cost inflation from unconstrained generation.
It must be emphasized that any trimming is premised on the quality red line; it is advisable to build an automated regression that compares consistency before and after compression.
6. Deploying in the Cloud: Building the Foundation with General Capabilities
The optimizations above do not depend on any single vendor’s proprietary interfaces; a complete solution can be assembled from common cloud product categories:
- Container platform: hosts inference services, with elastic scaling to handle peaks.
- Object storage: stores model weights, evaluation sets, and archived call logs.
- Message queue: smooths peaks and fills valleys, making offline batch requests asynchronous.
- Logging and monitoring/alerting: collects TTFT, TPOT, error rate, and cache hit rate, with threshold-based alerts.
- Gateway and rate limiting: routes traffic by tenant quota and priority.
Baidu AI Cloud’s general capabilities in containers, object storage, message queues, logging, and monitoring can serve as the foundation for such an architecture; the specific selection should still be evaluated against your own workload characteristics and compliance requirements.
7. Load Testing and Validation: Turning “30% Improvement” into a Reproducible Result
Performance claims that cannot be reproduced have no engineering value. It is advisable to fix a load-testing protocol as follows:
# Illustration: a load-testing loop with a fixed workload profileprofile = {"input_len": 2048, "output_len": 512,"concurrency": [1, 8, 32, 128],"prefix_cache": "warm", # Report cold and warm cache separately}for c in profile["concurrency"]:r = bench.run(profile, concurrency=c, duration="10m")report(c, ttft_p50=r.ttft.p50, tpot_mean=r.tpot.mean,throughput=r.tokens_per_sec, cost_per_1k=r.cost)assert quality_regression(r) < 0.5 # Quality regression red line
The report must give two sets of data for cold and warm cache, provide percentiles rather than only means, and note the hardware and concurrency conditions; otherwise cross-version comparison is meaningless.
8. Common Pitfalls
- Looking only at the mean and not percentiles: P99 latency determines the long-tail experience, and the mean hides queue collapse.
- Blindly applying quantization: low precision accumulates errors more easily in long-chain reasoning and code generation, so it must be validated scenario by scenario.
- Poor cache key design: putting timestamps or random IDs into the stable prefix permanently invalidates the cache.
- Ignoring time to first token: throughput goes up but TTFT worsens, and interactive products actually feel worse.
- Performance optimization without quality regression checks: this is technical debt, ultimately repaid through production incidents.
9. Conclusion
“Faster output and lower cost” has never been the exclusive result of a particular version number; it is the combined effect of metric definition, cost modeling, scheduling strategy, cache reuse, context engineering, and the load-testing system. Put TTFT, TPOT, throughput, and unit cost on the same dashboard, set a clear quality red line, and then roll out continuous batching, prefix caching, quantization, and tiered routing in sequence — most teams can achieve meaningful Pareto improvements without replacing hardware.
