LLM Inference Acceleration: Engineering Practices from First-Token Latency to Throughput

    This article explains how to treat speed as a first-class metric in LLM serving. It breaks down latency into TTFT, TPOT, end-to-end latency, and throughput, dissects where time is spent in a request, and covers practical acceleration techniques including continuous batching, chunked prefill, prefix caching, paged KV cache management, speculative decoding, quantization, and model routing. It also provides a benchmarking script for measuring latency percentiles, architecture-level design patterns such as tiered SLOs and graceful degradation, and common pitfalls to avoid.

    1. Why Speed Must Be a First-Class Metric

    In interactive AI applications, output quality sets the ceiling, while response speed sets the floor. No matter how complete an answer is, if users see no feedback within the first three seconds, they will assume the system is stuck. In engineering practice, the experience is typically broken down into two orthogonal metrics:

    • Time To First Token (TTFT): the time from when a request is sent until the first visible token arrives. It determines whether the system feels fast.
    • Time Per Output Token (TPOT): the average interval between tokens after the first one. It determines whether streaming output is smooth.

    From these, two derived metrics matter:

    • End-to-end latency: TTFT + output length × TPOT, which determines total time for long-text scenarios.
    • Throughput (tokens/s or concurrent requests): which determines how many users a given unit of cost can serve.

    These four metrics are naturally in tension. Larger batches improve throughput and reduce per-request cost, but raise both TTFT and TPOT for individual requests. A so-called “turbo mode” is essentially about finding a new operating point on this curve under a given SLO constraint—not simply cranking up a single number.

    2. Where Latency Comes From: Anatomy of a Request

    The time consumed by an inference request can be decomposed into:

    1. Queuing: the request enters the scheduler queue and waits to be included in a batch.
    2. Prefill: all input tokens are processed in parallel. This is compute-bound and is the main source of TTFT in long-context scenarios.
    3. Decode: autoregressive generation, one token per step, limited by memory bandwidth and KV cache reads.
    4. Post-processing and networking: detokenization, content-safety filtering, and streaming chunk forwarding.

    Optimization must target the actual bottleneck: if TTFT is high, look at queuing and prefill first; if TPOT is jittery, focus on KV cache management and long-tail requests within a batch.

    3. General-Purpose Acceleration Techniques

    • Continuous Batching: swaps requests in and out at the iteration level, avoiding the whole batch waiting on the longest request, and significantly improving GPU utilization and tail latency.
    • Chunked Prefill: splits the prefill of long prompts into chunks and interleaves them with decode steps, preventing long requests from monopolizing compute and stalling others.
    • Prefix Caching: system prompts, few-shot examples, and codebase contexts are often highly repetitive. Cache hits skip redundant computation.
    • Paged KV Cache Management: manages cache blocks with a page-table approach, reducing fragmentation and copies, and freeing up memory for higher concurrency.
    • Speculative Decoding: a small draft model guesses multiple tokens at once, and the large model verifies them in parallel. Accepted tokens let generation advance multiple steps at a time, reducing TPOT while preserving the output distribution.
    • Quantization and Kernel Compilation: low-bit weight/activation quantization reduces bandwidth pressure; graph compilation and operator fusion reduce kernel launch overhead.
    • Model Tiering and Routing: simple requests go to a small model or cache; complex requests are escalated to a large model—a layered strategy that trades quality for latency where appropriate.

    Illustrative routing logic:

    1. def route(prompt: str, history: list) -> str:
    2. # Template-like or cache-hit requests take the lightweight path
    3. if is_template_like(prompt) or cache_hit(prompt):
    4. return "small_model"
    5. # Requests needing multi-step reasoning, long context, or tool calls escalate
    6. if len(prompt) > LONG_CTX_THRESHOLD or needs_tooling(prompt):
    7. return "large_model"
    8. return "small_model"

    4. Turning “Fast” into Measurable Numbers

    There is no optimization without measurement. Build your own benchmark script with a fixed input/output length distribution, and report TTFT and TPOT percentiles (P50/P90/P99) rather than just averages:

    1. import json, time, statistics, urllib.request
    2. def bench(url, payload, rounds=20):
    3. ttfts, tpots = [], []
    4. for _ in range(rounds):
    5. req = urllib.request.Request(
    6. url, data=json.dumps(payload).encode(),
    7. headers={"Content-Type": "application/json"})
    8. t0 = time.perf_counter()
    9. first, last, n = None, t0, 0
    10. with urllib.request.urlopen(req) as resp:
    11. for line in resp:
    12. if not line.strip():
    13. continue
    14. now = time.perf_counter()
    15. if first is None:
    16. first = now
    17. last, n = now, n + 1
    18. ttfts.append(first - t0)
    19. if n > 1:
    20. tpots.append((last - first) / (n - 1))
    21. def p(vals, q):
    22. vals = sorted(vals)
    23. return vals[int(len(vals) * q)] if vals else float("nan")
    24. print(f"TTFT P50={p(ttfts,.5):.3f}s P99={p(ttfts,.99):.3f}s")
    25. print(f"TPOT P50={p(tpots,.5)*1000:.1f}ms P99={p(tpots,.99)*1000:.1f}ms")

    Cover three scenarios when benchmarking: short question/short answer, long prompt/short output, and short prompt/long output. Their bottlenecks are completely different, and testing only one leads to wrong conclusions.

    5. Architecture-Level Design

    • Tiered SLOs: assign different latency tiers to “chat/summarization” versus “code generation/complex analysis,” with separate resource and model configurations.
    • Streaming by Default: enable streaming responses by default so users see feedback early—it is the cheapest perceived-latency optimization.
    • Autoscaling and Warmup: scale out/in automatically based on queue length and TTFT metrics, and pre-warm model weights to avoid cold-start spikes.
    • Degradation Paths: during peak traffic, automatically shorten the maximum generation length, switch to a smaller model, or disable non-essential post-processing to preserve availability.
    • Observability: build monitoring and alerting dashboards for TTFT, TPOT, queue time, cache hit rate, and batch size, with unified log and metric collection for troubleshooting.
    • Cloud Building Blocks: run the stateless inference layer on a container platform with autoscaling, store model weights and datasets in object storage, use a message queue to buffer asynchronous workloads, and close the loop with logging services and monitoring alerts.

    6. Three Common Pitfalls

    1. Only looking at tokens/s: ignoring first-token latency means users still perceive the system as slow.
    2. Averages instead of percentiles: P99 is the true picture of the long-tail user experience.
    3. Blindly increasing batch size: throughput goes up, but latency SLOs are blown and the overall system ends up more expensive.

    7. Summary

    “Fast” is not a single switch—it is a systems engineering effort spanning metric definition, request scheduling, cache reuse, decoding algorithms, and elastic architecture. Start by measuring TTFT and TPOT percentiles accurately, then apply continuous batching, chunked prefill, prefix caching, and speculative decoding against the identified bottlenecks, and finally use tiered SLOs and degradation paths to contain the long tail. Only then can you reach a sustainable balance among cost, quality, and speed.