LLM Inference Optimization: A Practical Guide to Higher Throughput and Lower Costs
This guide breaks down how to speed up large language model inference while controlling costs. It defines the core metrics—TPS, TTFT, end-to-end latency, and cost per task—then walks through model-level and system-level optimizations such as continuous batching, paged KV cache, and scheduling. It also covers thinking-budget controls, canary and rollback strategies during version transitions, and rebalancing compute between online serving and training, with practical code and configuration examples.
1. Introduction: The Engineering Signal Behind a Version Switch
During the evolution of inference services, a familiar pattern often appears: a new version marketed for low latency and high throughput is about to launch, while the previous flagship version is retired. On the surface this looks like a product release cadence, but it usually signals three engineering realities: the older architecture has fallen behind on compute cost-efficiency, the inference infrastructure is due for a generational upgrade, and the resource contention between training and online serving needs to be rebalanced. This article sets aside any specific product context and focuses on the general technical problems and reusable practices behind these scenarios.
One caveat: any claim about a specific version reaching a certain TPS or first-token latency should be validated against official benchmarks and your own load tests. This article does not cite unconfirmed numbers; it only provides measurement methods and an optimization framework.
2. Define the Metrics First: Throughput, First-Token Latency, and Total Cost of Ownership
Before discussing whether something is “fast” or “expensive,” you must align on definitions, otherwise the conclusions cannot be compared.
- TPS (output tokens per second): reflects decoding speed during the generation phase and directly determines the reading experience.
- TTFT (Time To First Token): first-token latency, mainly composed of queue wait time, prefill computation, and scheduling overhead.
- End-to-end latency: TTFT plus total generation time, strongly correlated with output length.
- Cost per task: not just the unit price, but modeled as a weighted sum of three components:
input tokens + output tokens + thinking tokens.
Illustrative formulas:
cost_per_task ≈ (in_tokens × p_in) + (out_tokens × p_out) + (think_tokens × p_think)end_to_end_latency ≈ queue_delay + TTFT + out_tokens / TPS
The takeaway: high TPS can significantly compress the total time for long outputs, but if thinking tokens balloon, the total cost may actually rise rather than fall. This is the most easily overlooked factor when evaluating any “faster” version.
3. Where High Throughput and Low First-Token Latency Come From
Without assuming any vendor’s proprietary implementation, the optimization directions widely accepted in the industry fall into two categories: model structure and system level.
On the model-structure side, common techniques include making the attention mechanism more efficient, sparsification and mixture-of-experts-style routing, and compact models distilled specifically for the inference phase. Structural changes often alter memory footprint and batch-friendliness, which is the root cause of the order-of-magnitude differences a generational architecture change can bring.
On the system side, the focus is on continuous batching, paged KV cache management, prefix reuse and cache hits, operator fusion and low-precision computation, and request-priority scheduling. The scheduling logic can be described with the following pseudocode:
def schedule(requests, max_batch_tokens, kv_pool):ready = [r for r in requests if r.prefill_done or r.can_prefill(kv_pool)]ready.sort(key=lambda r: (r.priority, -r.arrival_time)) # priority + starvation preventionbatch = []used = 0for r in ready:cost = r.prefill_cost() if not r.prefill_done else 1if used + cost > max_batch_tokens:continuebatch.append(r); used += costreturn batch # decode phase emits tokens one by one to keep TPS stable
Key practice: treat TTFT and TPS as two independent SLOs and govern them separately, avoiding sacrificing interactive experience for the sake of throughput.
4. The “Overthinking” Trade-off: Thinking Budget and Cost Governance
A common side effect of new versions is that the inference phase generates a large amount of intermediate thinking content. It improves accuracy on complex tasks but directly drives up output-side costs. A practical approach is to introduce thinking-budget control:
if task_complexity < θ: think_budget = lowelse: think_budget = medium/high
Combined with three engineering constraints: set a cap and truncation policy for thinking tokens; route simple requests to a smaller model or disable deep thinking; and return thinking content on demand rather than in full, reducing network and storage amplification. This keeps quality intact while pulling cost per task back into a controllable range.
5. Canary and Rollback Design During Version Transitions
When an old version is retired and a new one launched, the biggest risks are quality drift and insufficient capacity. A four-step approach is recommended:
- Shadow traffic: mirror real requests to the new version, compare only, do not return.
- Small-percentage canary: ramp up by user or tenant dimension, monitoring TTFT, TPS, error rate, and cost per task.
- Automatic rollback: switch traffic back to the old version if any SLO is breached, provided the old version retains minimum viable capacity.
- Full cutover: retire the old version only after stability is confirmed, and announce the migration window in advance.
Configuration example (illustrative):
routing:default: model_v_newshadow: 0.10canary: { percent: 5, metric_guard: [ttft_p99, error_rate, cost_per_task] }fallback: model_v_old # retain fallback capacity
6. Rebalancing Cost and Compute Resources
Online inference and training often share the same resource pool. If high-priority online traffic persistently crowds out training jobs, training cycles get stretched. Common governance measures include: tiered scheduling based on queues and quotas, making offline training jobs preemptible, isolating resources by business line, and building a unit-cost dashboard with monitoring, alerting, and logging services. Resource isolation and quotas are general cloud capabilities; the specific implementation should follow your own environment.
7. Selection Advice: Don’t Look at Benchmarks Alone
When old and new versions coexist, run a small-scale benchmark on your own dataset: fix the input distribution, compute the percentiles of TTFT and TPS, record the share of thinking tokens, convert to cost per task, and then make a weighted decision combined with task accuracy. If you prioritize interactive experience and cost control, prefer the high-throughput compact version; if tasks are complex and accuracy-sensitive, consider the flagship version together with a thinking budget.
8. Conclusion
A version switch is not simply “swapping the model,” but a systems-engineering effort spanning metric definition, architecture upgrades, scheduling optimization, cost governance, and canary rollback. Only by breaking SLOs down finely, modeling costs, and keeping rollback ready can you land smoothly amid a performance leap. If you need a complete inference-acceleration and cost-governance solution, you can build your own observability and elasticity system using capabilities such as the general container platform, monitoring and alerting, and logging services offered by Baidu AI Cloud.
