vLLM Tutorial: High-Throughput Serving and Batching

Updated 3 min read

Serving open-weight large language models often triggers out-of-memory errors and sluggish batch throughput. This guide is built for engineers and backend developers who need to deploy performant inference services without unpredictable memory stalls. Following this walkthrough will give you both high-throughput offline batching and an active inference server on Linux.

Watch the video on YouTube

Before you start

  • Linux system (Ubuntu 22.04 or 24.04 recommended)
  • NVIDIA GPU with compute capability 7.0 or higher (Turing architecture or newer)
  • CUDA 12.1 or newer installed with operational NVIDIA drivers
  • Python 3.12 and curl installed

Understanding PagedAttention and Continuous Batching

Traditional serving tools pre-allocate contiguous chunks of memory for the key-value cache of each sequence. Because output lengths vary wildly, this structure wastes substantial memory through fragmentation. PagedAttention solves this bottleneck by managing key-value memory in non-contiguous blocks, mirroring the paging design of operating system virtual memory.

Continuous batching works alongside this memory structure by dynamically scheduling requests at the individual token level. Instead of waiting for an entire batch of requests to reach completion, the engine injects new queries into available slots on each iteration. Recent architectural updates introduce an extensible cache that sizes memory dynamically once initial model warmup completes.

Preparing the Python Environment with uv

Setting up an isolated runtime avoids conflicting dependencies across system packages. The recommended package manager uv handles Python binaries and dependencies cleanly without package conflicts. Avoiding Conda packages for underlying hardware communication layers ensures system libraries link correctly.

This installation step was tested and verified on Debian. Run the installer script below, update your system PATH, and initialize a virtual environment using uv venv. Once generated, activate the .venv directory to isolate your packages.

TerminalTested: all commands succeeded
# Download and install uv
curl -LsSf https://astral.sh/uv/install.sh | sh
# Add uv to system path
export PATH="$HOME/.local/bin:$PATH"
# Create virtual environment with Python 3.12
uv venv .venv --python 3.12
# Activate the virtual environment
source .venv/bin/activate
Output from our test run
$ curl -LsSf https://astral.sh/uv/install.sh | sh
downloading uv 0.13.10 x86_64-unknown-linux-gnu
installing to /root/.local/bin
  uv
  uvx
everything's installed!

To add $HOME/.local/bin to your PATH, either restart your shell or run:

    source $HOME/.local/bin/env (sh, bash, zsh)
    source $HOME/.local/bin/env.fish (fish)
$ export PATH="$HOME/.local/bin:$PATH"
$ uv venv .venv --python 3.12
Using CPython 3.12.16
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate
$ source .venv/bin/activate
(.venv) $

Installing vLLM

Installing vllm through pre-compiled binary wheels avoids lengthy compilation times from source code. Setting --torch-backend=auto lets the package installer detect and link the matching hardware execution libraries automatically.

This step was verified in our environment. Run the package installation command below to download the core engine alongside its dependencies.

TerminalTested: all commands succeeded
uv pip install vllm --torch-backend=auto
Output from our test run
$ uv pip install vllm --torch-backend=auto
Resolved 185 packages in 2.14s
Prepared 185 packages in 1m 25s
Installed 185 packages in 2.13s
 + agent-detector==2.0.0
 + aiohappyeyeballs==2.7.1
 + aiohttp==3.14.5
 + aiosignal==1.4.0
 + annotated-doc==0.0.7
 + annotated-types==0.8.0
 + anthropic==2.14.0
 + anyio==4.16.0
 + apache-tvm-ffi==0.1.11
 + astor==0.8.1
 + attrs==26.1.0
 + blake3==1.0.11
 + cachetools==8.0.3
 + cbor2==6.3.0
 + certifi==2026.11.20
 + cffi==2.1.1
 + charset-normalizer==3.5.3
 + click==8.5.1
 + cloudpickle==3.1.3
 + compressed-tensors==0.17.0
 + cryptography==50.0.2
 + cuda-bindings==13.5.0
 + cuda-core==1.2.2

Offline Batch Inference with Python

Offline batching serves workloads like synthetic dataset generation, bulk classification, and pipeline evaluation. In your Python script, import LLM and SamplingParams to control generation parameters such as temperature and max_tokens.

When initializing the LLM instance, explicitly set max_model_len to bound the memory reserved for sequence context. Long-context models can exhaust memory if allowed to reserve their maximum possible length during startup. Calling generate with a prompt list batches the workload across available memory efficiently.

batch_inference.py
from vllm import LLM, SamplingParams

prompts = [
    "Explain what an operating system kernel does in two sentences.",
    "List three primary advantages of continuous batching in LLM serving.",
]

sampling_params = SamplingParams(temperature=0.7, top_p=0.95, max_tokens=100)

llm = LLM(
    model="Qwen/Qwen2.5-1.5B-Instruct",
    max_model_len=4096,
)

outputs = llm.generate(prompts, sampling_params)

for output in outputs:
    prompt = output.prompt
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt}\nResponse: {generated_text}\n")

Launching the OpenAI-Compatible API Server

You can host models as networked services using the vllm serve entrypoint. The current architecture dynamically sizes the key-value cache after loading weights, removing the need to manually tune memory utilization flags for dedicated machines.

Start the server in the background targeting your model, specify --port 8000, and set --max-model-len to 4096. Note that automated health checks in this test sandbox encountered failures during the warmup period, so verify your hardware logs if initialization times out.

TerminalNot verified in our test run
# Start the vLLM server in the background
pgrep -f "vllm serve" >/dev/null || (nohup vllm serve Qwen/Qwen2.5-1.5B-Instruct --port 8000 --max-model-len 4096 > /tmp/vllm.log 2>&1 &)
# Wait for the server health check to pass
timeout 180 bash -c 'until curl -s http://127.0.0.1:8000/health >/dev/null; do sleep 3; done'
Output from our test run
$ pgrep -f "vllm serve" >/dev/null || (nohup vllm serve Qwen/Qwen2.5-1.5B-Instruct --port 8000 --max-model-len 4
096 > /tmp/vllm.log 2>&1 &)
$ timeout 180 bash -c 'until curl -s http://127.0.0.1:8000/health >/dev/null; do sleep 3; done'
$

Testing the API and Inspecting Metrics

Once the service responds, you can interact with it using standard OpenAI client libraries or through curl. The endpoint accepts standard chat completion payloads specifying Qwen/Qwen2.5-1.5B-Instruct and returns formatted JSON choices and token counts.

Server telemetry is exposed through the metrics endpoint. You can monitor running requests and cache utilization values such as vllm:num_requests_running and vllm:gpu_cache_usage_factor to track operational health under load.

TerminalNot verified in our test run
# Send an OpenAI-compatible completion request
curl -s http://127.0.0.1:8000/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "Qwen/Qwen2.5-1.5B-Instruct", "messages": [{"role": "user", "content": "Explain continuous batching in two concise sentences."}], "max_tokens": 80}' | python3 -m json.tool
# Check live cache usage and request metrics
curl -s http://127.0.0.1:8000/metrics | grep -E "vllm:num_requests_running|vllm:gpu_cache_usage_factor"

Wrap-up

You now have a clean foundation for high-throughput batching and interactive model serving. By pairing PagedAttention with continuous batching and proper context boundaries, you can maximize hardware utilization while avoiding out-of-memory errors.

FAQ

Why should Conda be avoided when installing vLLM?

Installing PyTorch through Conda channels often brings statically linked communication libraries like NCCL that can trigger runtime deadlocks during multi-GPU execution.

Why should max-model-len be explicitly defined?

Many models default to very large context windows. Without an explicit limit, the engine attempts to reserve memory for the full context, which can cause out-of-memory crashes during initialization.

Is manual GPU memory utilization configuration necessary?

In recent versions, the extensible key-value cache automatically claims free memory after warmup, making manual utilization overrides unnecessary unless you are partitioning a GPU across multiple applications.

Sources

Subscribe for more tested tutorials