LLM Inference Optimization: Techniques and Tradeoffs
By Shye Uy

LLM inference optimization is the work of cutting the latency and cost of generating tokens from a trained model without degrading the output quality a product depends on. Every request passes through two phases with different hardware limits, compute-bound prefill and memory-bandwidth-bound decode, so the same change can speed up one workload and slow down another. On production workloads, the first gains usually come from the serving layer (continuous batching, KV cache management, prefix caching and scheduling), while model-level changes such as quantization and speculative decoding pay off once you have measured where your own time and money go.
Key Takeaways
- Prefill processes the whole prompt in parallel and is compute-bound, while decode generates one token at a time and is limited by memory bandwidth.
- Time to first token, tokens per second, tail latency and cost per request are the four numbers that decide whether an optimization is worth keeping.
- Continuous batching, paged KV cache management, prefix caching and chunked-prefill scheduling are serving-layer changes that leave model weights untouched, which makes them the lower-risk place to start.
- Quantization trades numerical precision for memory and speed, and the size of the quality loss depends on the bit width, the method and the calibration data.
- Speculative decoding helps memory-bound, low-concurrency decode and can slow a server down once the GPU is already compute-bound.
- The right technique depends on whether the bottleneck sits in prefill or decode and in memory or compute, so diagnosis comes before any change.
Where LLM Inference Time Goes: Prefill vs Decode
LLM inference time splits into two phases: prefill, which reads the prompt and produces the first token, and decode, which generates every token after that one at a time. The NVIDIA Technical Blog post on inference optimization describes prefill as a highly parallel matrix-matrix operation that "effectively saturates GPU utilization," and decode as a matrix-vector operation that leaves GPU compute underused, where the speed of moving weights, keys and values from memory "dominates the latency, not how fast the computation actually happens."
Prefill is compute-bound
During prefill, every prompt token is known in advance, so the model computes keys and values for all of them in one large parallel pass. The vLLM paper notes that this phase "can efficiently use the parallelism inherent in GPUs." Long prompts, retrieval-augmented generation (RAG) contexts and long chat histories all make prefill longer, and prefill time is the main component of time to first token once queueing is accounted for.
Decode is memory-bandwidth-bound
Decode is the phase where a model generates output tokens one by one, and each step has to read the full model weights and the growing KV cache from GPU memory to produce a single token per request. The vLLM paper states that this phase "severely underutilizes GPU computation and becomes memory-bound, being responsible for most portion of the latency of a single request." The AWQ paper quantifies this for a 7B Llama model on an NVIDIA RTX 4090 at batch size 1: processing a 200-token prompt took 10 ms, while generating 20 tokens took 310 ms. The same analysis puts the arithmetic intensity of FP16 generation at about 1 FLOP per byte (and about 4 FLOPs per byte with 4-bit weights), far below the 165 FLOPs per byte the RTX 4090 needs to become compute-bound (165 TFLOPS of compute against 1 TB/s of memory bandwidth). Batching is the main lever here, because a batch of requests shares one read of the weights.

The KV cache is the memory you are actually managing
The KV cache stores the attention keys and values of every previous token so that decode does not recompute them at each step. NVIDIA gives its size as batch size × sequence length × 2 × number of layers × hidden size × bytes per value, and works the example as roughly 2 GB for Llama 2 7B at a 4,096-token sequence and batch size 1 in FP16, on top of about 14 GB of weights. The vLLM paper reports that for a 13B model on a 40 GB NVIDIA A100, parameters take 26 GB (65% of memory) and the KV cache takes more than 30%, and that because "the KV cache of a single token demands 800 KB of space" for OPT-13B, a single 2,048-token request "can be as much as 1.6 GB." Because the KV cache grows linearly with both batch size and sequence length, it caps how many requests can share a decode step, which is why so many serving-layer techniques are really memory-management techniques.

Measuring LLM Inference Speed and Cost: The Four Metrics
Four metrics decide whether an LLM inference optimization is worth keeping: time to first token, tokens per second, tail latency and cost per request. Each one maps to a different phase or resource, so a change that improves one can quietly worsen another.
Time to first token
Time to first token (TTFT) is the delay from request arrival to the first generated token, and it covers queueing plus prefill. The DistServe paper frames TTFT as the latency metric for the prefill phase. Long prompts, prefill-heavy traffic and requests waiting behind other prefills all raise it.
Tokens per second
Tokens per second measures decode speed, either per request (the inverse of time per output token, TPOT, or inter-token latency, ITL) or in aggregate across the server. DistServe uses TPOT as the latency metric for the decode phase. NVIDIA warns that tokens per second is not comparable across models with different tokenizers, because "corresponding tokens may represent a different number of characters."
Tail latency
Tail latency is the latency at a high percentile such as P99, and it is what users notice when a long prefill stalls everyone else's decode. Mean values hide these spikes, which is why research systems such as Sarathi-Serve and DistServe report results under tail-latency or service-level objective (SLO) constraints, with DistServe defining goodput as the highest request rate at which a set share of requests, such as 90%, meets both TTFT and TPOT limits.
Cost per request
Cost per request is GPU spend divided by the number of requests served within your latency SLOs. The vLLM paper ties the two directly: higher throughput is what lowers the cost per request. Measuring throughput only at the request rate where your TTFT and TPOT targets still hold for the required share of requests (what DistServe calls goodput) keeps cost figures honest. For capacity planning and the broader economics of GPU infrastructure, see our article on the hidden cost of scaling AI and GPU infrastructure.
Serving-Layer LLM Inference Optimization Techniques
Serving-layer techniques change how requests are batched, how KV cache memory is allocated and reused, and how prefill and decode work is scheduled, without touching model weights. That is why they carry little quality risk and why they are the usual first step in optimizing LLM inference.
Continuous batching
Continuous batching (also called iteration-level scheduling or in-flight batching) lets new requests join and finished requests leave the running batch after every decode step, instead of waiting for the whole batch to finish. The technique was introduced in the Orca paper, which observed that under request-level scheduling "requests that have finished earlier than other requests in a batch cannot return to the client, while newly arrived requests have to wait until the current batch completely finishes." NVIDIA explains that static batching is suboptimal because every request waits for the longest generation in the batch, and notes that TensorRT-LLM provides in-flight batching. vLLM and SGLang also schedule at the iteration level. The cost is scheduler complexity and the need for attention kernels that handle requests of different lengths in one batch, which is a problem engines now solve for you.
KV cache optimization with PagedAttention
PagedAttention stores each request's KV cache in fixed-size blocks that do not need to be contiguous in GPU memory, much as an operating system pages virtual memory. The vLLM paper found that earlier systems pre-allocated contiguous space for the maximum possible sequence length and, as a result, used only 20.4% to 38.2% of KV cache memory for actual token states. Paging reduces that waste to at most one block per request, which lets more requests fit in a batch. On OPT and LLaMA models running on NVIDIA A100 GPUs, the authors report 2 to 4 times higher throughput than state-of-the-art systems at the same latency; on the ShareGPT trace specifically, vLLM sustained 1.7 to 2.7 times higher request rates than an Orca baseline with oracle knowledge of output lengths, and up to 22 times higher request rates than FasterTransformer. The tradeoff is kernel overhead: their PagedAttention kernel showed 20% to 26% higher attention-kernel latency than FasterTransformer's because of block-table lookups, which end-to-end batching gains outweighed in their tests. Block size also matters, and vLLM settled on a default of 16 tokens after finding that larger blocks increased internal fragmentation on short-sequence workloads.
Prefix caching for shared prompts
Prefix caching reuses the KV cache of a prompt prefix (a system prompt, few-shot examples, a shared document or earlier chat turns) across requests, so prefill only runs on the new tokens. This section covers prefix caching inside self-hosted engines, not the prompt caching offered by hosted model APIs. The vLLM paper measured the effect on LLaMA-13B with a WMT16 translation workload: sharing a one-shot prefix gave 1.67 times the throughput of an Orca baseline that knew output lengths in advance, and a five-shot prefix gave 3.58 times. vLLM documents the feature as Automatic Prefix Caching.
SGLang implements prefix reuse with RadixAttention, described in the SGLang paper. The runtime keeps cached prompts and generations "in a radix tree, enabling efficient prefix search, reuse, insertion, and eviction," evicts the least recently used leaves first, and orders batched requests longest-shared-prefix-first to raise the hit rate. Across the paper's benchmarks the cache hit rate ranged from 50% to 99%, and in one month of Chatbot Arena traffic the authors observed hit rates of 52.4% for LLaVA-Next-34B and 74.1% for Vicuna-33B. Two limits are worth knowing. The authors note that greedy cache-aware scheduling "can lead to starvation," and in their multi-turn chat test, long outputs saw "almost no speedup" because decode time dominated. Prefix caching moves TTFT and prefill cost; it does little for decode-heavy traffic.
Request scheduling and chunked prefill
Request scheduling decides when a waiting prefill is allowed to interrupt ongoing decodes, and that decision trades TTFT against inter-token latency. Chunked prefill splits a long prompt into smaller pieces and batches them alongside decode steps. The vLLM Optimization and Tuning documentation states that in vLLM V1 chunked prefill is on by default, that the scheduler batches all pending decodes before scheduling prefills, and that the max_num_batched_tokens budget is the main tuning knob: smaller values such as 2048 "achieve better inter-token latency (ITL) because there are fewer prefills slowing down decodes," while higher values "achieve better time to first token (TTFT)." The same page recommends values above 8096 for optimal throughput, "especially for smaller models on large GPUs."
Sarathi-Serve introduced this combination of chunked prefills and "stall-free" schedules that add new requests "without pausing ongoing decodes." Its authors report 2.6 times higher serving capacity for Mistral-7B on a single NVIDIA A100 and up to 3.7 times for Yi-34B on two A100s compared with vLLM under tail-latency constraints, plus up to 5.6 times on Falcon-180B with pipeline parallelism. That comparison was against an earlier vLLM scheduler that paused decodes to run prefills, a policy vLLM has since replaced with chunked prefill by default.
Scheduling also covers what happens when KV cache memory runs out. The vLLM documentation explains that the engine preempts requests and recomputes them later, which "can adversely affect end-to-end latency," and lists remedies: raise gpu_memory_utilization, lower max_num_seqs or max_num_batched_tokens, or add tensor or pipeline parallelism to free memory per GPU. Frequent preemption warnings are a direct signal that the workload is KV-memory bound.
Prefill and decode disaggregation
Disaggregation runs prefill and decode on separate GPUs or machines, and it competes with chunked prefill as the answer to prefill-decode interference. DistServe argues that colocating the phases "leads to strong prefill-decoding interferences" and couples their resource allocation, so it assigns each phase its own GPUs and parallelism plan. The Splitwise paper makes a related case on cost grounds: token generation "does not require the compute capability of the latest GPUs, and can be run with lower power and cost." Sarathi-Serve takes the opposite position and keeps both phases on the same GPUs, using chunking to make them coexist. Disaggregation adds a KV cache transfer between machines, which Splitwise handles over fast cluster interconnects, so the choice depends on your interconnect, traffic mix and operational appetite.
Model-Level Techniques: Quantization, Speculative Decoding and Parallelism
Model-level techniques change the numbers the model computes with or the way tokens are produced, and each one trades something away: quality for quantization, memory and complexity for speculative decoding, and communication overhead for parallelism. They are worth adding after the serving layer is tuned and you have baseline numbers to compare against.
Quantization for LLM inference optimization
Quantization stores weights, activations or the KV cache in fewer bits, which shrinks memory use and, for memory-bound decode, raises tokens per second. NVIDIA's post explains the two broad options. Weight-only quantization is "much more straightforward" because weights are fixed after training, but it can "leave some performance on the table" because GPUs lack hardware for mixed INT8 and FP16 multiplication, so weights are converted back up before computing. Quantizing activations as well is harder because "activation vectors often contain outliers," which widens their dynamic range.
Methods differ in how they limit the quality loss:
- GPTQ uses approximate second-order information to quantize weights to 3 or 4 bits "with negligible accuracy degradation relative to the uncompressed baseline," and reports end-to-end speedups over FP16 of around 3.25 times on NVIDIA A100 and 4.5 times on NVIDIA A6000 for 175-billion-parameter models.
- AWQ protects the small fraction (0.1% to 1%) of salient weights tied to large activations by scaling them before quantization; for OPT-6.7B at 3 bits, keeping those weights in FP16 cut perplexity from 43.2 to 13.0. On Llama-2-7B, WikiText-2 perplexity rose from 5.47 in FP16 to 5.60 with 4-bit AWQ, 5.69 with 4-bit GPTQ and 5.73 with plain round-to-nearest, and rose further to 6.24 with 3-bit AWQ.
- SmoothQuant enables 8-bit weights and 8-bit activations by migrating "the quantization difficulty from activations to weights with a mathematically equivalent transformation."
Calibration data is a point of disagreement. The AWQ authors report that GPTQ can overfit its calibration set: on OPT-6.7B at 3 bits, calibrating on one dataset and evaluating on another raised GPTQ's perplexity by 2.3 to 4.9 points, against 0.5 to 0.6 for AWQ. The GPTQ authors, for their part, report negligible degradation at 3 to 4 bits on their own evaluations. The practical reading is that you should evaluate any quantized model on your own task data, not only on published perplexity.
KV cache quantization is a separate setting from weight quantization and targets long-context, memory-bound decode. The vLLM blog post on FP8 KV cache and attention quantization reports that on a single NVIDIA H100 running Llama-3.1-8B at concurrency 1, FP8 KV cache cut the inter-token latency slope from 4.37e-05 to 2.37e-05 ms per cached token (about 54% of the BF16 slope), with a break-even point of 7,010 tokens of context in vLLM v0.19.1, down from 24,889 tokens in v0.10.2. The same post shows how a quantization path can fail quietly: before a kernel fix, FP8 accuracy on a 128k-token needle-in-a-haystack test on Hopper GPUs fell from 91% (BF16) to 13%, recovering to 89% after the fix. The authors also flag that prefill can still regress for models with a head dimension of 256 and recommend skipping sliding-window layers in hybrid-attention models.
Speculative decoding
Speculative decoding uses a cheap draft (a small model, extra prediction heads or n-gram matches from the prompt) to propose several tokens, which the target model then verifies in a single forward pass. Because decode is memory-bound, verifying several tokens costs about the same as generating one. Leviathan et al. showed the method can accelerate generation "without any changes to the outputs," and Chen et al. describe a rejection-sampling scheme that "preserves the distribution of the target model within hardware numerics."
The speedup depends on load. The vLLM blog post on speculative decoding reports, for Llama3-70B on 4 NVIDIA H100 GPUs at 1 query per second, up to 1.5 times faster generation on ShareGPT with a draft model and up to 2.8 times on CNN/DailyMail summarization with n-gram prompt lookup. At high query rates, the same setup ran 1.4 times slower on ShareGPT and 1.8 times slower on CNN/DailyMail, because "the extra compute required to propose and verify tokens can sometimes slow down the system when it is already compute-bound." The costs are extra GPU memory for the draft model and its KV cache, a shared-vocabulary requirement for draft models, and configuration that has to be re-tuned as traffic changes. The vLLM speculative decoding documentation frames the feature as one that "improves inter-token latency in memory-bound LLM inference," which is the condition to check before enabling it.

Parallelism strategies
Parallelism spreads a model across GPUs when it does not fit on one, or when you need more KV cache room per GPU. NVIDIA describes tensor parallelism as sharding individual layers across devices and pipeline parallelism as splitting the model into groups of layers, with "pipeline bubbles" leaving devices idle while they wait for earlier stages. The vLLM Optimization and Tuning documentation gives the operational tradeoffs: tensor parallelism is "the most common strategy for large model inference within a single node" but can add synchronization overhead; pipeline parallelism suits multi-node setups or cases where tensor parallelism is already maxed out, at a possible latency cost; expert parallelism targets mixture-of-experts models; and data parallelism replicates the whole model to scale throughput. The two sources disagree on data parallelism: NVIDIA's post calls it "a training time optimization that is less relevant during inference," while the vLLM documentation recommends it for scaling serving throughput once the model fits. Both positions hold within their framing, since replicas add throughput but do nothing for the latency of a single request.
Choosing an LLM Inference Optimization by Bottleneck
Choosing an LLM inference optimization starts with locating the bottleneck: whether TTFT or inter-token latency is out of bounds, and whether the GPU is short on memory or on compute. A practical diagnostic sequence looks like this:
- Record TTFT, TPOT or ITL, P99 latency and requests per second at your real prompt and output length distribution, using a load tool such as
vllm bench serve, which the vLLM team used for its FP8 KV cache measurements. - If TTFT is high and prompts are long or share prefixes, the bottleneck is prefill: look at prefix caching, a larger chunked-prefill budget or disaggregation.
- If ITL is high or spiky, check whether long prefills are interrupting decodes (tune the chunked-prefill budget) and whether decode is memory-bound at your batch size.
- If the engine logs preemptions or the batch size is capped by KV cache, the bottleneck is memory capacity: paged KV cache, FP8 KV cache, weight quantization or more tensor parallelism free space.
- If GPUs are saturated and throughput has plateaued, the workload is compute-bound: speculative decoding is likely to hurt, and the remaining options are lower-precision compute (such as W8A8 or FP8) or more replicas.
The table below maps each technique to the bottleneck it fixes, the metric it moves and what it costs.
Technique | Bottleneck it fixes | Metric it moves | What it costs |
|---|---|---|---|
Continuous batching | Idle GPU slots while requests wait for the longest one in a static batch | Throughput, queueing delay, cost per request | Scheduler complexity; requires kernels that handle mixed sequence lengths |
Paged KV cache (PagedAttention) | KV memory fragmentation that caps batch size | Throughput and cost per request at the same latency | 20% to 26% higher attention-kernel latency in the original vLLM measurements; block-size tuning |
Prefix caching | Repeated prefill of shared system prompts, few-shot examples and chat history | TTFT, prefill compute, throughput | Cache memory competes with running requests; little gain for long, decode-heavy outputs; possible starvation under greedy cache-aware scheduling |
Chunked prefill and scheduling | Long prefills stalling ongoing decodes | Inter-token latency and P99 latency | A larger chunk budget favors TTFT, a smaller one favors ITL, so one improves at the other's expense |
Prefill and decode disaggregation | Prefill-decode interference and coupled resource allocation | TTFT and TPOT within SLOs, cost per request | KV cache transfer between machines; more infrastructure to operate |
Weight quantization (GPTQ, AWQ, W8A8) | Memory capacity and memory-bandwidth-bound decode | Tokens per second, model fit, cost per request | Quality loss that grows at lower bit widths; calibration-data sensitivity |
FP8 KV cache | KV cache size at long context | Inter-token latency at long context, concurrency | Accuracy risk on some kernels and architectures; prefill regressions at head dimension 256 |
Speculative decoding | Memory-bound decode at low concurrency | Inter-token latency | Draft model memory and complexity; slowdowns when the server is already compute-bound |
Tensor or pipeline parallelism | Model or KV cache that does not fit on one GPU | Model fit, KV cache headroom | Synchronization overhead (tensor) or pipeline bubbles and latency (pipeline) |
What Startups Ask an Inference Engineer to Own
Inference engineering is a specialization within AI infrastructure engineering: an inference engineer owns the path from a trained model to served tokens, and job descriptions for the role list the same techniques covered above. 2 open jobs at accepted companies on Fonzi are dedicated inference roles, with inference in the job title. Of those 2 roles:
- Both name vLLM, SGLang and TensorRT-LLM as the serving engines candidates should know.
- Both list latency, batching, prefix or KV caching, quantization and parallelism as part of the work, and one of the 2 also lists speculative decoding.
- One of the 2 asks candidates to show a production system they owned, a bottleneck they diagnosed, what they changed, and the measured results and tradeoffs.
That last request mirrors the method in this article: measure, locate the bottleneck, change one thing, and measure again. Evidence that holds up in that conversation includes the baseline and post-change values for TTFT, inter-token latency, P99 latency and cost per request at a stated request rate, the quality evaluation behind any quantization decision, and, for speculative decoding, the acceptance behavior and the load level at which the gain disappeared. A record of a change that did not work, and why, shows the same diagnostic skill as one that did.
How to Optimize LLM Inference: What to Do First
LLM inference optimization works best as a sequence: measure TTFT, tokens per second, tail latency and cost per request on your own traffic, fix the serving layer first, and add model-level changes only when the data shows a bottleneck that justifies the tradeoff. Continuous batching, paged KV cache management, prefix caching and chunked prefill leave model weights untouched, and the vLLM paper reports 2 to 4 times higher throughput than earlier serving systems at the same latency. Quantization pays off on memory-bound decode, but only after you evaluate it on your own task data. Speculative decoding helps at low concurrency and made a Llama3-70B server 1.4 to 1.8 times slower at high query rates, so check whether the GPU is already compute-bound before you turn it on.
If you are an inference engineer who builds and tunes these systems and you want to do that work at an AI startup, sign up on Fonzi.
FAQ
How do I tell whether prefill or decode is my bottleneck?
Compare time to first token with inter-token latency under real load: high TTFT with long or shared prompts points to prefill, while high or spiky inter-token latency points to decode or to prefills interrupting decodes. Preemption warnings in vLLM indicate that KV cache memory, not compute, is the limit.
Does quantization always reduce output quality?
It always reduces numerical precision, but the measured quality loss varies: on Llama-2-7B, 4-bit AWQ raised WikiText-2 perplexity from 5.47 to 5.60, while 3-bit quantization raised it further. Evaluate the quantized model on your own task data before shipping it.
When does speculative decoding make inference slower?
It slows inference when the GPU is already compute-bound at high request rates, as in the vLLM team's Llama3-70B tests on 4 H100 GPUs, which showed 1.4 to 1.8 times slowdowns at high query rates. It helps when decode is memory-bound and concurrency is low.
Should prefix caching be enabled on every self-hosted deployment?
It pays off when requests share long prefixes such as system prompts, few-shot examples or chat history, and SGLang's authors measured hit rates of 52.4% to 74.1% on production Chatbot Arena traffic. For workloads with unique prompts and long outputs, the gain is small because decode time dominates.
What is the difference between continuous batching and chunked prefill?
Continuous batching lets requests enter and leave the running batch at every decode step, while chunked prefill splits long prompts into pieces so they can share a step with ongoing decodes. Engines such as vLLM run both together, with the chunk budget trading time to first token against inter-token latency.



