A Practical Guide to Large-Scale Inference Deployment

    This guide explains how to deploy large-scale inference services, covering why inference requires a different engineering approach than training, how to define service level objectives, capacity planning from a single-instance baseline to cluster topology, parallelism and GPU memory strategies, scheduling and batching, prefix and semantic caching, elastic autoscaling and traffic governance, observability and stability, rollout and load testing, and common pitfalls. It is intended for engineers who need a layered, metrics-driven design that balances latency, throughput, and cost.

    1. Where the Problem Starts: Why Large-Scale Inference Is Not Training

    Many teams move a model from an experimental environment to production by reusing the resource planning approach from the training stage. Once traffic ramps up, they quickly run into queuing, timeouts, and runaway costs. The root cause is that the two workloads have completely different resource profiles: training is a throughput-oriented, latency-tolerant, relatively static offline job, while inference is a latency-oriented online service whose load fluctuates sharply with business cycles and is extremely sensitive to tail latency.

    The first principle of large-scale inference deployment is therefore to design around a service, not a job. The service metrics you need to define typically include time to first byte, latency percentiles end to end (such as P95 and P99), requests per second, concurrent sessions, the maximum concurrency a single GPU can handle, and the compute cost per request. These metrics involve hard trade-offs. Any promise to “both maximize throughput and minimize latency” does not hold up in engineering, so priorities must be chosen explicitly.

    A practical approach is to write the metrics as verifiable service level objectives, for example:

    1. service_objective:
    2. ttft_p95_ms: 800 # time to first byte
    3. e2e_p99_ms: 6000 # end-to-end latency
    4. throughput_qps: 120 # peak requests per second
    5. max_concurrent: 2000 # concurrent sessions
    6. availability: 0.995

    With quantified targets, later decisions on parallelism strategy, batching parameters, and autoscaling thresholds have a basis, rather than being set by guesswork.

    2. Capacity Planning: From a Single-GPU Baseline to Cluster Topology

    The core action of capacity planning is to establish a “single-instance baseline.” Under controlled load testing, increase load step by step and record where the latency curve shows an inflection point. The concurrency at that point is the safe concurrency limit for a single instance (typically 70%–80% of it is used as the production watermark). Then divide peak QPS by single-instance capacity, add a redundancy factor (1.3–1.5 is recommended) and cross-availability-zone disaster-recovery replicas, and you get the total number of instances.

    Note in particular that GPU memory, not compute, is often the first bottleneck. GPU memory is consumed jointly by static weights, runtime activations, batch buffers, and context cache. A rough check can use the following inequality:

    1. weight usage + peak activations + batch buffers + context cache <= single-GPU memory × safety factor (0.9)

    When the context length distribution has a pronounced long tail, plan by P95 length rather than average length; otherwise long requests will crowd out the cache and trigger cascading queuing.

    3. Parallelism and GPU Memory: General Strategies for Fitting Large Models

    For models that exceed the memory of a single GPU, the industry commonly combines three types of parallelism: tensor parallelism splits the operators of a single layer across multiple GPUs, with frequent communication but latency-friendly behavior; pipeline parallelism splits by layer, with little communication but bubbles; data parallelism scales throughput horizontally. A common trade-off in practice is “intra-machine tensor parallelism + inter-machine pipeline/data parallelism,” letting high-bandwidth interconnects carry high-frequency communication and putting low-frequency communication on slower links.

    GPU memory optimization relies on several general techniques: half-precision or lower-precision storage, operator fusion, paged cache management to reduce fragmentation, and offloading cold data to host memory. A schematic configuration structure is as follows:

    1. runtime_config = {
    2. "dtype": "float16",
    3. "tensor_parallel_size": 4, # intra-machine split
    4. "pipeline_parallel_size": 2, # cross-node split
    5. "kv_cache": {
    6. "page_size": 16, # paging granularity
    7. "gpu_mem_fraction": 0.85,
    8. "enable_offload": True, # offload cold cache
    9. },
    10. }

    There is no universally optimal value for these parameters; they must be tuned with real measurements. Too high a parallelism degree amplifies communication overhead, too small a paging granularity increases management cost, and too large a granularity worsens internal fragmentation.

    4. Scheduling and Batching: The Main Source of Throughput

    Throughput gains in online inference come almost entirely from batching, but batching directly raises latency, so the scheduling strategy is the single most critical part of the whole system. Continuous batching (dynamically inserting new requests during the decoding phase and evicting completed ones) is significantly better than static batching, as it avoids short requests waiting behind long ones.

    The scheduler needs to manage two queues at the same time: a waiting queue and a running queue, and perform admission control based on maximum batch size, maximum token budget, and preemption policy. When resources are tight, the preemption mechanism can offload the cache of low-priority requests or even fall them back to the waiting queue, protecting high-priority traffic. The decision logic is expressed in pseudocode:

    1. while True:
    2. batch = scheduler.form_batch(max_batch_size=B, max_tokens=T)
    3. if batch.is_empty():
    4. sleep(1ms); continue
    5. outputs = engine.step(batch) # one forward/decode iteration
    6. for req in batch.finished():
    7. stream(req) # stream the response
    8. cache.release(req)
    9. scheduler.reclaim_preempted() # reclaim preempted resources

    Tuning notes: the maximum batch size is constrained jointly by GPU memory and the latency budget; a token budget prevents long requests from blowing up GPU memory better than a request count does; streaming output greatly improves perceived latency even if total time is unchanged.

    5. Caching and Reuse: An Undervalued Cost Lever

    In large-scale settings, request prefixes are highly repetitive (system prompts, templates, few-shot examples). Prefix cache reuse turns repeated computation into a single computation and is one of the most cost-effective optimizations. In practice you need cache key design, an invalidation strategy, and a capacity limit, to avoid an inflated hit rate accompanied by memory thrashing.

    Semantic caching targets the result layer: for high-frequency similar questions, return historical results directly. It requires a similarity threshold and an expiration time, and should be enabled cautiously when the business is sensitive to accuracy. The cache layer must be observable, exposing at least four metrics: hit rate, average reuse length, eviction count, and memory usage.

    6. Elastic Autoscaling and Traffic Governance

    Inference load has clear peaks and valleys, and static always-on replicas waste resources during valleys. A sound shape is “minimum always-on replicas + elastic scale-out driven by queue metrics.” The scaling signal should not look only at CPU; metrics closer to the nature of the service are waiting queue length, batch saturation, and P95 latency. Because starting a model instance involves weight loading and warm-up, scaling must happen ahead of time: predictive scaling can be based on historical patterns, and a buffer of instances should be kept to absorb bursts.

    For traffic governance, the recommendations are: rate limit by tenant or priority; set request timeouts and a retry budget to avoid retry storms; route requests with extremely long context to a dedicated instance pool so they do not pollute the main pool’s cache; and validate request body size and context length at the gateway, blocking invalid traffic before it reaches compute.

    7. Observability and Stability

    Observability should cover four dimensions: metrics (throughput, latency percentiles, queue length, cache hits, GPU memory usage), logs (structured request trace identifiers), tracing (breakdown of queuing, prefill, and decode stage times), and quality evaluation (output truncation rate, error rate). Stage-level time breakdown is especially important: only by separating “queue time” from “compute time” can you tell whether the bottleneck is scheduling or compute.

    For stability design, prepare degradation paths for different priorities: shorten the maximum generation length, lower the batch limit, switch to a smaller backup model or return a cached result, so that core availability is preserved under overload.

    8. Rollout Process and Load Testing Method

    A four-step approach is recommended: offline baseline (single-instance inflection point and GPU memory check) → shadow traffic (replicate real traffic without returning results, verifying capacity and error rate) → small-percentage canary (ramp up by tenant or region, watching percentile latency) → full rollout with routine capacity inspections. Load tests must replay the real length distribution and arrival curve, driven by a Poisson process or the actual business rhythm rather than uniform requests; otherwise the conclusions are seriously distorted.

    9. Common Pitfalls

    First, looking only at average latency and ignoring the long tail; second, using request count rather than token volume as the capacity unit; third, binding the scaling threshold to indirect metrics such as CPU; fourth, caches with no limit causing memory thrashing; fifth, retries with no budget triggering an avalanche; sixth, ignoring warm-up and counting cold-start time as service latency. Avoiding these problems costs far less than fixing them after the fact.

    In summary, the competitiveness of large-scale inference deployment comes from layered design and a quantified feedback loop: service objectives define the metrics, a single-instance baseline derives capacity, parallelism and GPU memory strategies determine the feasible region, scheduling and caching determine throughput and cost, and elasticity and governance determine stability. To shorten the build cycle further, you can rely on general cloud product capabilities such as the container platform, object storage, message queue, logging service, and monitoring and alerting offered by Baidu AI Cloud to quickly stand up this layered system, keeping engineering focus on model quality and business iteration.