FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Latency and Throughput

How queueing prompt processing generation batching and concurrency determine serving performance.

Freshness: current•15 min read•Foundation Models and Multimodal AI

Key Learning Outcomes

  • ✓Decompose response latency
  • ✓Distinguish latency and throughput
  • ✓Identify optimization levers
Isometric Diagram LabSystem Design · 10 steps · 10 min

Latency vs. Throughput & Tail Amplification

Step through p50/p99 queueing curves, Little's Law saturation, and hedged fan-out latency in 2:1 isometric diagrams.

Open Isometric Walkthrough
Full Technical Reference Document

Mental model

Latency measures wall-clock waiting time experienced by a single user request (TTFT plus sequential decode duration), whereas throughput measures total aggregate tokens or requests completed across a GPU fleet per second. Because increasing concurrent batch size raises Tensor Core utilization while adding queue wait and memory-bus contention per active stream, tuning purely for peak cluster throughput directly degrades interactive tail latency.

Ingress queue wait
Prefill GEMM (TTFT)
KV prefix reuse
Continuous batch decode (TPOT)
Tool I/O & SSE flush
Conceptual teaching model synthesized from:Latency OptimizationEfficient Memory Management for Large Language Model Serving with PagedAttention

Learning outcomes

  • Decompose end-to-end LLM wall-clock response time into queueing, prefill (TTFT), decode (TPOT), and upstream tool round-trips.
  • Apply hardware Roofline bounds to distinguish compute-bound prefill bottlenecks from HBM memory-bandwidth-bound autoregressive decode.
  • Configure batching concurrency, prefix caching, and concise schema budgets to meet strict P95 and P99 user SLAs simultaneously.

Theory

Serving modern transformers crosses two sharply contrasting hardware regimes within every single request lifecycle:

Serving MetricDefinition & UnitsPrimary Hardware BottleneckHigh-Leverage Engineering Lever
Queue Time (TqueueT_{\text{queue}})Ingress arrival until scheduler batch admission (ms)Active request saturation (max_num_seqs) & head-of-line prefillsPriority fairness queues, chunked prefill, horizontal autoscale
Time to First Token (TTFT)Admission through first emitted token (ms)Compute FLOPs (Prefill GEMM scaling quadratically with cache misses)KV prefix caching, prompt trimming, tensor parallelism (TP)
Time Per Output Token (TPOT)Inter-token interval during generation (ms/tok)HBM memory bandwidth reading full model weights + KV cache per stepFP8/INT4 weight quantization, GQA compression, speculative decoding
Total Task P95 LatencyEnd-to-end completion including tools & retries (s)Generated output token count (NoutN_{\text{out}}) & sequential tool loopsShorter structured output schemas, parallel tool fan-out, early stop

During prefill, thousands of input prompt tokens multiply weights across matrix-matrix (GEMM) operations at high arithmetic intensity, saturating Tensor Core FLOPs cleanly. During autoregressive decode, each running sequence produces just one next token per forward step, reading gigabytes of model weights and KV tensors from GPU HBM per token generated. Continuous (iteration-level) batching lets newly arrived requests swap into vacated slots immediately on any token step rather than waiting for the longest batch sequence to hit end-of-sequence, dramatically lifting throughput—yet pushing concurrent active requests past the GPU memory-bandwidth saturation knee stretches TPOT upward across every connected stream.

python
from dataclasses import dataclass
​
@dataclass(frozen=True)
class ServingProfile:
model_weights_gb: float
kv_gb_per_active_req: float
gpu_hbm_bw_gb_s: float
prefill_tps: float
​
def estimate_request_latency_ms(
profile: ServingProfile,
prompt_tokens: int,
output_tokens: int,
concurrent_batch: int,
cached_prefix_tokens: int = 0,
) -> dict[str, float]:
"""First-order analytical estimator separating prefill TTFT vs bandwidth-bound decode."""
uncached_prompt = max(1, prompt_tokens - cached_prefix_tokens)
ttft_ms = (uncached_prompt / profile.prefill_tps) * 1000.0
​
# Each decode iteration streams all weights plus active KV rows once across concurrent_batch tokens
bytes_read_gb = profile.model_weights_gb + (concurrent_batch * profile.kv_gb_per_active_req)
step_time_ms = (bytes_read_gb / profile.gpu_hbm_bw_gb_s) * 1000.0 * 1.15 # 15% kernel launch margin
tpot_ms = step_time_ms
total_ms = ttft_ms + (max(0, output_tokens - 1) * tpot_ms)
cluster_decode_tps = (concurrent_batch / step_time_ms) * 1000.0
return {
"ttft_ms": round(ttft_ms, 1),
"tpot_ms": round(tpot_ms, 1),
"total_ms": round(total_ms, 1),
"cluster_decode_tps": round(cluster_decode_tps, 1),
}

Trade-offs

Aggressive continuous batching and maximum KV-cache packing minimize unit dollar cost per million generated tokens cleanly on offline ETL pipelines, batch summarization, and synthetic data generation where individual request latency matters little as long as aggregate hourly completion remains high. Interactive chat assistants, code editors, and voice agents invert that priority: users notice delays past 500 ms TTFT or stuttering TPOT > 40 ms immediately, demanding capped concurrency headroom, smaller/quantized checkpoints, speculative drafting, and strict verbose-prose limits even at higher per-token hardware cost. Mixing multi-tenant long-context batch jobs onto the exact same worker pool as interactive streams causes severe queue jitter unless workloads isolate across separate queues or employ fine-grained Chunked Prefill interleaving.

Failure modes and misconceptions

  • Tracking Only Mean Latency: Reporting average latency hides catastrophic P95/P99 stalls experienced whenever long 64K prompts monopolize workers or trigger KV-cache preemption swaps.
  • Over-Tuning Model Speed While Tools Stall: Cutting TPOT by 20 ms saves little when unparallelized upstream vector database calls and sequential API tools burn 3.5 seconds on the critical path.
  • Unbounded Client Retries Under Overload: Retrying timed-out LLM generations automatically without exponential backoff or server circuit breakers triggers catastrophic queue collapse (goodput -> 0).
  • Ignoring Output Length Multipliers: Swapping to a model 2x slower per token hurts less than silently allowing system prompts to emit 600 verbose filler words instead of 120 focused tokens.

Decision scenario

An enterprise SaaS copilot suffers severe P99 completion spikes above 9 seconds during peak morning hours while average cluster GPU utilization stays around 55%. Telemetry shows mixing 32K batch document uploads with 800-token interactive chat sessions without Chunked Prefill or token caps. Propose queue isolation, prefix cache locking, and output length controls balancing cost cleanly against interactive responsiveness.

Reflect before revealing the guide

Why can increasing serving batch size improve cluster throughput while making individual request P95 latency slower?

Prerequisites & Related Concepts (3)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.