LLM Inference Optimization: A Practical Guide to Speed and Cost
This guide explains how to improve large language model inference speed while controlling costs. It defines the key metrics—TTFT, TPS, end-to-end latency, and cost per completed task—and shows why higher throughput alone does not reduce spending. It covers the architectural changes required for high-throughput serving, including attention optimizations, sparse expert routing, continuous batching, chunked prefill, prefix caching, and KV cache tiering. It also explains the opportunity cost behind retiring a flagship model, the hidden expense of overthinking and token inflation, and how to run reproducible benchmarks. A deployment checklist for version migrations is included.
1. Introduction: The Technical Signal Behind a Model Version Change
A cloud provider recently adjusted its LLM service lineup: a lightweight version focused on high throughput and low latency is about to launch, while the previous flagship version is being retired. The community discussion has focused less on “how much stronger the new version is” and more on two engineering questions: Why would a provider give up some high-value workloads to migrate users to a lightweight version? And once the lightweight version is fast enough, what goal is the next flagship version making room for?
Strip away the product narrative, and this is a classic inference system problem: under a fixed compute budget, how do you satisfy both interaction experience targets and cost per task? This article breaks down the architectural logic behind such version changes from a general technical perspective and offers a reusable evaluation and optimization method.
2. Define the Metrics First: The Triangle of Latency, Throughput, and Cost
Before discussing whether a model is “fast,” you need a shared vocabulary. The industry commonly uses these metrics:
- TTFT (Time To First Token): The time from sending a request to receiving the first output token. It determines how responsive an interaction feels.
- TPS (Tokens Per Second): The generation speed during streaming output. It determines the reading experience for long text.
- End-to-end latency: TTFT plus the generation time for all tokens.
- Cost per task: Note that this is not the “price per million tokens,” but the total tokens consumed to complete a real task multiplied by the unit price.
The high-throughput targets mentioned above (TPS 300+, TTFT around 500ms) represent first-tier interactive experience. To understand the difficulty, consider a simplified model:
end-to-end latency ≈ TTFT + (output tokens / TPS)cost per task ≈ (input tokens + output tokens + reasoning tokens) × unit price
This reveals a frequently overlooked fact: throughput improvements enhance experience but barely reduce cost per task. When a model emits more intermediate reasoning tokens, the cost term is pushed higher instead. This is the mathematical root of why “fast” and “cheaper” are not the same thing.
3. What Must Change Architecturally to Reach 300+ TPS and 500ms-Level TTFT
The claim that “the architecture and infrastructure must have changed significantly” is sound from an engineering standpoint. Stacking single-GPU compute alone cannot satisfy both metrics. A combination of the following is typically required:
3.1 Efficiency Improvements in Attention and Decoding
Approximate structures such as grouped-query attention and multi-query attention reduce memory-access pressure by compressing redundant key-value cache computation. Combined with more efficient sampling and batching strategies, they can significantly raise decoding throughput in long-context scenarios.
3.2 Sparsity and Expert Routing
Mixture-of-experts structures activate only part of the parameters for each token, controlling per-step computation while total parameter count grows. However, sparsity is extremely sensitive to load balancing: routing skew causes individual devices to queue up and amplifies tail latency. Routing strategy and capacity factor tuning are therefore mandatory pre-launch tests.
3.3 Serving Layer and Infrastructure Coordination
What really determines TTFT is often scheduling rather than the model itself:
- Continuous batching: Dynamically batch at the token level to avoid long requests blocking short ones;
- Chunked prefill: Slice the prefill of long inputs and interleave it with the decoding phase to reduce TTFT;
- Prefix cache reuse: Shared prefixes such as system prompts and long documents do not need to be recomputed after a cache hit;
- KV cache tiering: Store data across GPU memory and CPU memory/storage in tiers to support a larger concurrent context scale;
- Operator and compiler optimization: Custom operators, graph compilation, and quantization push memory-access bottlenecks lower.
Illustrative server-side pseudocode:
# Scheduling skeleton for continuous batching + chunked prefill (illustrative)while serving:batch = scheduler.pop_ready_requests()for req in batch.prefill_chunked(chunk_size=512):kv_cache.put(req.prefix_id, req.kv) # prefix reusescheduler.merge_into_decode(batch)step_model(batch) # token-level generation
4. Why Retiring the Flagship Version Makes Sense: The Opportunity Cost of Compute
The idea of “switching even if it means giving up some revenue” is essentially an opportunity cost calculation. Inference compute is a finite, schedulable resource. A single flagship request consumes more GPU memory and computation, so it supports fewer concurrent requests under the same budget. When high-value, long-chain, batch workloads continuously occupy flagship resources, what gets squeezed is not only revenue but also the headroom needed for training and iteration.
From a platform perspective, a common approach is tiered supply:
| Tier | Target scenarios | Optimization focus |
|---|---|---|
| Lightweight high-throughput tier | Interactive Q&A, code completion, agent loops | TTFT, TPS, concurrency density |
| Flagship capability tier | Complex reasoning, long-document analysis, hard tasks | Task success rate, context length |
| Batch offline tier | Data processing, bulk extraction | Cost per token, retryability |
Pushing interactive traffic down to the lightweight tier is the most direct way to improve overall resource utilization.
5. The Underrated Cost Black Hole: Overthinking and Token Inflation
The observation that the new version “overthinks” reflects a common phenomenon in today’s reasoning models. The model generates a large number of intermediate reasoning tokens before giving an answer. This improves accuracy on complex tasks but directly increases total output tokens. As the earlier formula shows: output volume scales cost linearly, and higher TPS does nothing to help.
Engineering options for convergence include:
- Reasoning budget constraints: Set a cap or soft threshold on intermediate reasoning tokens per request;
- Difficulty-adaptive routing: Send simple requests to a low-reasoning tier and open up the budget for complex ones;
- Prompt-level constraints: Explicitly require “conclusion first, then supporting evidence” to suppress unnecessary elaboration;
- Result and semantic caching: Reuse answers for high-frequency repeated questions to avoid repeated reasoning;
- Streaming truncation and early stopping: Terminate generation once a confidence threshold is met.
{"model": "general-purpose","stream": true,"max_output_tokens": 2048,"reasoning_effort": "low","temperature": 0.2}
Note that the fields above are generic illustrations. Actual parameter names and value ranges should follow the latest documentation for the platform you use; do not copy them blindly.
6. Selection and Load Testing: Turning Subjective Feelings into Reproducible Data
When facing a version change, the safest approach is to build a small-scale regression evaluation:
- Fixed test set: Cover four categories—short Q&A, long-document summarization, code generation, and multi-turn tool calls;
- Dual-metric collection: Record TTFT, TPS, total tokens, and task success rate at the same time;
- Percentile statistics: Focus on P50/P95/P99; averages hide the long tail;
- Cost conversion: Replace unit-price comparison with “total cost per 100 completed real tasks”;
- Regression gate: Roll out the new version gradually and roll back if metrics degrade beyond a threshold.
Illustrative load-test output:
case TTFT(ms) TPS out_tokens successshort-qa P95 480 310 180 0.98long-summary P95 760 295 1450 0.94code-gen P95 620 300 880 0.91tool-call P95 900 280 620 0.89
7. If You Were Running a Version Switch: A Deployment Checklist
- Define business tiers and completely separate interactive from offline traffic;
- Set an SLO for each tier (such as a TTFT P95 and a TPS floor) along with a cost ceiling;
- Enable prefix caching and continuous batching to capture infrastructure gains first;
- Tier reasoning budgets and establish difficulty detection or rule-based routing;
- Roll out gradually and keep one-click rollback available;
- Review decisions using real task cost rather than unit price.
8. Conclusion
A version change looks like a product move on the surface, but it is essentially the combined result of a generational architecture gap and the opportunity cost of compute. For developers, rather than chasing version numbers, it is better to focus on three controllable things: measurable metrics, calculable costs, and adjustable routing. Once this engineering capability is in place, you can migrate smoothly and continuously gain both experience and cost benefits no matter how upstream models iterate. If you need elastic compute and supporting observability, you can build your own evaluation and gradual rollout system using general cloud product categories such as the container platform, log service, and monitoring and alerting offered by Baidu AI Cloud.
