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.
- 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.
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.
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"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.
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
| Flag | Default | What it trades |
|---|---|---|
--gpu-memory-utilization | 0.92 | Share of GPU memory vLLM may use; the rest after weights becomes KV cache |
--max-model-len | from model config | Longest prompt plus output allowed; lowering it frees KV cache |
--max-num-seqs | set by vLLM | Maximum requests decoded together: concurrency versus per-request speed |
--max-num-batched-tokens | set by vLLM | Tokens per scheduler step; higher favours throughput, lower favours latency |
--quantization, --kv-cache-dtype | off / auto | Smaller weights or cache (for example FP8) for more room, with some accuracy risk |
--enable-lora, --max-loras | off | Serve 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:
| Metric | Type | Tells you |
|---|---|---|
vllm:num_requests_running / vllm:num_requests_waiting | gauge | Load, and whether a queue is forming |
vllm:kv_cache_usage_perc | gauge | How full the KV cache is; near 1 means preemption ahead |
vllm:time_to_first_token_seconds | histogram | Responsiveness as users feel it |
vllm:inter_token_latency_seconds | histogram | Streaming speed once tokens flow |
vllm:num_preemptions_total | counter | Requests evicted for lack of cache space |
vllm:prompt_tokens_total / vllm:generation_tokens_total | counter | Token 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.