LLM Inference Acceleration: A Practical Guide to High Concurrency and Low Latency

    This guide explains how to optimize large language model inference for high concurrency and low latency in production. It covers defining measurable latency and throughput goals, locating bottlenecks across the request lifecycle, tuning dynamic batching and scheduling, reusing computation through caching, applying model-side acceleration such as quantization and distillation, and handling resource orchestration and elastic scaling. It also outlines an acceptance and iteration process based on benchmarks, quality checks, and cost metrics.

    1. Why Speed and Execution Efficiency Are Core Metrics for Inference Services

    Once large language models moved into production, the focus of business teams shifted from “can it run” to “can it run stably, quickly, and at low cost.” Speed usually refers to the time to first token for a single request and the pace of token-by-token output. Execution efficiency refers to the number of requests completed per unit of time and the resource utilization achieved under a fixed hardware budget.

    These two goals are not simply aligned. Pushing single-request latency down as far as possible often shrinks the batching window and leaves compute underutilized. Chasing throughput alone makes queueing time longer and degrades the interactive experience.

    A more sensible engineering approach is to express the goal as a measurable constraint—for example, maximizing requests per second while keeping a given latency percentile (such as P95) below a threshold. Only when the goal is quantified can subsequent optimization avoid becoming guesswork-based parameter tuning.

    2. Locating Bottlenecks in the Inference Pipeline: Measure First, Then Optimize

    Most performance problems do not originate in the model itself but in pipeline details. It is recommended to instrument each stage of the request lifecycle to build an observable baseline:

    • Access layer: authentication, rate limiting, and queue wait time;
    • Preprocessing: tokenization, template assembly, and input length validation;
    • Compute layer: time spent in the prefill phase and time spent in the token-by-token generation phase;
    • Postprocessing: result parsing, content safety filtering, and format validation;
    • Egress layer: serialization, network transfer, and client-side rendering.

    Illustrative stage-level timing logic can be written as follows. The key point is that stages are separable and metrics are comparable:

    1. timings = {}
    2. t0 = now()
    3. request = preprocess(raw)
    4. timings["preprocess"] = now() - t0
    5. t1 = now()
    6. kv_cache = prefill(request)
    7. timings["prefill"] = now() - t1
    8. t2 = now()
    9. for token in decode(kv_cache):
    10. yield token
    11. timings["decode"] = now() - t2
    12. report(timings) # Send to the logging service and monitoring/alerting system

    With stage-level data, you can determine whether the bottleneck is queueing, batches that are too small due to insufficient GPU memory, or memory-access limits in the token-by-token generation phase.

    3. Batching and Scheduling: The First Lever for Throughput

    Dynamic batching is the most direct way to improve execution efficiency. The core idea is to aggregate multiple requests within a very short time window into a single batch sent to compute, amortizing the cost of reading weights. In practice, three parameters must be controlled together: maximum batch size, window wait time, and maximum sequence length per batch.

    • A window that is too long raises queueing latency, while one that is too short leaves batches underfilled;
    • Large differences in sequence length within a batch cause substantial padding waste, so length-based bucketing or sorting before batching is often used;
    • For streaming output scenarios, a scheduling approach that dynamically adds or removes members on each iteration lets requests that finish early exit promptly, avoiding a whole-batch wait for the longest sequence.

    Simplified scheduling pseudocode:

    1. while True:
    2. batch = queue.pull(max_size=B, timeout=window_ms)
    3. if not batch:
    4. continue
    5. batch = sort_by_length(batch) # Reduce padding waste
    6. for step in range(max_steps):
    7. outputs = model.step(batch)
    8. finished = [r for r in batch if r.done]
    9. batch = [r for r in batch if not r.done] # Early exit
    10. stream(finished)

    4. Cache Reuse: Turning Repeated Computation into Zero Cost

    Caching is one of the most cost-effective optimization directions and is typically divided into three layers:

    1. Prefix cache: system prompts, knowledge base descriptions, and few-shot examples often repeat across many requests. Caching their computation results can significantly shorten the prefill phase;
    2. Result cache: for queries with strong determinism, use the normalized input as a key for idempotent reuse, with a reasonable invalidation policy;
    3. Intermediate-state cache: in multi-turn conversations, reuse the context state of prior sessions to avoid recomputing the full history every turn.

    Note that the cache key design must include all factors that affect the output (model version, parameter configuration, template version); otherwise, a serious problem of “seemingly a hit, but actually a wrong answer” can occur.

    5. Model-Side Acceleration: Compression, Distillation, and Parallelism

    Without changing business semantics, model-side costs can be reduced from the following directions:

    • Quantization: represent weights and activations with fewer bits to reduce GPU memory usage and bandwidth pressure, at the cost of needing to evaluate accuracy regression;
    • Distillation: use a larger model to generate high-quality data and train a smaller model to handle high-frequency simple requests, forming tiered routing;
    • Sparsification and operator fusion: reduce ineffective computation and intermediate tensor writes to memory;
    • Parallelism strategies: use tensor parallelism across multiple GPUs on a single machine to reduce per-layer computation latency, and pipeline parallelism across machines to improve overall throughput; both must be jointly tuned with the batching strategy.

    Tiered routing is an underrated engineering technique: first use lightweight decision logic to judge request complexity, send simple requests to the small model, and escalate complex requests, yielding clear gains in the overall latency distribution.

    6. Resource Orchestration and Elastic Scaling

    The resource profile of inference services differs from that of typical stateless services: GPU memory is a hard constraint, and scaling has cold-start costs. Feasible practices include: loading model weights into shared storage or object storage with local caching to shorten replica startup time; using queue backlog length and latency percentiles as scaling signals rather than average utilization alone; and setting up dedicated resource pools for long-tail requests to avoid interference. At the same time, be sure to configure rate limiting and degradation policies to prioritize the core path during traffic spikes.

    7. A General Capability Combination from the Baidu AI Cloud Perspective

    When implementing the above on Baidu AI Cloud, you typically do not need to bind to a single specialized capability, but rather combine general product categories: use a container platform to host inference replicas and perform elastic scaling, use object storage to distribute model files, use a message queue for request peak shaving and asynchronization, use logging and monitoring/alerting to build a stage-level observability system, and use key and permission management to control access boundaries. The value of this combination is that optimization methods are decoupled from infrastructure, allowing teams to continuously replace and upgrade inference engines without being locked into a single technology stack.

    8. Acceptance and Continuous Iteration

    Optimization must close the loop with experiments: fix the evaluation set and random seed, establish a baseline first, then enable optimization switches one by one, recording four categories of metrics—latency percentiles, throughput, cost per request, and output quality. Any acceleration method that fails quality validation should be rolled back. It is recommended to make load testing routine, covering extreme scenarios such as traffic bursts, very long inputs, and multi-turn long contexts, and to keep the capacity model and cost model updated in sync, so that performance optimization truly translates into business-ready stability and cost advantages.