LLM Inference Latency: Causes and Optimization Practices for Open-Source Models

    This article explains why inference latency occurs when self-hosting open-source large language models and how to optimize it. It covers how compute supply constraints propagate into latency, defines four key metrics (TTFT, TPOT, end-to-end latency, and throughput), and breaks down six major sources of delay, including memory bandwidth, batching strategy, cache reuse, parallelism, quantization, and request length distribution. It also outlines a practical tuning workflow, robustness patterns at the architecture level, and common pitfalls to avoid.

    1. Background: How Compute Supply Uncertainty Propagates into Inference Latency

    Over the past year or two, open-weight models have been iterating at a noticeably faster pace, and more enterprises are motivated to build their own inference services. However, an often-overlooked reality is that whether a model can be deployed successfully depends not only on the algorithm itself but also on the compute resources available. When the supply of a specific accelerator card model is restricted externally, development schedules and launch timelines are forced to slip, and teams must re-evaluate hardware selection and capacity planning.

    These fluctuations eventually surface on the business side as “latency.” Understanding this propagation chain is the prerequisite for sound engineering optimization:

    • Compute supply constraints → changes in available accelerator models and quantities → different per-card memory and bandwidth tiers → batching and parallelism strategies must be re-tuned → fluctuations in time-to-first-token and throughput metrics.
    • Therefore, performance optimization cannot focus solely on model code; hardware assumptions must be written as configurable items to avoid全面失准 when the environment changes.

    2. Define the Metrics First: Latency Is Not a Single Number

    Most performance discussions are inefficient because “latency” is treated as a single value. In engineering, it should be broken down into at least four metrics:

    1. Time to First Token (TTFT): The time from sending a request to receiving the first output token, which determines interactive responsiveness.
    2. Time Per Output Token (TPOT): The average time for each subsequent output token, which determines reading fluency.
    3. End-to-end latency: The total time to complete an entire response, strongly correlated with output length.
    4. Throughput and concurrency: The number of requests that can be served per unit time, which determines unit cost.

    It is recommended to write metrics as explicit configurations for easy comparison across environments:

    1. # Explicit definition of the performance baseline to avoid vague conclusions like "it feels slower"
    2. BENCH = {
    3. "ttft_ms": 800, # TTFT target
    4. "tpot_ms": 40, # TPOT target
    5. "max_tokens": 1024, # output length limit
    6. "concurrency": 32, # concurrency level
    7. }

    3. Six Major Sources of Latency

    3.1 Memory Capacity and Bandwidth

    Autoregressive generation is a memory-access-intensive workload; during the decoding phase, weights and cache must be re-read for every token generated. When memory bandwidth is insufficient, even high compute power will idle. If the model does not fit on a single card, cross-card communication is introduced, further increasing TPOT.

    3.2 Batching Strategy

    Static batching causes short requests to wait for long ones, amplifying tail latency; continuous batching (dynamically inserting and retiring requests along the sequence dimension) can significantly improve utilization but requires more sophisticated scheduling and preemption logic.

    3.3 Cache Reuse

    Prefix caching can reuse the computation results of repeated prefixes such as system prompts and long documents, offering substantial benefits for fixed-template workloads. The cost is that cache eviction policies and memory usage must be managed uniformly.

    3.4 Parallelism Partitioning

    Tensor parallelism reduces per-card pressure but introduces high-frequency communication; pipeline parallelism has low communication volume but introduces pipeline bubbles. An inappropriate choice of partitioning dimension can let communication overhead eat up the gains from parallelism.

    3.5 Quantization and Precision

    Low-bit quantization can reduce the amount of weight reading, thereby lowering TPOT, but may cause fluctuations in output quality, requiring trade-offs based on business tolerance.

    3.6 Request and Output Length Distribution

    Long-tail, ultra-long outputs occupy slots for extended periods. Setting reasonable output limits and timeouts is a common approach to stabilizing tail latency.

    4. An Actionable Tuning Path

    1. Establish a baseline: Fix input/output lengths and concurrency levels, record the four metrics, and form a reproducible comparison.
    2. Identify bottlenecks: Observe memory usage, bandwidth utilization, and batching wait time to determine whether the constraint is memory-access-bound or scheduling-bound.
    3. Single-variable validation: Change only one variable at a time (batching strategy, cache toggle, quantization level) to avoid confounding multiple factors.
    4. Capacity planning: Work backward from peak concurrency and output length distribution to determine required memory and card count, reserving redundancy to handle supply fluctuations.
    5. Continuous monitoring: Integrate latency metrics into logging services and monitoring alerts, setting percentile thresholds rather than average-based alerts.

    A sample load-testing skeleton:

    1. def run_bench(requests, cfg):
    2. stats = {"ttft": [], "tpot": []}
    3. for req in requests:
    4. t0 = now_ms()
    5. first = stream_first_token(req)
    6. stats["ttft"].append(now_ms() - t0)
    7. stats["tpot"].append((now_ms() - t0) / max(req.max_tokens, 1))
    8. return summarize(stats, cfg) # output P50/P95/P99

    5. Robustness Design at the Architecture Level

    • Abstract hardware assumptions: Write card type, memory, and parallelism as configurations so that only the configuration changes when the environment changes, not the code.
    • Tiered service: Deploy latency-sensitive and throughput-priority traffic in separate pools so they do not interfere with each other.
    • Elastic scaling: Combine container platforms and message queues for queuing and scaling out, turning burst traffic into controllable latency.
    • Degradation strategy: During peak periods, shorten output limits or switch to a smaller model tier to prioritize availability.

    6. Common Pitfalls

    • Looking only at average latency while ignoring P95/P99, leading to chronic capacity shortfalls.
    • Equating throughput improvement with latency reduction; the two often move in opposite directions under batching.
    • Repeatedly tuning parameters without reproducible conditions, so conclusions cannot be consolidated.
    • Ignoring input length distribution and using a single test case to represent real traffic.

    7. Conclusion

    Self-hosting inference services for open-source models is essentially a continuous trade-off among compute supply, memory bandwidth, and scheduling strategy. Only by clearly defining metrics, rigorously identifying bottlenecks, and making hardware assumptions configurable can teams quickly re-tune without losing stability when resource conditions change. If you need managed model services along with supporting object storage, container platforms, and logging and monitoring capabilities, Baidu AI Cloud can provide the corresponding general-purpose infrastructure support to help teams focus their energy on business outcomes themselves.