Education › OSS Deep Dives › Stage 4: LLM inference infrastructure

vLLM: high-throughput LLM serving

PagedAttention, continuous batching, the OpenAI-compatible server, parallelism, quantization and the metrics that matter.

Advanced ~35 min read Module 8 of 10

vLLM is the open-source inference engine most teams reach for when they self-host open-weight language models. It began as the research code behind PagedAttention and is now a large community project in vllm-project/vllm. This lesson explains why LLM serving is a memory-management problem, how vLLM's scheduler keeps GPUs busy, how to run its OpenAI-compatible server, which flags actually change throughput and latency, how to spread a model across GPUs, and which metrics tell you it is healthy.

After this module you can
  • Explain the KV cache, PagedAttention and continuous batching, and why they raise throughput
  • Start the OpenAI-compatible server and call it with any OpenAI-style client
  • Tune memory, batching and context-length flags against latency and throughput goals
  • Choose tensor, pipeline or data parallelism for a model and a GPU budget
  • Monitor vLLM with its Prometheus metrics and recognise preemption and queueing

Why LLM serving is a memory problem

Generating text happens in two phases. Prefill processes the whole prompt in one pass and is compute-bound. Decode then produces one token per step for every active request and is memory-bandwidth-bound. To avoid recomputing the prompt at every step, the model keeps each layer's attention keys and values for every token so far: the KV cache. It grows with every token of every concurrent request, and it, not the model weights, usually decides how many requests fit on a GPU.

Per token, the cache holds 2 (keys and values) times layers times KV heads times head dimension times bytes per value. For a model with 32 layers, 8 KV heads of dimension 128 in 16-bit precision, that is 2 x 32 x 8 x 128 x 2 = 131,072 bytes, 128 KiB per token. One 8,192-token conversation therefore needs 1 GiB of KV cache on top of the weights.

Older servers reserved one contiguous slab per request sized for the maximum length, wasting most of it. PagedAttention, vLLM's founding idea, stores the cache in small fixed-size blocks, like virtual-memory pages, allocated on demand and shareable between requests. Little memory is wasted, so many more requests fit, and requests that share a prefix (a long system prompt, a few-shot template) can share the same blocks. That is prefix caching, enabled by default.

requestsadmitbatchread, appendallocate blockspreemptClientsOpenAI APIWaiting queuenum_requests_waitingSchedulerbatch every stepModel runnerprefill + decodePaged KV cacheblocks, shared prefix
vLLM's scheduler re-forms the batch at every step, and PagedAttention hands each request KV-cache blocks on demand, so shared prefixes reuse blocks and memory runs out late instead of early.

The scheduler adds continuous batching: instead of waiting for a whole batch to finish, it adds new requests and retires finished ones at every decode step, so the GPU never idles while one long answer completes. Chunked prefill, on by default, splits long prompts into pieces and mixes them with decode steps, so one huge prompt does not stall everyone else's token stream.

Running the OpenAI-compatible server

Install with uv pip install vllm (or pip) on a machine with a supported GPU, or use the official container image. vllm serve downloads weights from the Hugging Face Hub (or loads a local path) and exposes an HTTP server on port 8000 that speaks the OpenAI API, including chat completions, completions, embeddings and tool calling, so existing clients and frameworks work by changing the base URL.

Serve a model on one GPU with an API key and a friendly name
bash
export MODEL_ID=YOUR_ORG/YOUR_MODEL
export VLLM_API_KEY=CHANGE_ME

vllm serve "$MODEL_ID" \
  --served-model-name chat \
  --max-model-len 16384 \
  --gpu-memory-utilization 0.90 \
  --api-key "$VLLM_API_KEY"
Call it like any OpenAI-compatible endpoint
bash
curl -s http://localhost:8000/v1/chat/completions \
  -H "Authorization: Bearer $VLLM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "chat", "messages": [{"role": "user", "content": "Say hi"}]}'

Other useful endpoints: /v1/models lists what is served, /health is a liveness check for Kubernetes probes, and /metrics exposes Prometheus metrics. For offline batch jobs, skip the server and use the LLM class in Python, which runs the same engine over a list of prompts.

Watch out

Startup takes minutes for large models: downloading weights, loading them to GPU, compiling and capturing CUDA graphs. Give the readiness probe a long initial delay, cache weights on a persistent volume, and keep the compile cache (under ~/.cache/vllm by default) between restarts.

The flags that matter

FlagDefaultWhat it trades
--gpu-memory-utilization0.92Share of GPU memory vLLM may use; the rest after weights becomes KV cache
--max-model-lenfrom model configLongest prompt plus output allowed; lowering it frees KV cache
--max-num-seqsset by vLLMMaximum requests decoded together: concurrency versus per-request speed
--max-num-batched-tokensset by vLLMTokens per scheduler step; higher favours throughput, lower favours latency
--quantization, --kv-cache-dtypeoff / autoSmaller weights or cache (for example FP8) for more room, with some accuracy risk
--enable-lora, --max-lorasoffServe many fine-tuned adapters on one base model

When demand exceeds KV cache space, vLLM preempts requests: it evicts their cache and recomputes it later, which shows up as latency spikes and a rising preemption counter. The documented fixes are more cache (raise memory utilisation, add GPUs with tensor parallelism, quantize the cache) or less concurrency (lower --max-num-seqs or --max-num-batched-tokens). The docs suggest --max-num-batched-tokens above 8192 for throughput, especially for smaller models on large GPUs.

Benchmark instead of guessing: vllm bench serve replays a synthetic or recorded workload against a running server and reports throughput, time to first token and time per output token, so you can compare flag settings on your own prompt and output lengths.

Bigger than one GPU

  • Tensor parallelism (--tensor-parallel-size N) splits every layer across N GPUs in one node. Use it when the model does not fit on one GPU; it needs fast interconnect such as NVLink.
  • Pipeline parallelism (--pipeline-parallel-size N) puts different layers on different GPUs or nodes. Use it, usually combined with tensor parallelism, when a model spans nodes.
  • Data parallelism (--data-parallel-size N) runs N full copies for more throughput; for dense models, separate replicas behind a load balancer do the same job.
  • Expert parallelism spreads the experts of mixture-of-experts models across GPUs.

Beyond one engine, the ecosystem adds routing and scheduling: vLLM's production stack Helm chart, KServe with a vLLM runtime, llm-d, and NVIDIA Dynamo (next lessons) all run vLLM engines underneath while adding prefix-cache-aware routing and, in some cases, disaggregated prefill and decode on separate GPUs.

Watching it in production

The /metrics endpoint exposes Prometheus series prefixed vllm: with model_name and engine labels. A useful first dashboard needs only a few:

MetricTypeTells you
vllm:num_requests_running / vllm:num_requests_waitinggaugeLoad, and whether a queue is forming
vllm:kv_cache_usage_percgaugeHow full the KV cache is; near 1 means preemption ahead
vllm:time_to_first_token_secondshistogramResponsiveness as users feel it
vllm:inter_token_latency_secondshistogramStreaming speed once tokens flow
vllm:num_preemptions_totalcounterRequests evicted for lack of cache space
vllm:prompt_tokens_total / vllm:generation_tokens_totalcounterToken throughput, the basis of cost

Autoscale on queued requests, for example with KEDA's Prometheus trigger on vllm:num_requests_waiting, not on GPU utilisation, which is high whenever any work is running. Alert on time-to-first-token SLOs and on a rising preemption rate.

Hands-on practice

Measure what the flags do

  1. On a machine with one GPU (a cloud instance or a free notebook GPU), install vLLM and start vllm serve with a small open-weight model and --max-model-len 4096.
  2. Send a chat request with curl, then point an OpenAI-style client at http://localhost:8000/v1 and confirm it works unchanged.
  3. Open http://localhost:8000/metrics and find the running, waiting and KV cache usage series.
  4. Run vllm bench serve against the server with a fixed request rate and record throughput and p95 time to first token.
  5. Restart with --max-num-seqs 8 and rerun the benchmark; then try a larger value and compare both numbers.
  6. Send many long prompts at once and watch vllm:num_preemptions_total and vllm:kv_cache_usage_perc; lower --gpu-memory-utilization to 0.6 and observe preemptions increase.
  7. Shut the instance down when finished so it stops costing money.
Cheat sheet

vLLM: high-throughput LLM serving — at a glance

Main things to focus on

  • The KV cache, not the weights, usually limits how many requests fit on a GPU.
  • PagedAttention stores the cache in shareable blocks; prefix caching reuses shared prompt prefixes.
  • Continuous batching and chunked prefill keep the GPU busy without stalling streams.
  • Preemption means not enough KV cache: add memory or reduce concurrency.
  • Tensor parallelism to fit a model; data parallelism or replicas for throughput.
  • Scale on waiting requests, alert on time to first token and preemptions.

Run and call

uv pip install vllmInstall (or use the official container image)
vllm serve MODEL --served-model-name NAMEOpenAI-compatible server on :8000
--api-key KEYRequire a bearer token on API calls
POST /v1/chat/completionsChat endpoint; also /v1/completions, /v1/embeddings
GET /health /metrics /v1/modelsProbe, Prometheus metrics, served models
vllm bench serveBenchmark a running server

Capacity flags

--gpu-memory-utilization 0.92Default share of GPU memory vLLM claims
--max-model-len NCap context length to free cache
--max-num-seqs NCap concurrent sequences
--max-num-batched-tokens NTokens per scheduler step
--kv-cache-dtype fp8Halve KV cache memory on supported GPUs

Parallelism

--tensor-parallel-size NSplit each layer across N GPUs in a node
--pipeline-parallel-size NSplit layers into N stages, across nodes
--data-parallel-size NN engine replicas for throughput

Formulas

KV bytes/token = 2 x layers x kv_heads x head_dim x bytesSize the cache per token
concurrent requests ~ KV cache memory / (KV bytes/token x avg tokens)Rough concurrency estimate
TTFT ~ queue wait + prefill timeWhy queues hurt first-token latency

Common pitfalls

  • Setting --max-model-len to the model's maximum when real requests are short, starving the KV cache.
  • Autoscaling on GPU utilisation, which is high as soon as anything runs.
  • Readiness probes that fail during the minutes-long model load, causing restart loops.
  • Exposing the server without --api-key or an authenticating gateway in front.
  • Comparing configurations by feel instead of with vllm bench serve on realistic prompt lengths.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →