LLM Latency Optimization: Practical Strategies for a Better Interactive Experience

    This article breaks down large language model latency into measurable metrics such as time to first token, tokens per second, end-to-end completion time, and interruption rate. It examines the four main sources of delay—prefill, decoding, reasoning chains, and multimodal output—and presents engineering practices including streaming output, first-token prioritization, tiered routing, cancellable requests, and reproducible evaluation with offline benchmarks, canary comparisons, and production monitoring. The goal is to turn subjective "waiting" complaints into tunable technical decisions.

    1. Background: Why “Waiting Time” Has Become a Core UX Metric

    When people discuss conversational AI applications, they rarely lead with parameter counts or benchmark scores. Instead, they ask: “Is it fast?” “Do I have to wait long?” “Can it just read the answer aloud?” Behind these questions is a long-underestimated engineering fact: the perceived quality of an LLM experience is shaped largely by its latency structure, not by output text quality alone.

    From a system perspective, a single chat request passes through several stages: request intake and authentication, context assembly and truncation, the prefill phase that computes the input sequence in parallel, the decode phase that generates tokens autoregressively one at a time, an optional reasoning or “thinking” chain, post-processing and safety filtering, and finally rendering or speech synthesis. The “slowness” users perceive may originate in any of these stages, and different application forms are sensitive to different stages.

    For this reason, arguing about “which one feels better” on subjective grounds cannot guide engineering decisions. A more rigorous approach is to translate subjective impressions into measurable technical metrics, then optimize against those metrics.

    2. Breaking “Fast” Into Measurable Metrics

    Engineering practice usually splits latency into two independent quantities:

    • Time To First Token (TTFT): the time from sending the request to receiving the first visible output. It drives the instinctive sense of whether the system is stuck.
    • Tokens Per Second (TPS): the output speed after the first token, which determines whether reading feels smooth.

    Two frequently ignored quantities are worth adding:

    • End-to-end completion time: the time a task actually takes to finish, which matters especially for long-form generation and code generation.
    • Interruption rate: the share of cases where users actively interrupt or rewrite before an output completes. It is a strong signal of UX problems.

    A sketch of a measurement skeleton follows (pseudocode, illustrating measurement definitions rather than any specific API):

    1. def measure_once(call_fn, prompt):
    2. t0 = now()
    3. stream = call_fn(prompt) # returns an iterable of output chunks
    4. first = next(stream)
    5. ttft = first.ts - t0 # time to first token
    6. start = first.ts
    7. tokens = 0
    8. for chunk in stream:
    9. tokens += chunk.n_tokens
    10. total = now() - t0
    11. tps = tokens / max(total - ttft, 1e-6)
    12. return {"ttft": ttft, "tps": tps, "total": total}

    One point deserves emphasis: a single measurement is meaningless. Production evaluation should use percentiles (P50/P90/P99) rather than averages, because averages hide the long tail—and the long tail is exactly what users complain about.

    3. Four Main Sources of Latency and Their Remedies

    3.1 Prefill: Longer Inputs, Slower First Token

    Time to first token correlates roughly with input length. Long contexts, large batches of retrieved snippets, and repeatedly carried conversation history all push first-token time up significantly.

    Viable strategies include context compression and summarization, reranking and truncating retrieved snippets, using a rolling window for conversation history, and reusing cached stable prefixes (commonly known as prefix caching). Engineers should treat the “context budget” as an explicit resource to manage, rather than stuffing content into the prompt without restraint.

    3.2 Decode: Throughput Bounded by Batching and Memory Bandwidth

    Decoding proceeds token by token, and throughput is typically constrained by memory bandwidth and batch scheduling policy. Improvement options include raising concurrency to form more effective batches, using quantization to reduce weight bandwidth pressure, adopting paged memory management to limit fragmentation, and capping maximum output length when the business allows.

    A caveat: higher concurrency often improves overall throughput but may raise single-request time to first token. This is an explicit trade-off whose ratio should be decided by business priority.

    3.3 Reasoning Chains: An Explicit Trade of Quality for Time

    Output modes that include a reasoning process are essentially trading time for accuracy on complex problems. When earlier discussions describe “thinking for ages and waiting too long,” engineering should not simply attribute this to “slowness” but treat it as a configurable cost item.

    The recommended approach is tiered routing: simple intents take a low-latency path, while complex reasoning, code, and math tasks enable deep thinking, with a cap on thinking length. Sketch of the logic:

    1. def route(prompt, meta):
    2. if meta["intent"] in ("chitchat", "rewrite", "extract"):
    3. return {"mode": "fast", "max_output": 512}
    4. if meta["intent"] in ("math", "code", "multi_hop"):
    5. return {"mode": "deep", "max_output": 4096}
    6. return {"mode": "fast", "max_output": 1024}

    3.4 Output Modality: Longer Multimodal Pipelines

    Capabilities such as speech playback and voice input introduce extra synthesis and streaming delivery stages. Their UX value is high—they free the user’s hands and suit mobile and in-car scenarios—but the pipeline is longer. Generation and synthesis must run in streaming fashion, side by side, or the first-token advantage is fully cancelled out.

    4. Engineering Practices for Experience Optimization

    • Streaming output: switching from “return everything at once” to incremental delivery is the most cost-effective way to improve the waiting experience.
    • First-token-first scheduling: when resources are tight, guarantee the first token first, then fill in subsequent throughput.
    • Skeleton first: return a structured skeleton or key points first, then fill in details, letting users judge early whether the direction is right.
    • Cancellable and retryable: offering interruption and regeneration noticeably reduces frustration.
    • Explainable progress: for tasks that will inevitably be long, provide stage hints that turn uncontrollable waiting into predictable waiting.
    • Device and edge collaboration: push lightweight tasks down to the device or a nearby node to shorten network round trips.

    5. Building a Reproducible Evaluation Method

    Subjective preference cannot serve as an architecture basis. A three-layer evaluation is recommended:

    1. Offline benchmark set: a fixed prompt set covering short Q&A, long-form summarization, code generation, and multi-turn dialogue, reporting percentile latency and quality scores.
    2. Canary comparison: small-traffic parallel comparison of different routing strategies and parameter configurations, watching interruption and rewrite rates.
    3. Production monitoring: dashboards and alerts for time to first token, throughput, error rate, and timeout rate, with trace retention so bottleneck stages can be located.

    On the cloud, these can be combined with container platforms hosting inference services, message queues for peak shaving, object storage for evaluation datasets, and logging plus monitoring and alerting for observability. All of these are general capability categories; specific choices should be decided by load testing against your own workload characteristics.

    6. Conclusion

    The debate over “which one is smoother” ultimately converges on three engineering questions: whether time to first token is controllable, whether long tasks are predictable, and whether the output modality matches the scenario. Turning subjective experience into metrics, making trade-offs with tiered routing and streaming output, and continuously calibrating with monitoring and canary releases is the sustainable optimization path. Baidu AI Cloud continues to invest in model services and inference acceleration, and developers can build a low-latency conversational experience tailored to their own business on top of these general methods.