A Practical Guide to Large-Scale LLM Inference Deployment

    This guide explains how to design and operate large language model inference services under compute budgets and latency constraints. It covers profiling workload characteristics, managing GPU memory and KV cache, applying continuous batching and scheduling strategies, building elastic scaling with cost attribution, and closing the observability and load-testing loop. It also highlights common pitfalls and a phased rollout path, helping teams maximize cost-effective throughput rather than merely getting a model to run.

    1. Background: Capability Limits vs. Cost Limits

    A model’s capability ceiling is determined by the model itself, but what users actually experience—whether it is fast, stable, and affordable—often depends on the quality of the inference serving layer. When online request volume grows from a few thousand per day to hundreds of millions, an inference system quickly shifts from “it runs” to “it runs, but it cannot hold up.” Common symptoms include:

    • Queueing latency spikes during peak hours
    • GPU memory saturated by a small number of long requests
    • GPU utilization fluctuating unpredictably
    • Cost rising linearly after scaling out, with limited throughput gains

    The core problem an inference framework solves is not “getting the model to run,” but maximizing effective throughput per unit of cost under a given compute budget and latency constraints. This requires teams to optimize four dimensions simultaneously: throughput (tokens/s), latency (time to first token and end-to-end latency), GPU memory usage, and fault recovery.

    2. Real Characteristics of Inference Workloads

    Before optimizing anything, you must profile the workload. Otherwise, all tuning is guesswork. At minimum, collect the following metrics:

    • Input length distribution: short Q&A and long-document summarization can differ by an order of magnitude in memory and compute consumption.
    • Output length distribution: generation is token-by-token autoregressive decoding, so longer outputs mean a larger share of time spent in the decode phase.
    • Request arrival curve: whether there are clear peaks and valleys, and whether traffic can be isolated by business segment.
    • Concurrency pattern: a few very long requests versus many short requests—the optimal batching strategy for each is completely different.

    A simplified classification logic:

    1. def classify(workload):
    2. if workload.p99_input_len > 8192:
    3. return "prefill_bound" # Prefill-dominated, compute-intensive
    4. if workload.avg_output_len > 512:
    5. return "decode_bound" # Decode-dominated, memory-bandwidth-intensive
    6. return "balanced"

    The prefill phase is compute-intensive, with the bottleneck in compute. The decode phase is memory-access-intensive, with the bottleneck in GPU memory bandwidth and KV cache capacity. Confusing these two types of bottlenecks is the most common reason performance optimization fails.

    3. GPU Memory and KV Cache Management

    Autoregressive generation requires caching the key-value pairs of historical tokens. This usage grows linearly with concurrency and sequence length, making it the primary constraint in long-context scenarios. A widely adopted approach in the industry is paged memory management, which splits the cache into fixed-size blocks allocated on demand, significantly reducing fragmentation and reserved waste. Key practices:

    1. Set an upper limit on the maximum number of concurrent sequences per instance to prevent GPU memory from being exhausted by a few requests, which would make the whole instance unavailable.
    2. Set admission thresholds and queueing policies for very long inputs; when necessary, fall back to a smaller model or an asynchronous task queue.
    3. Requests sharing the same prefix (such as a common system prompt) can share the cached prefix to reduce redundant computation.
    4. Establish GPU memory watermark monitoring, and actively throttle when approaching the threshold rather than crashing passively.

    4. Batching and Scheduling Strategies

    Static batching almost inevitably wastes resources in online scenarios: short requests must wait for long requests to finish. Continuous batching (dynamically swapping requests in and out at decode-step granularity) has become a common industry solution, and its core is iteration-level scheduling.

    A scheduler typically has to handle three types of conflicts: latency priority versus throughput priority, how to interleave long and short requests, and how priority queues prevent starvation. A practical scheduling skeleton:

    1. Each scheduling round:
    2. 1. Pick requests from the waiting queue ordered by priority and estimated cost
    3. 2. If memory headroom is insufficient, trigger preemption: pause low-priority sequences and swap out their cache
    4. 3. Assemble this batch's tokens and run one forward pass
    5. 4. Release resources immediately when a sequence completes; fill the free slot with a new request

    Combined with chunked prefill (splitting the prefill of a long input into multiple small chunks interleaved with decoding), this can effectively alleviate the blocking of short requests’ time to first token by long requests.

    5. Elastic Scaling and Cost Governance

    The key to inference cost optimization is making the compute supply curve match the request curve. A layered design is recommended:

    • Base layer: a minimum number of always-on instances to guarantee low latency and avoid cold starts.
    • Elastic layer: trigger scaling based on multiple metrics such as queue length, batch utilization, and GPU memory watermark, rather than CPU alone.
    • Buffer layer: sink non-real-time tasks (batch summarization, offline evaluation) into a message queue for asynchronous consumption to smooth out peaks and fill valleys.

    Model weights and runtime images should be stored in object storage and mounted read-only, with the container platform responsible for launching and rolling updates. Logging and monitoring/alerting systems need to cover custom metrics such as queueing time, batch size, cache hit rate, and cost per request. Cost attribution must be broken down by business owner and model version; otherwise, you cannot tell whether an optimization is actually effective.

    6. Observability and the Load-Testing Loop

    Without measurement, there is no optimization. The minimum viable observability set includes: time to first token at P50/P95/P99, end-to-end latency, output tokens per second, average batch size, GPU memory usage curve, queueing time, and error and timeout rates. Load tests should closely match the real length distribution and cover mixed scenarios of burst traffic and very long requests, avoiding optimistic conclusions drawn from uniform short requests only.

    7. Common Pitfalls

    • Blindly increasing batch size: beyond the memory and bandwidth inflection point, latency worsens while throughput barely increases.
    • Optimizing only the model and not the serving layer: gains from quantization and distillation are often offset by inefficient scheduling.
    • Ignoring long-tail requests: a few very long requests can pull up overall P99 and need to be isolated and throttled separately.
    • Lacking a fallback plan: during peak hours, the system should support switching to a smaller model, shortening the maximum output length, or falling back to asynchronous processing.

    Phase one: complete workload profiling and baseline load testing. Phase two: introduce continuous batching and paged cache management. Phase three: fill in elastic scaling, asynchronous buffering, and cost attribution. Phase four: establish a routine load-testing and capacity-planning mechanism. Baidu AI Cloud can provide standardized infrastructure support for the architecture above through general capabilities such as container platforms, object storage, logging services, and monitoring/alerting, allowing teams to focus their energy on scheduling strategies and the business experience itself.