Serving Large Language Models in Production: Engineering Practices and Optimization Strategies
This article covers the key engineering practices for deploying large language model (LLM) inference services in production. It explains the four core metrics—TTFT, TPOT, throughput, and unit cost—the two phases of autoregressive generation, and practical techniques such as continuous batching, paged KV cache management, prefix caching, quantization, tensor parallelism, and speculative decoding. It also discusses service-layer reliability, elastic scaling, cost control, and observability, helping teams build inference services that are fast, stable, and cost-efficient.
Serving Large Language Models in Production: Engineering Practices and Optimization Strategies
A large model’s capability ceiling is determined by its parameters and training process. Inference engineering addresses a different problem: how to deliver those capabilities to a large number of concurrent users at an acceptable cost. These two responsibilities usually belong to different teams, but the end-user experience often depends on the latter. The same model can be slow and expensive on a poorly scheduled service, yet run stably on a well-optimized one.
1. Define Your Optimization Goals First
Inference services typically focus on four metrics.
- Time to First Token (TTFT): The time from request arrival to the first output token. It determines perceived responsiveness and is mainly affected by prefill computation and queuing time.
- Time per Output Token (TPOT): The average time to generate each token during decoding. It determines how smooth the output feels.
- Throughput: The number of tokens or requests processed per unit of time. It determines the output per unit of hardware.
- Unit cost: The hardware, energy, and operational cost per million tokens. It is the direct constraint on whether the business can sustainably operate.
These metrics involve trade-offs. Larger batches improve throughput but may increase queuing time and TPOT for individual requests. Teams should first define service level objectives (SLOs), then optimize within those constraints, rather than chasing a single metric.
2. Understand the Two Phases of Inference
Autoregressive generation consists of two phases: prefill and decoding. Prefill processes the entire input at once; it is compute-intensive and well suited to parallel execution. Decoding generates one token per step, repeatedly reading model weights and the historical KV cache; it is memory-bandwidth intensive, and GPU compute is often underutilized. Because the two workloads behave differently, mixing them in one schedule can cause problems: the prefill of an extremely long input may noticeably stall requests that are currently decoding.
Two common engineering approaches exist: scheduling the two phases separately, or limiting the total number of prefill tokens per scheduling step so that long requests do not block short ones.
3. Continuous Batching
Static batching requires all requests in a batch to start and finish together. Short requests must wait for the longest one to complete, wasting resources. Continuous batching removes completed requests and immediately admits new ones from the waiting queue at the end of each decoding step, keeping GPU utilization high.
The following is illustrative scheduling logic intended to convey the idea, not tied to any specific framework:
def schedule_step(running, waiting, kv_pool, token_budget):# Running requests each generate one token this step; deduct that budget firstbudget = token_budget - len(running)# Try to admit new requests in arrival orderwhile waiting and budget > 0:req = waiting[0]if req.prompt_len > budget:break # Prefill exceeds this step's budget; defer to the next stepif not kv_pool.can_allocate(req.prompt_len + req.max_new_tokens):break # Not enough VRAM; keep the request queuedwaiting.popleft()kv_pool.allocate(req)running.append(req)budget -= req.prompt_lenreturn running
This code highlights three points. First, the scheduling unit is a token budget, not a request count. Second, VRAM availability is one of the admission conditions. Third, prefill and decoding share the same budget, which bounds the duration of a single step. A real system also needs to reclaim resources from completed requests and handle priorities and fairness.
4. Memory Management Determines Concurrency Limits
During decoding, every active request must store the Keys and Values of all previous tokens—the KV cache. Its per-token memory footprint can be roughly estimated as:
Per-token usage ≈ 2 × layers × KV heads × head dimension × bytes per element
For FP16, each element takes 2 bytes. The more layers a model has, the longer the context, and the higher the concurrency, the larger the KV cache becomes—often exhausting VRAM before the model weights do.
Pre-allocating a contiguous block of memory per request creates significant fragmentation and waste, since many requests generate far fewer tokens than reserved. Paged management splits the KV cache into fixed-size blocks allocated on demand—an approach similar to virtual memory in operating systems. This allows substantially more concurrent requests.
Prefix reuse is another common source of savings. When multiple requests share the same system prompt or document context, the service can cache that portion of the KV cache and let subsequent requests reuse it, avoiding redundant prefill computation. Cache hits require an exactly matching prefix, so applications should place fixed content at the beginning of the prompt and variable content at the end.
5. Quantization, Parallelism, and Speculative Decoding
These techniques are general-purpose tools; all of them trade precision, communication, or extra computation for speed and cost improvements.
Quantization converts weights or activations from high precision to lower-bit representations, reducing memory usage and memory traffic. Common choices include 8-bit and 4-bit integer quantization. Lower bit widths bring bigger gains but higher risk of accuracy loss. Before going live, compare output quality on evaluation sets from your actual business—not just on general benchmarks.
Tensor parallelism splits the computation of a single layer across multiple GPUs. It enables models that exceed a single card’s memory to run and shortens per-step computation time. The cost is inter-GPU communication at every layer, so it is usually applied within a node with high interconnect bandwidth. For multi-node deployments, pipeline parallelism or hybrid strategies are more common, and the choice depends on the network topology.
Speculative decoding uses a small draft model to propose several candidate tokens, which the target large model verifies in one pass. If most candidates are accepted, the actual number of decoding steps decreases. The benefit depends on how well the draft model agrees with the target model. The more deterministic the task—for example, structured output or code completion—the higher the acceptance rate tends to be. For open-ended long-form generation, the benefit is generally weaker.
6. Service-Layer Reliability Design
The inference engine is only one link in the chain. Online stability is often determined by service-layer policies.
- Request tiering: Queue interactive requests separately from offline batch requests to protect TTFT for the former. Offline jobs can run during off-peak hours or on idle resources.
- Rate limiting and admission control: Set rate limits per user, tenant, or API, and cap the maximum queue length. When the queue is too long, returning a clear busy error makes client retry and fallback easier than letting all requests time out.
- Timeouts and cancellation: When a client disconnects, the server should promptly release the corresponding compute resources and KV blocks. Otherwise, stale requests keep consuming VRAM.
- Fallback strategies: During peak load, switch to a smaller model version, reduce the maximum output length, or disable non-essential features. Fallback plans should be documented in the runbook in advance and rehearsed regularly.
7. Elasticity and Cost Control
Inference workloads typically show strong daily patterns and sudden traffic spikes. Fixed-capacity deployments either leave resources idle or cause heavy queuing at peak. Elastic scaling raises three concerns.
Scaling signals. Relying solely on CPU or GPU utilization is unreliable, because utilization can be low during decoding while the queue is already backing up. Better signals are queueing time, the number of waiting requests, and TTFT percentiles.
Cold starts. Loading large model weights takes time, and naive scaling causes noticeable latency spikes. A common practice is to keep a pool of pre-warmed instances and set scaling thresholds slightly early, leaving time for new instances to load.
Cost accounting. The core metric should be “total cost per million output tokens.” Include hardware depreciation, energy, idle time, and the cost of failed retries—avoid judging by hourly GPU price alone.
8. Observability and Release Process
Establish the following monitoring metrics before launch:
| Metric | Meaning | Purpose |
|---|---|---|
| TTFT percentiles | P50, P95, P99 of time to first token | Measures interactive experience |
| TPOT | Per-token generation time | Assesses decoding efficiency |
| Queue length and wait time | Queuing before admission | Triggers scaling and rate limiting |
| KV block utilization | Share of cached blocks in VRAM in use | Anticipates memory bottlenecks |
| Error and timeout rates | Broken down by error type | Locates failures |
Model updates should follow a gradual rollout process: start with a small percentage of traffic, monitor the metrics above, and increase traffic step by step until full deployment.
