LLM Inference Optimization: Engineering Practices for Lower Latency and Cost
This article reviews engineering practices for optimizing large language model (LLM) inference. It explains the token-based cost model, including prefill and decode behavior, and covers core acceleration techniques such as KV cache management, continuous batching, quantization, speculative decoding, and attention optimization. It also discusses cost-reduction strategies across input, model, and service layers, along with practical trade-offs among quality, latency, and cost.
1. Why Inference Efficiency Matters for LLM Services
In generative AI engineering, model capability is important, but inference efficiency often determines user experience and operating cost more directly. Training defines what a model can do; inference determines whether that capability can be delivered reliably at an acceptable price. For a cloud provider or application team, every improvement in throughput or every reduction in cost per token directly affects service capacity and business sustainability.
After each new model generation, the industry tends to focus on three consistent goals: faster output generation, lower cost per call, and higher concurrency per unit of compute. This article organizes the main technical paths for accelerating LLM inference and reducing cost, and provides an engineering approach that can be applied in practice.
2. Understanding the Cost Model: What Token-Based Billing Reveals
LLM APIs are commonly billed by token. The input side—prompt and context—and the output side—generated content—are usually priced separately, with the output side often priced higher than the input side. This happens because the two phases have very different compute characteristics:
- Prefill: The input is typically processed in a single parallel forward pass. It is compute-intensive but happens only once.
- Decode: Output is generated token by token in an autoregressive manner. Each new token depends on all previously generated content, and the accumulated computation grows as the sequence becomes longer. This phase is typically memory-bandwidth-bound.
This distinction matters: output generation speed is mainly determined by decode throughput, while the cost structure is affected by input length, output length, and call frequency. Speed and cost are therefore not separate goals; many techniques can improve both at the same time.
The following sample code shows a simple cost estimation:
def estimate_cost(input_tokens, output_tokens,in_price_per_m=8.0, out_price_per_m=40.0):"""Estimate the cost (in USD) of a single call based on price per million tokens."""in_cost = input_tokens / 1_000_000 * in_price_per_mout_cost = output_tokens / 1_000_000 * out_price_per_mreturn {"input": in_cost, "output": out_cost, "total": in_cost + out_cost}
As shown above, the output-side price is usually much higher than the input-side price. Therefore, controlling output length and improving decode throughput are key levers for optimizing cost.
3. Core Techniques for Faster Inference
3.1 KV Cache and Paged Management
A costly part of autoregressive generation is repeatedly computing keys and values for historical tokens. KV cache stores these intermediate results so they do not need to be recomputed. Cache management inspired by virtual-memory paging in operating systems divides the KV cache into fixed-size blocks and allocates them on demand. This can significantly reduce memory fragmentation, improve cache hit rates, and increase batch-level concurrency. It is a foundational capability in mainstream inference engines.
3.2 Continuous Batching
Traditional static batching must wait for all requests in a batch to finish before accepting new requests, leaving compute idle while slow requests are still running. Continuous batching schedules at token granularity: when a request finishes, its slot is immediately released and filled with a new request. This keeps compute utilization high over time and can increase overall throughput by several times.
# Continuous batching scheduling illustration (pseudocode)def continuous_batching_loop(pending, running):while pending or running:# 1. Add new requests whenever a slot is availablewhile running.has_free_slot() and pending:running.add(pending.pop(0))# 2. Finished requests exit immediately and release slotsfor req in running:if req.is_finished():yield req.result()running.remove(req)# 3. Advance each active request by one steprunning.step()
3.3 Quantization
Quantization compresses model weights and activations from high-precision floating point, such as FP16, to lower bit widths such as INT8 or INT4. This can reduce both memory footprint and memory-access overhead, improving generation speed. The key is to calibrate under controllable accuracy loss, using a small representative dataset to determine quantization parameters and avoid obvious quality degradation.
3.4 Speculative Decoding
Speculative decoding uses a smaller, faster draft model to propose several tokens, which the main model then verifies in parallel. If the draft hit rate is high, the main model can confirm multiple tokens in one step, improving decoding speed with almost no sacrifice in output quality. The core trade-off is between draft quality and draft overhead.
3.5 Attention Optimization
Because attention is memory-bandwidth-intensive, kernel-level optimizations can improve performance. Techniques such as tile-based computation and online softmax reduce reads and writes of intermediate matrices. In long-context scenarios, this can provide significant speedup and reduce memory pressure.
4. Cost-Reduction Strategies Across Three Layers
Input Side
- Simplify prompts and compress context: remove redundancy and merge repeated instructions to directly reduce input tokens.
- Semantic caching: cache and reuse results for highly similar or repeated queries to avoid repeated inference.
Model Side
- Knowledge distillation: use a larger teacher model to guide a smaller student model, achieving similar results on vertical tasks at lower cost.
- Model routing: send simple requests to smaller models and escalate complex requests to larger models, so compute is spent where it matters most.
Service Side
- Elastic scaling and resource pooling: automatically scale resources based on load metrics, and improve utilization with containerization and batch scheduling.
- Result caching and rate limiting: cache reusable results and use rate limiting to protect backend stability.
5. Engineering Trade-offs: Quality, Latency, and Cost
Every optimization has a cost. Engineering maturity comes from making these trade-offs explicitly:
| Optimization goal | Main techniques | Potential trade-off |
|---|---|---|
| Lowest latency (TTFT / TPOT) | Reserve more parallelism and cache capacity | Higher cost |
| Lowest cost | Increase quantization level and batch size | Possible loss in quality or tail latency |
| Highest quality | Keep higher precision and larger models | Pressure on throughput and cost |
Before production rollout, it is recommended to build an observability system. Instrumentation should collect key metrics such as first-token latency, per-token generation latency, cache hit rate, and cost per request. Optimization should be driven by data rather than guesswork.
6. Summary
Faster and lower-cost LLM inference is not magic. It is an engineering methodology built from cache management, batch scheduling, quantization, speculative decoding, and layered routing. Understanding token-based billing and autoregressive generation is the key first step from optimization techniques back to cost root causes.
For enterprises that want to implement these approaches, a practical starting point is observability: first quantify the current state, then introduce optimizations one by one, and validate each benefit with data. This helps find the best balance among quality, latency, and cost for a specific business. These capabilities also depend on general cloud infrastructure, such as container platforms for serving inference workloads, object storage and message queues for data flow, and logging and monitoring/alerting for operational visibility. With such mature capabilities, teams can focus more on models and business logic.
