Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Artificial Intelligence
14 min read

LLM Service Load Testing Handbook: TTFT, TPOT & Throughput Metrics with Concurrency Bottleneck Analysis

This comprehensive guide defines standardized metrics (TTFT, TPOT, ITL, throughput) for LLM serving, provides step-by-step vLLM benchmarking procedures including concurrency ladder testing, server-side metric correlation, and a bottleneck decision table to distinguish queueing, KV cache pressure, compute saturation, and preemption issues.

1. Production Pain Points & Business Scenarios

A team deployed a 7B dialogue model with vLLM. Single-GPU testing showed 1.2s average latency, so they scaled to 200 concurrent users. Two issues emerged:

First token appeared after 6-10 seconds, though subsequent output speed was acceptable.

During peak hours, output became choppy; GPU utilization neared 100%, but doubling instances barely helped.

Root cause: load testing only measured average end-to-end latency, ignoring first-token vs per-token latency separation and the concurrency knee point.

2. Core Principles & Architecture

2.1 Request Lifecycle Phases

A streaming request splits into three phases with distinct resource profiles:

Queue : Wait for scheduler slot. Main bottleneck: concurrency exceeds engine parallelism. Metric: counted in TTFT.

Prefill : Process all input tokens at once. Main bottleneck: compute-bound. Metric: TTFT.

Decode : Generate tokens one by one. Main bottleneck: memory-bandwidth bound. Metric: TPOT, ITL.

Key insight: High TTFT → suspect queueing or Prefill; high TPOT → suspect Decode batch size or KV cache pressure. Analyze separately.

2.2 Metric Definitions

TTFT (Time to First Token): Request sent to first output token received. Unit: ms. Includes queue, network, Prefill.

TPOT (Time per Output Token): (E2E latency - TTFT) / (output tokens - 1). Unit: ms/token. Excludes first token; average measure.

ITL (Inter-Token Latency): Interval between adjacent output tokens. Unit: ms. P99 reveals stalls.

E2E Latency : Request sent to last token returned. Unit: ms. Grows linearly with output length.

Output Throughput : Output tokens generated per second. Unit: tok/s. Core capacity planning metric.

Total Throughput : Input + output tokens per second. Unit: tok/s. Meaningful only for long inputs.

Pitfall: TPOT is an average and masks individual token pauses. For UX-sensitive scenarios, always check ITL P99.

2.3 Concurrency vs Throughput (Little's Law)

Little's Law: Concurrent requests = Request throughput (req/s) × Average E2E latency (s). At low concurrency, adding concurrency linearly increases throughput. Beyond a knee point, throughput plateaus while latency keeps rising. Finding this knee is the core task of load testing.

2.4 KV Cache Capacity Model

Each live request in Decode holds KV cache. Exhaustion triggers preemption (swap-out + recompute), causing latency spikes.

Per-token KV cache size:

2 × layers × KV heads × head dimension × dtype bytes

Example (verify with actual config.json): 7B model, 28 layers, 4 KV heads, head dim 128, BF16 → ~57 KB/token. Single 80 GB GPU, gpu-memory-utilization=0.90, after ~15 GB weights/activations → ~50 GB for KV cache → ~800K tokens. With avg 1280 tokens/request (1024 in + 256 out), theoretical max ~600 live requests. Actual lower due to fragmentation; trust engine startup logs.

3. Experimental Baseline & Prerequisites

OS : Ubuntu 22.04 LTS, kernel ≥5.15

GPU : 1× NVIDIA datacenter GPU, ≥24 GB VRAM

Driver/CUDA : Match vLLM release CUDA requirement

Inference Engine : vLLM ≥0.8 (uses vllm bench serve)

Python : 3.10–3.12

Load Generator : Same subnet, ≥4 vCPU, separate from GPU node

Version note: Older vLLM lacks vllm bench serve; use benchmarks/benchmark_serving.py from source. Prometheus metric names differ across versions; see Section 4.

Pre-check commands:

nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv
python3 -c "import vllm; print(vllm.__version__)"
vllm bench serve --help | head -n 5

Expected output shows GPU name, driver, VRAM (for KV cache estimation), vLLM version, and bench command availability.

4. Standardized Deployment & Core Practice

Step 1: Start Service Under Test

Launch with explicit, reproducible parameters; all conclusions bind to this config.

vllm serve <MODEL_PATH> \
  --served-model-name <SERVED_MODEL_NAME> \
  --host 0.0.0.0 --port 8000 \
  --max-model-len 4096 \
  --gpu-memory-utilization 0.90 \
  --max-num-seqs 256 \
  --max-num-batched-tokens 8192

Four key parameters: --max-model-len: Default/Rec: Model config / business max context. Mechanism: Caps per-request tokens, sets KV cache reservation ceiling. Misconfig impact: Too large → concurrency drops; too small → long requests rejected. --gpu-memory-utilization: Default/Rec: 0.9 / 0.85–0.92. Mechanism: Fraction of VRAM engine may use; rest for overhead. Misconfig impact: Too high → OOM on startup/long context; too low → less KV cache. --max-num-seqs: Default/Rec: Varies / tune via knee point. Mechanism: Max parallel requests per scheduling step. Misconfig impact: Too large → TPOT degrades; too small → throughput low, queue grows. --max-num-batched-tokens: Default/Rec: Varies / 4096–16384. Mechanism: Token budget per step, mixes Prefill & Decode. Misconfig impact: Too large → long Prefill blocks Decode, ITL jitter; too small → TTFT rises.

Defaults vary by version/hardware; verify with vllm serve --help. Newer versions enable chunked prefill by default; older need --enable-chunked-prefill.

Expected startup logs (key lines):

INFO ... # GPU KV cache size: 812,345 tokens        # Record for §2.4 capacity estimate
INFO ... # Maximum concurrency for 4,096 tokens per request: 198.3x  # Theoretical concurrency ceiling
INFO ... Application startup complete.            # Service ready

Log wording varies; locate lines containing “KV cache” and “concurrency”. If KV cache far below expectation, check for other processes consuming VRAM.

Step 2: Verify Test Path & Avoid Measurement Distortion

Every proxy layer adds potential distortion.

First test straight to engine for engine baseline, then via gateway for full-path baseline; delta = gateway overhead.

Must use streaming requests; non-streaming cannot measure TTFT.

If Nginx proxies, disable response buffering and raise read timeout, else TTFT inflated by buffering.

location /v1/ {
  proxy_pass http://<VLLM_UPSTREAM>;
  proxy_http_version 1.1;
  proxy_set_header Connection "";
  proxy_buffering off;
  proxy_read_timeout 300s;
}
proxy_buffering off

forwards tokens immediately; buffering on makes Nginx accumulate before sending. proxy_read_timeout must exceed longest generation time or long outputs get cut.

Step 3: Warm-up & Single-Point Baseline

First request incurs CUDA graph capture, cache init; skipping warm-up pollutes data.

vllm bench serve \
  --backend vllm \
  --host <VLLM_HOST> --port 8000 \
  --model <SERVED_MODEL_NAME> \
  --dataset-name random \
  --random-input-len 1024 --random-output-len 256 \
  --num-prompts 50 \
  --max-concurrency 4 \
  --ignore-eos

Parameter rationale: --dataset-name random: Random token sequences avoid prefix cache hits. If omitted: Repeated text hits cache → artificially low TTFT. --random-input-len / --random-output-len: Fixed input/output lengths. If omitted: Variable lengths make multi-run comparison impossible. --max-concurrency: Limits client-side in-flight requests. If omitted: All requests fire at once = extreme concurrency. --ignore-eos: Ignores EOS, forces generation to exact length. If omitted: Random output lengths distort throughput.

If --served-model-name differs from real model path, client tokenizer load fails; add --tokenizer <MODEL_PATH> (behavior version-dependent).

Expected output (simulated):

============ Serving Benchmark Result ============
Successful requests:              50          # Must equal num-prompts; else failures exist
Benchmark duration (s):           18.64
Total input tokens:               51200
Total generated tokens:           12800
Request throughput (req/s):       2.68
Output token throughput (tok/s):  686.7       # Capacity planning uses this
Total Token throughput (tok/s):   3433.4
---------------Time to First Token----------------
Mean TTFT (ms):                   96.2
Median TTFT (ms):                 91.0
P99 TTFT (ms):                    148.5       # Low concurrency ≈ pure Prefill time
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                   5.9         # Low-concurrency Decode speed floor
Median TPOT (ms):                 5.8
P99 TPOT (ms):                    7.2
==================================================

Readouts: Concurrency=4 gives “no queue, no congestion” ideal baseline; all ladder results compare against it. Successful requests < total → investigate errors first.

Step 4: Concurrency Ladder Test

Increasing concurrency to plot throughput/latency curves and locate knee.

#!/usr/bin/env bash
set -euo pipefail

HOST=<VLLM_HOST>
PORT=8000
MODEL=<SERVED_MODEL_NAME>
mkdir -p results

for C in 1 2 4 8 16 32 64 128 256; do
  N=$(( C * 10 ))
  [ "$N" -lt 50 ] && N=50
  vllm bench serve \
    --backend vllm \
    --host "$HOST" --port "$PORT" \
    --model "$MODEL" \
    --dataset-name random \
    --random-input-len 1024 --random-output-len 256 \
    --num-prompts "$N" \
    --max-concurrency "$C" \
    --ignore-eos \
    --percentile-metrics ttft,tpot,itl,e2el \
    --metric-percentiles 50,95,99 \
    --save-result --result-dir results \
    --result-filename "c${C}.json"
  sleep 10
done

Key points:

Requests per tier = 10× concurrency (min 50) for steady-state dominance. sleep 10 drains queues/caches between tiers.

Each tier repeat ≥3 times, take median for formal acceptance.

Step 5: Aggregate Results

First confirm JSON fields (names vary by version): jq 'keys' results/c1.json | head -n 40 Aggregation script:

printf "conc\treq/s\tout_tok/s\tttft_p50\tttft_p99\ttpot_p50\ttpot_p99
"
for C in 1 2 4 8 16 32 64 128 256; do
  jq -r --arg c "$C" '[$c, .request_throughput, .output_throughput,
    .median_ttft_ms, .p99_ttft_ms, .median_tpot_ms, .p99_tpot_ms] | @tsv' \
    "results/c${C}.json"
done

Field names like p99_ttft_ms depend on --metric-percentiles. null output means name mismatch; re-check keys.

Simulated aggregate (with commentary):

conc  req/s  out_tok/s  ttft_p50  ttft_p99  tpot_p50  tpot_p99
1     0.88   225        62        88        4.4       5.1
8     5.9    1510       110       210       5.2       7.0
32    14.8   3790       260       690       8.1       12.5
64    19.6   5020       520       1480      11.9      19.8   # Throughput growth slows, TTFT rises sharply
128   21.3   5450       2350      6900      20.4      34.0   # Throughput plateaus, TTFT ×4+, entering queue
256   21.6   5530       7800      15200     21.1      36.2   # Throughput flat, latency pure increase, past knee

Knee interpretation:

Between 64–128 concurrency: throughput +8%, TTFT P99 ×4+ → knee here.

Beyond 128: throughput stalls, TTFT keeps climbing → requests queueing, not processing.

Usable concurrency ceiling = highest pre-knee tier meeting SLO, with headroom.

Step 6: Simultaneous Server-Side Metric Collection

Client sees “slow”; server metrics explain “why”.

Collect every second during test:

while true; do
  date +%T
  curl -s http://<VLLM_HOST>:8000/metrics | \
    grep -E '^vllm:(num_requests_running|num_requests_waiting|gpu_cache_usage_perc|kv_cache_usage_perc|num_preemptions_total)'
  sleep 1
done | tee metrics_during_bench.log

Simultaneously on GPU node:

nvidia-smi --query-gpu=timestamp,utilization.gpu,memory.used,power.draw \
  --format=csv -l 1 | tee gpu_during_bench.csv

Metric meanings: num_requests_running: Requests currently executing. Anomaly: Long-term equals max-num-seqs → execution slots saturated. num_requests_waiting: Requests queued. Anomaly: Persistently >0 → engine can't keep up. gpu_cache_usage_perc / kv_cache_usage_perc: KV cache utilization. Anomaly: Near 1.0 → VRAM capacity tight. num_preemptions_total: Cumulative preemptions. Anomaly: Rising during test → swap-out/recompute occurring.

Version note: KV cache metric renamed to kv_cache_usage_perc in newer versions; token-interval histograms also renamed. Verify against actual /metrics output.

Expected output (annotated):

10:21:08
vllm:num_requests_running 256.0         # Hit max-num-seqs
vllm:num_requests_waiting 74.0          # Queue present → direct cause of TTFT rise
vllm:gpu_cache_usage_perc 0.62          # KV cache has headroom → bottleneck not VRAM capacity
vllm:num_preemptions_total 0.0          # No preemption

5. Functional Verification & Acceptance

5.1 Bottleneck Decision Table

Combine client curves with server metrics:

Symptom: TTFT up, TPOT stable | Server Evidence: waiting >0, cache usage low | Diagnosis: Insufficient parallelism, queueing | Adjustment: Increase max-num-seqs or add instances

Symptom: TTFT & TPOT both up | Server Evidence: running saturated, GPU util high | Diagnosis: Compute or bandwidth saturated | Adjustment: Quantize, add GPUs, scale out

Symptom: Throughput flat, latency jitter | Server Evidence: Cache usage ~1.0, preemptions rising | Diagnosis: KV cache insufficient | Adjustment: Reduce max-model-len, enable KV cache quantization, add VRAM

Symptom: Individual ITL spikes | Server Evidence: Long-input requests mixed in | Diagnosis: Long Prefill blocks Decode | Adjustment: Enable chunked prefill, reduce max-num-batched-tokens Symptom: Low throughput, low GPU util | Server Evidence: running & waiting both small | Diagnosis: Load generator or path is bottleneck | Adjustment: Check load generator CPU, gateway, network

5.2 Acceptance Criteria Example

Criteria must derive from business SLOs; below is illustrative:

TTFT P99 : ≤ 2000 ms | Measurement Condition: Input 1024, target concurrency

TPOT P99 : ≤ 50 ms | Measurement Condition: Output 256

Request Success Rate : ≥ 99.9% | Measurement Condition: Steady 30 min run

Output Throughput : ≥ 1.3× target | Measurement Condition: Capacity headroom

Steady-state validation: Run at target concurrency ≥30 min; watch for metric drift, memory growth, preemption accumulation.

Target concurrency command:

vllm bench serve \
  --backend vllm \
  --host <VLLM_HOST> --port 8000 \
  --model <SERVED_MODEL_NAME> \
  --dataset-name random \
  --random-input-len 1024 --random-output-len 256 \
  --num-prompts 3000 \
  --max-concurrency <TARGET_CONCURRENCY> \
  --ignore-eos \
  --percentile-metrics ttft,tpot,itl,e2el \
  --metric-percentiles 50,95,99 \
  --save-result --result-dir results \
  --result-filename steady.json
<TARGET_CONCURRENCY>

= max SLO-meeting pre-knee concurrency × 0.7–0.8 safety factor.

5.3 Multi-Scenario Coverage

Single 1024-in/256-out profile insufficient. Add at least:

Short input, long output (writing, code gen): Decode-dominated → focus TPOT & output throughput.

Long input, short output (doc QA, summarization): Prefill-dominated → focus TTFT.

Real traffic replay : Extract input/output length distributions from production logs; test with real dataset for highest confidence.

6. Production Pitfalls & Troubleshooting

Pitfall 1: Benchmark Numbers Much Better Than Production

Symptom: Bench TTFT P99 300 ms; production same concurrency >3 s.

Root-cause commands:

curl -s http://<VLLM_HOST>:8000/metrics | grep -i prefix_cache
vllm bench serve --help | grep -E "dataset-name|random"

Fix:

Check if benchmark used repeated text → prefix cache hits → artificially low Prefill time.

Switch to --dataset-name random or real traffic replay.

If production genuinely has heavy shared prefixes, evaluate prefix cache benefit separately and report apart from no-cache baseline.

Pitfall 2: High Concurrency Causes Mass Failures/Timeouts

Symptom: Successful requests < total; client logs show Connection reset, HTTP 502/504.

Root-cause commands:

journalctl -u <VLLM_SERVICE> --since "10 min ago" | grep -iE "error|exception|abort"
tail -n 50 /var/log/nginx/error.log
ss -s

Fix:

Failure at gateway → check gateway proxy_read_timeout, connection limits, buffering (see §4 Step 2).

Failure at engine → check CUDA OOM; lower --gpu-memory-utilization or --max-model-len.

Fix failures first, then compare performance; failed requests distort throughput.

Pitfall 3: Severe Latency Jitter at Throughput Plateau

Symptom: TPOT P99 periodically spikes; GPU util normal; client sees occasional long pauses.

Root-cause commands:

curl -s http://<VLLM_HOST>:8000/metrics | grep -E "num_preemptions_total|cache_usage_perc"
journalctl -u <VLLM_SERVICE> | grep -i preempt

Fix:

Rising preemption count → KV cache exhaustion.

Reduce --max-model-len or --max-num-seqs to cut live sequences.

Enable KV cache quantization (e.g., --kv-cache-dtype fp8 if hardware/version supports), or add GPUs / use tensor parallelism.

Some versions log preemption warnings with suggested tuning; follow actual logs.

Pitfall 4: Throughput Stalls While GPU Utilization Low

Symptom: Output throughput caps at low concurrency; nvidia-smi shows 40–60% GPU util; num_requests_running ≪ max-num-seqs.

Root-cause commands:

top -b -n 1 | head -n 15
mpstat -P ALL 1 3

Fix:

Load generator CPU saturated → request send/stream parse slows → “server idle, client busy”.

Use multiple load generators or multi-process parallel runs, each with capped concurrency, then merge results.

Load generator should be dedicated, same subnet, not competing for CPU with GPU node.

Pitfall 5: High Variance Across Repeated Runs

Symptom: Two runs differ >20% in output throughput; non-reproducible.

Root-cause commands:

jq '.output_lens | (add / length)' results/c32.json
nvidia-smi --query-gpu=clocks.sm,clocks.max.sm,temperature.gpu --format=csv

Fix:

Inconsistent output lengths → add --ignore-eos to fix length.

Insufficient warm-up → run one warm-up round, discard first data.

GPU throttling/overheating → check cooling, power limits; lock clocks if needed; note in report.

Repeat each tier ≥3 times; use median for conclusion.

7. Production Launch Checklist

Unified Definitions: Report explicitly defines TTFT, TPOT, ITL with percentiles; includes full benchmark command & parameters.

Version Binding: Record engine version, driver version, model version, startup params; any param change requires re-test.

Knee & Headroom: Target concurrency = max pre-knee SLO-meeting tier; reserve 20–30% headroom.

Steady-State Validation: Run target concurrency ≥30 min; no errors, no preemption accumulation, no VRAM growth.

Monitoring & Alerts: Collect num_requests_waiting, KV cache usage, preemption count, TTFT/TPOT histograms; alert on queueing & preemption.

Rate Limiting & Degradation: Gateway enforces limit at knee concurrency; excess requests fast-fail to prevent unbounded queue growth wrecking TTFT.

Log Persistence: Archive raw benchmark JSON + server metric logs for post-mortem & version comparison.

Rollback Plan: Before engine upgrade, param change, or model swap, retain prior image & params; run same benchmark script for regression comparison.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Write a comment

Sign in to join the discussion

No public comments on this page. Sign in to comment