Why Deployment Is a Chain, Not a Step

Most DeepSeek deployment guides start with "install vLLM, run the model" and end when "curl works". But in production the moment curl succeeds is exactly when risk concentrates: are the weights complete? Did you leave headroom in VRAM for concurrency? What happens when traffic arrives? How are in-flight requests handled during a restart? None of those answers live in the install steps; they live in the decision points along the whole chain.

This article does not repeat "how to install it". It treats deployment as an engineering chain with stages, dependencies, and verifiable preconditions: what each stage must prove, which parameters can be tuned after launch, and which mistakes are expensive to undo. We walk through four stages — environment preparation (driver / CUDA / PyTorch / vLLM version matrix), weight acquisition and integrity verification, inference engine selection and launch parameters, and production hardening (auth, rate limiting, monitoring, graceful shutdown, rolling upgrades) — then cover a minimal runnable deployment, an air-gapped variant, a failure-mode handbook, capacity planning, and a pre-launch checklist.

How This Differs from Existing Deployment Articles on the Site

Several articles here already cover a lot of ground, and this one deliberately avoids repeating them. "The Complete Guide to Running DeepSeek Models Locally" (id=73) focuses on tool selection and hardware pairing. "Downloading and Installing DeepSeek Models" (id=44) focuses on download commands and quantized variants. "DeepSeek Deployment and Operations Tutorial" (id=40) covers Docker and Kubernetes operating shapes. "DeepSeek-V4.1-Flash Local Deployment and Inference Optimization in Practice" (id=140) drills into one specific model's architecture and inference tuning.

The distinguishing angle here is the chain and its decision points. The same decision looks different in different stages, and stages impose hard constraints on each other: quantization precision determines whether the weights fit on one GPU, which determines whether tensor parallelism is possible, which in turn determines the concurrency ceiling. Other articles scatter those constraints. This one is the glue layer between them.

Four Stages and How They Depend on Each Other

The four stages depend on each other in one direction: the environment determines whether weights load, the weights determine how service parameters are set, and the service parameters determine how production hardening works — while production hardening in turn forces you back to change parameters (a gateway rate limit must sit below the engine's concurrency ceiling). Failures also propagate backwards: an out-of-memory condition surfaces as "the service got slow", but the root cause may live in the version matrix.

StageKey outputWhat happens when this layer breaksSection
1. EnvironmentA reproducible CUDA / PyTorch / vLLM combinationErrors surface only at weight load time, and the message usually does not point at the root causeSection 2
2. WeightsA locally verified weight directoryRandom crashes or garbled output at inference time, hard to reproduceSection 3
3. ServiceA stable OpenAI-compatible endpointYou discover during load testing that throughput will not scale or VRAM will run outSection 4
4. ProductionA service with auth, rate limits, monitoring, and rolling upgradesDuring an incident you cannot locate, cannot degrade gracefully, and cannot roll back quicklySection 5

Preconditions and the Boundaries of This Article

This article assumes you have already picked a model (DeepSeek-V3 / V3.2, or a newer architecture such as V4.1-Flash with long-context support) and have at least one NVIDIA GPU. Every VRAM estimate below assumes the conservative case where all weights stay resident in GPU memory. If you are using CPU offload or expert offload, recompute the numbers.

  • Hardware assumption: NVIDIA GPU with the driver installed and nvidia-smi producing output. AMD/ROCm, CPU-only, and Apple Silicon unified-memory paths are out of scope — vLLM's support level and parameter semantics differ substantially on those platforms.
  • Model assumption: DeepSeek open weights distributed in Hugging Face format (safetensors plus config.json plus tokenizer). GGUF quantized weights belong to the llama.cpp ecosystem; see the engine positioning notes in section 4.1.
  • Freshness: the inference stack moves fast. Version numbers, parameter names, and default behaviors mentioned here can change within months. Always confirm against the upstream compatibility matrix, and use the verification commands given in this article rather than trusting a copied snippet.

Stage Quick-Reference

If you are stuck on a specific symptom, jump straight to the relevant subsection:

Your current stateRead this first
torch.cuda.is_available() returns False, or you see an undefined symbol error2.2 / 2.3 / 2.4
Weights downloaded fine but loading fails with odd key errors3.5 / 3.7
The service answers, but throughput will not scale under load9.3 / 10
Requests queue as concurrency rises, then OOM a few minutes later5.2 / 5.3 / 9.1
You need auth, rate limiting, and monitoring on a self-hosted service5.1 / 5.6 / 5.10
Your network is air-gapped and the whole stack must be installed offlineSection 8

Stage One: Environment Preparation and the Version Matrix

This is the layer where things most often "look fine" while hiding landmines. The typical scenario: several CUDA Toolkit versions installed, a PyTorch wheel that bundles its own CUDA runtime, and vLLM whose extension is compiled against a specific PyTorch ABI — each piece looks healthy on its own, yet the combination will not run.

The Relationship Between Driver, CUDA Runtime, PyTorch, and vLLM

Build the right mental model first, because it determines every diagnostic action that follows:

  • Driver: installed in the operating system, provides the low-level GPU capability, and is the only component that genuinely cannot be missing.
  • CUDA Toolkit: includes nvcc, cuBLAS and other development/runtime libraries. You only need a full Toolkit if you compile CUDA extensions yourself. For inference only, you usually do not.
  • PyTorch's bundled CUDA runtime: pip-installed PyTorch wheels statically bundle the CUDA runtime they need (no system Toolkit required), but they impose a minimum driver version.
  • vLLM: a Python package with C++/CUDA extensions. Those extensions are compiled against a particular PyTorch ABI and pull in FlashAttention and cuBLASLt.

So the real compatibility constraint is vLLM to PyTorch, to the CUDA runtime PyTorch bundles, to the driver. Any other CUDA Toolkit you happen to have installed is usually irrelevant, as long as it does not interfere with the driver — unless you compile extensions yourself, in which case it must line up.

Trap One: The CUDA Version in nvidia-smi Is Not the Installed Version

The most common beginner mistake is reading "CUDA Version: 12.4" from the top of nvidia-smi output and concluding "I have CUDA 12.4 installed". That field actually reports the highest CUDA runtime version the current driver supports. It depends only on the driver and has nothing to do with whether you installed a Toolkit or which runtime PyTorch bundles.

# Driver version and the highest CUDA version that driver supports
nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv

# The CUDA runtime PyTorch was actually compiled against (this is the one in effect)
python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available())"

# Compute capability of the GPUs (decides FP8 / TF32 / Marlin availability)
python -c "import torch; print([torch.cuda.get_device_capability(i) for i in range(torch.cuda.device_count())])"

If torch.version.cuda differs from the version shown by nvidia-smi, that is not an error — as long as the driver is new enough for the PyTorch wheel, everything runs. The genuinely fatal case is an old driver, which produces "CUDA driver version is insufficient for CUDA runtime version".

Trap Two: pip-installed PyTorch Carries Its Own Runtime

Seeing CUDA 12.4 in nvidia-smi while torch.version.cuda reports 11.8 is perfectly normal — it simply means you installed the cu118 wheel. So pick wheels by the CUDA tag in the PyTorch index rather than by inspecting the system CUDA:

# Install from the PyTorch index for a specific CUDA version (example; replace cuXXX as needed)
pip install torch --index-url https://download.pytorch.org/whl/cu124

# Self-check immediately after install; mismatches surface right here
python -c "import torch; assert torch.cuda.is_available(); print(torch.__version__, torch.version.cuda)"

When download.pytorch.org is unreliable from mainland China, a domestic mirror can be used instead — but confirm the wheel's CUDA tag matches your driver. Mirrors often default to cu118 or cu121 wheels, which on a 4090 or H100 can manifest as "installed fine, will not run".

Common Version Combination Reference

The table below lists several combinations that have proven stable in the field, along with the symptoms you get when you mismatch them. Confirm exact versions against the vLLM README compatibility matrix, and run the environment self-check at the end of this section before installing anything.

CUDA runtime (bundled by PyTorch)Approximate driver floor (per NVIDIA release notes)Common vLLM pairingSymptom when mismatched
11.8 (cu118)about 520+older vLLM 0.4x–0.6.xMissing sm_89 / sm_90 kernels on newer GPUs (Ada, Hopper)
12.1 (cu121)about 530+vLLM 0.6.x–0.8.xIncompatible with newer torch.compile / inductor
12.4 (cu124)about 550+vLLM 0.8.x–0.10.x, a common pairing—
12.6 / 12.8 (cu126 / cu128)about 560+ / 570+newer vLLM and Blackwell cardsDriver too old: nvidia-smi looks fine but torch fails to initialize

Compute Capability Decides Which Acceleration Paths Exist

Compute capability (the SM version) determines the usable acceleration paths more directly than the CUDA version does. Confirm it on the machine rather than guessing:

Compute capabilityCommon cardsFP8 Tensor CoreBF16Notes
7.5T4NoNo (FP16 only)Noticeably slow, not suitable for large MoE models
8.0A100 / A30NoYesNo native FP8 instructions; FP8 runs an emulated path
8.6A10 / 3090 / 4090NoYesMarlin path for INT4/AWQ is available
8.9L4 / L40SYesYesConsumer 4090 is also 8.9, so FP8 works there
9.0H100 / H800YesYesFP8 weights and FP8 KV cache pay off most here

For a DeepSeek-scale MoE, BF16 is the floor: official weights are distributed in BF16, and loading them as FP16 can overflow numerically on long contexts — you get repeated output or NaNs. So --dtype bfloat16 should be the default, not an option.

Containerized Environment Preparation

The version matrix breaks most often when several people install different things on the same machine. In production, lock the matrix with a container rather than with documentation conventions:

# Run with the official prebuilt image; the image tag already binds CUDA and vLLM versions
docker run --gpus all --ipc=host --shm-size=16g \
  -p 8000:8000 \
  -v /data/models:/models:ro \
  vllm/vllm-openai:latest \
  --model /models/DeepSeek-V3 \
  --served-model-name deepseek-v3 \
  --tensor-parallel-size 2 \
  --max-model-len 16384

Two easily missed parameters: --ipc=host (or a large --shm-size) is required for multi-process tensor parallelism, otherwise the engine fails to start for lack of shared memory; and -v /data/models:/models:ro mounts the weights so you are not re-downloading hundreds of GB every time you rebuild the container.

Environment Self-Check

Before downloading any weights, run this and archive the output as your environment baseline. Every bizarre problem later can be traced back to this record:

nvidia-smi
python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available(), torch.cuda.device_count())"
python -c "import torch; print([torch.cuda.get_device_capability(i) for i in range(torch.cuda.device_count())])"
python -c "import vllm; print(vllm.__version__)"
python -c "import transformers; print(transformers.__version__)"
pip list | grep -Ei "torch|vllm|transformers|flash|xformers|numpy"
df -h /data
free -g

Keep the pip list output. Version conflicts among numpy, protobuf, and tokenizers are the single most common cause of vLLM crashing at startup (ImportError, or "AttributeError: 'NoneType' object has no attribute 'split'"), and almost no deployment document warns you about it in advance.

Stage Two: Acquiring Weights and Verifying Integrity

This stage looks like "download some files" but it is the first place where silent corruption happens. A hundreds-of-gigabytes model downloaded through LFS shards can leave behind a directory that looks complete but has missing pieces; the symptom only shows up at inference time, as a missing key or a nonsensical number.

Weight Sources and Repository Naming

DeepSeek open weights are primarily hosted on Hugging Face under the deepseek-ai organization, with mirrors such as ModelScope usually carrying the same repository names. The repository name must match exactly: deepseek-ai/DeepSeek-V3, deepseek-ai/DeepSeek-V3.2, deepseek-ai/DeepSeek-V4.1-Flash, and so on. Check the official organization page for the current list. Probe read-only before downloading anything:

# List repository files and sizes without downloading
huggingface-cli scan-cache
hf download deepseek-ai/DeepSeek-V3 --dry-run

Note that flags such as --dry-run are named differently in older CLIs (the older form being huggingface-cli download ... --dry-run). If you see "unrecognized argument", your local CLI is old — upgrade it or fall back to listing the manifest first.

Download Commands and Mainland China Networks

The recommended approach keeps weights in a fixed directory with the repository layout intact, so --model can point at a local path and container mounts stay simple:

# Option 1: Hugging Face CLI (new: hf, old: huggingface-cli)
pip install -U "huggingface_hub[cli]"
hf download deepseek-ai/DeepSeek-V3 --local-dir /data/models/DeepSeek-V3

# Option 2: ModelScope (more stable on mainland China networks)
pip install -U modelscope
modelscope download --model deepseek-ai/DeepSeek-V3 --local_dir /data/models/DeepSeek-V3

Two things to prepare for: disk headroom — downloads write temporary files before renaming, so peak usage can exceed the final size by 20% or more; and transfer acceleration — installing hf_transfer and setting HF_HUB_ENABLE_HF_TRANSFER=1 can cut multi-hundred-GB download times dramatically, but it also fails more often behind some proxies, so keep a fallback to plain download.

Resuming and Sharded Downloads

The HF CLI resumes by default — rerunning the same command continues where it stopped. But if you are behind a mirror or a custom proxy, confirm it actually honors Range requests. The test is simple: interrupt with Ctrl+C, rerun the same command, and watch whether the progress bar continues or restarts.

For very large repositories, downloading shards in parallel beats a single process:

# Export the file manifest first
hf download deepseek-ai/DeepSeek-V3 --dry-run --format json > files.json
# Group by shard prefix and download each group in its own process
for shard in 00001 00002 00003; do
  hf download deepseek-ai/DeepSeek-V3 --include "model-*-of-*.safetensors" \
     --local-dir /data/models/DeepSeek-V3 --max-workers 8 &
done
wait

Parallel downloads amplify random-write pressure. On spinning disks or network storage the speedup can be negative — on a production box, download to a local NVMe cache and then sync the whole directory into place.

Integrity Verification: Three Layers

After downloading, verify in three layers from weakest to strongest. Only when all three pass should you consider the weights usable:

  • Layer one: presence and size.Compare the local directory against the repository file manifest; confirm no shard is missing and no truncated file is hiding.
  • Layer two: LFS pointer detection.If a file is only about 130 bytes and its content starts with version https://git-lfs.github.com/spec/v1, you downloaded the pointer instead of the payload and must refetch that file. This is the classic silent failure in LFS setups.
  • Layer three: SHA256.Compare each file against the official sha256 index (or a manifest you generated from the repository metadata) and then perform a real deserialization test.
# Layer two: find every LFS pointer file (real weight files are far larger than 1KB)
find /data/models/DeepSeek-V3 -name "*.safetensors" -size -1k -print

# Layer three: generate and verify a sha256 manifest
cd /data/models/DeepSeek-V3
find . -type f \( -name "*.safetensors" -o -name "*.json" \) -print0 \
  | xargs -0 sha256sum > /data/models/DeepSeek-V3.sha256
sha256sum -c /data/models/DeepSeek-V3.sha256

Finally, run an actual load test — it catches structural problems the sha256 manifest cannot, such as a weight map that names tensors the shards do not contain:

python -c "
from safetensors import safe_open
import glob
for f in sorted(glob.glob('/data/models/DeepSeek-V3/*.safetensors')):
    with safe_open(f, framework='pt') as fp:
        print(f.split('/')[-1], len(fp.keys()), 'tensors')
"

Cross-check config.json against the actual weights while you are at it: num_hidden_layers, hidden_size, num_attention_heads, and torch_dtype determine how the engine allocates memory and KV cache. If config and weights come from different versions, the symptom is a shape mismatch at load time — or a successful load that produces unusable output.

Moving Weights into an Air-Gapped Environment

Air-gapped deployments need the download and packaging done on a machine with internet access. Tar split into pieces plus a checksum manifest is the pragmatic choice; keeping each file under 2 GB avoids problems with many media and transfer tools:

# Package (relative paths, so unpacking yields the model directory directly)
cd /data/models
tar -cf - DeepSeek-V3 | split -b 2000M -d -a 3 - DeepSeek-V3.tar.part.
sha256sum DeepSeek-V3.tar.part.* > DeepSeek-V3.tar.part.sha256

# After transfer: verify first, then unpack
sha256sum -c DeepSeek-V3.tar.part.sha256
cat DeepSeek-V3.tar.part.* | tar -xf - -C /data/models/

The pieces produced by split must be concatenated in order; the wrong order yields a directory that looks complete but is corrupt. The manifest must travel with the pieces, and verification must happen before unpacking.

Failure Modes in the Download Stage

SymptomRoot causeFix
Download "completes" but the safetensors file is 130 bytesYou received an LFS pointerLocate it with find -size -1k and refetch that file
"No space left on device" mid-downloadTemporary and target files coexist; peak usage exceeds final sizeReserve 1.5x the final size, or download to another filesystem and move
Speed oscillates and drops to zeroProxy does not honor Range requestsSwitch to a direct link or mirror; disable HF_HUB_ENABLE_HF_TRANSFER
Checksum mismatchTruncated transfer or silent disk errorRefetch the shard; enable storage-side checksums where available
config.json does not match the weightsFiles from different versions mixed across several downloadsWipe the directory and download again; never patch files incrementally

Stage Three: Choosing the Inference Service

For most cases the answer is vLLM, but "why" and "when not to" matter just as much, because the wrong engine invalidates every parameter tuning effort that follows.

Positioning of Four Engines

  • vLLM: PagedAttention plus continuous batching, aimed at high-throughput production services with a complete OpenAI-compatible surface. It is the de facto standard for DeepSeek weights. The costs are high VRAM usage, slow startup, and sensitivity to CUDA versions.
  • SGLang: offers a more structured execution engine and RadixAttention prefix caching on top of the same ideas, which helps in multi-turn and agent workloads with repeated prefixes. Its interface and parameters broadly resemble vLLM's.
  • llama.cpp: targets CPUs and edge devices and supports GGUF quantization. It remains the practical option without a GPU, but its support and performance for a MoE of DeepSeek's scale trail the GPU path badly.
  • Ollama: a convenience wrapper for local interactive use. It is not a production API host — concurrency control, authentication, and metrics exposure are all missing.

Selection Decision Table

ScenarioRecommended engineWhyWhat to avoid
Public OpenAI-compatible API with concurrent usersvLLMContinuous batching and PagedAttention give the best throughput and VRAM utilizationExposing Ollama directly to the internet
Agents and multi-turn chats with heavy prefix reusevLLM or SGLangWith prefix caching, shared prefixes cut TTFT noticeablyRe-prefilling the entire history on every request
No GPU; edge boxesllama.cppGGUF quantization with the CPU backendForcing vLLM onto a CPU-only box
Personal interactive useOllamaRuns with one commandBuilding a production stack for personal use
Multi-node cluster needing DAG-level schedulingSGLang or a dedicated inference platformStronger multi-replica and structured schedulingCopying weights across nodes and hoping for horizontal scaling

Anatomy of a Minimal vllm serve Command

This command is the basis for every example that follows. Read it as a whole first, then go parameter by parameter:

vllm serve /data/models/DeepSeek-V3 \
  --served-model-name deepseek-v3 \
  --tensor-parallel-size 2 \
  --dtype bfloat16 \
  --max-model-len 16384 \
  --gpu-memory-utilization 0.90 \
  --max-num-seqs 64 \
  --enable-prefix-caching \
  --port 8000
ParameterEffectHow to choose it
--modelWeight path or repository IDAlways a local absolute path in production, so startup never triggers a download check
--served-model-nameThe model name exposed to clientsUse a stable business alias (for example deepseek-v3) so client configs do not churn when the weights change
--tensor-parallel-sizeTensor parallel degree (how many GPUs to shard across)Increase until the weights fit; cross-node setups also need --pipeline-parallel-size plus Ray/NCCL configuration
--dtype bfloat16Compute precisionDeepSeek weights are BF16 by default; do not switch to fp16
--max-model-lenMaximum context lengthSet it to what the workload really needs; it directly determines how much KV cache is reserved
--gpu-memory-utilizationFraction of total GPU memory vLLM may useDefault 0.9; drop toward 0.8 when the GPU is shared with other processes
--max-num-seqsMaximum sequences scheduled at onceSet it explicitly; defaults vary by version (somewhere between 256 and 1024)
--enable-prefix-cachingEnable KV reuse across shared prefixesLarge gains in multi-turn chats and fixed-system-prompt workloads
--portListening portBind locally; let nginx handle external traffic

OpenAI Compatibility and Model Aliases

Once vLLM is up, it exposes the standard OpenAI paths: /v1/models, /v1/chat/completions, /v1/completions, and /v1/embeddings (depending on model capability). Any OpenAI SDK client can connect by changing base_url:

export OPENAI_BASE_URL="http://127.0.0.1:8000/v1"
export OPENAI_API_KEY="not-needed-but-some-clients-require-it"

Mind the /v1 suffix: base_url must include it, otherwise the client appends another /v1 and you get a 404. This is the single most common small mistake when wiring up a self-hosted service.

Verifying with curl: Regular and Streaming

# Regular request
curl -s http://127.0.0.1:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v3",
    "messages": [{"role": "user", "content": "Explain tensor parallelism in one sentence"}],
    "max_tokens": 128
  }'

# Streaming request
curl -N http://127.0.0.1:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model":"deepseek-v3","messages":[{"role":"user","content":"count to three"}],"stream":true,"max_tokens":32}'

Streaming responses arrive as SSE: each line starts with data:, and the stream ends with data: [DONE]. If you see incremental output followed by [DONE], the entire chain — HTTP, scheduling, model execution, stream encoding — works.

How to Read the Startup Log

The startup log is long, but a handful of lines actually determine the behavior that follows. Check each one:

# Weight loading progress
Loading safetensors checkpoint shards:  50%|#####     | 5/10 [00:41<00:42, 1.20s/it]

# Memory profiling: the most important line, it determines KV cache size
Memory profiling results: model weights take 671.24 GiB; non_torch_memory takes 2.15 GiB;
PyTorch activation peak memory takes 18.30 GiB; the rest of the memory reserved for KV Cache is 148.11 GiB

# KV cache capacity and maximum concurrency
GPU KV cache size: 243712 tokens
Maximum concurrency for 16384 tokens per request: 14.87x

The "Maximum concurrency" line gives your concurrency ceiling directly: it is available KV cache tokens divided by the per-request maximum length. If it reads 14.87x, only a dozen or so long requests can run simultaneously at that --max-model-len. Dropping --max-model-len to 4096 quadruples that number. This is the most common technical reason "concurrency will not scale", and it has nothing to do with insufficient compute.

Multi-GPU and Tensor Parallelism

When the weights exceed a single GPU's memory, tensor parallelism is the only realistic option. Key points:

  • The TP degree must divide the attention head count and intermediate dimensions evenly. MoE architectures like V3/V4 have many heads, and the usable values are typically 2, 4, or 8.
  • All GPUs should be the same model — mixing card types consumes most of the gain in communication and memory asymmetry.
  • Containers need --ipc=host or a sufficient --shm-size, otherwise the engine stalls during process initialization.
  • Multi-node deployments add --pipeline-parallel-size and require correct NCCL environment variables (NCCL_P2P_DISABLE and NCCL_IB_DISABLE are common workarounds for specific network environments).

Stage Four: Production Hardening

The first three stages aim for "the service runs". This stage aims for "the service can be depended on". Production hardening is not a nice-to-have; it decides whether an incident takes five minutes or two hours.

Authentication: Three Layers

The most serious common mistake with self-hosted inference services is exposing them to the network with no authentication at all. vLLM provides the innermost layer:

vllm serve /data/models/DeepSeek-V3 --api-key "$INTERNAL_API_KEY" --port 8000

With --api-key set, clients must send Authorization: Bearer <key>. Production should use three layers:

  1. Network: vLLM binds to 127.0.0.1 or an internal address; only nginx is exposed. This is the most effective layer.
  2. Gateway: nginx handles API key validation, rate limiting, access logs, and TLS termination.
  3. Engine: --api-key as a backstop in case someone bypasses the gateway and hits the port directly.

Rate Limiting and Concurrency Control: max-num-seqs Is Not the Concurrency Ceiling

A common belief is that raising --max-num-seqs raises concurrency capacity. The real relationship is:

actual concurrent sequences = min(max-num-seqs, KV cache tokens / average tokens per request)

In long-context workloads, KV cache is usually the bottleneck. The right move is to shape the queue at the gateway rather than let the engine absorb it: queue in nginx's limit_conn (observable and controllable) instead of letting requests pile up inside the engine (unobservable, and it can trigger VRAM preemption).

# Concurrency limits on the nginx side (placed in the http block)
limit_req_zone $binary_remote_addr zone=llm_chat:10m rate=20r/s;
limit_conn_zone $binary_remote_addr zone=llm_conn:10m;

The gateway threshold should sit below the engine's real concurrency ceiling with margin to spare. Otherwise you get the classic symptom: the gateway still admits requests while the engine is already queueing, which shows up as severe latency jitter. A practical rule is to start at 60–70% of the "Maximum concurrency" value from the engine log.

Why the Service Slows Down Instead of Crashing When VRAM Runs Out

This is the most counter-intuitive part of self-hosted inference and the one you most need to understand in advance: when VRAM fills up, the service usually does not crash — it slows down first. The reason is that the vLLM scheduler does not surface allocation failures to users; it converts pressure into queueing and recomputation:

  • Queuing: when no KV block is free, new requests wait, and TTFT climbs.
  • Preemption by RECOMPUTE: when a block must be freed for a new request, the engine preempts a running sequence and discards its KV, recomputing it if needed. The log shows "Sequence group is preempted by RECOMPUTE". Preemption destroys throughput — you pay for prefill and never get the result.
  • Failure comes last: only when the activation memory needed for prefill itself exceeds the limit do you get torch.OutOfMemoryError and a 500 response.

So queue depth and preemption counts belong in first-tier monitoring, alongside VRAM usage and 5xx rates. A full GPU is healthy by design in vLLM; only a full GPU accompanied by queueing and preemption indicates a misconfigured deployment.

Health Checks: Separate Liveness from Readiness

Production health checks must express two different things: liveness (is the process alive) and readiness (can it serve). Loading weights takes from tens of seconds to several minutes, and a liveness probe pointing at the same endpoint makes Kubernetes restart the container in a loop during startup.

# Liveness: succeed as long as the process is running
curl -i http://127.0.0.1:8000/health

# Readiness: confirm the engine finished initializing and can list models
curl -s http://127.0.0.1:8000/v1/models | head -c 200

Health endpoint paths have varied across vLLM versions (/health and /healthz have both existed), so test it once before deploying rather than copying a config. The safe readiness probe is /v1/models: it always exists and its meaning is unambiguous.

Graceful Shutdown and Draining Connections

Shutdown is the most neglected part of production hardening and has the most direct consequences. A default kill -9 fails every in-flight request instantly, and clients see a connection reset rather than an error. The correct sequence is:

# Send SIGTERM first: the engine stops accepting new requests and drains in-flight ones
kill -TERM $(cat /run/vllm.pid)
# Wait for the drain, escalating to SIGKILL only on timeout
timeout --signal=KILL 300 tail --pid=$(cat /run/vllm.pid) -f /dev/null

Pair this with a preStop hook: in Kubernetes, configure preStop.exec to sleep a few seconds so endpoint changes propagate before SIGTERM is sent. Otherwise there is a window between deregistration and client awareness in which new requests get rejected outright.

Monitoring Metric Checklist

The open-source vLLM build does not expose a Prometheus endpoint by default; that requires the vLLM Production Stack or your own instrumentation. Even without a full monitoring stack, you should be able to extract these from logs:

MetricSourceSuggested alert thresholdWhat an anomaly means
Queued requestsEngine logs or custom instrumentationAbove zero while TTFT risesNot enough KV cache, or concurrency configured too aggressively
Preemption / recompute countRECOMPUTE records in the logAlert on first occurrenceVRAM budget and concurrency do not match; throughput is being wasted
TTFT / TPOTClient-side or gateway instrumentation50% above baselineScheduling queue or slower prefill
GPU memory and utilizationnvidia-smi or DCGMUtilization pinned at 100%Compute saturated; scale out or reduce concurrency
5xx ratioGateway access logAbove 1%Real errors are starting, usually alongside OOM
Client 502 / 504Gateway error logAbove zeroEngine restart, upstream refused, or timeout

Also monitor engine restart counts. Many production incidents look like "the service occasionally slows for ten seconds and recovers", but the real cause is the engine being killed by the OOM killer and restarted by systemd, with Restart=on-failure masking the crash as a performance blip.

Running Under systemd

systemd is worth the small effort: boot-time startup, automatic restart after crashes, resource limits, graceful shutdown, and log collection all come for free.

[Unit]
Description=vLLM OpenAI-compatible server
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=vllm
WorkingDirectory=/opt/vllm
Environment="HF_HUB_OFFLINE=1"
Environment="TRANSFORMERS_OFFLINE=1"
Environment="CUDA_VISIBLE_DEVICES=0,1"
ExecStart=/opt/vllm/venv/bin/vllm serve /data/models/DeepSeek-V3 \
  --served-model-name deepseek-v3 \
  --tensor-parallel-size 2 \
  --dtype bfloat16 \
  --max-model-len 16384 \
  --gpu-memory-utilization 0.90 \
  --max-num-seqs 64 \
  --enable-prefix-caching \
  --api-key $INTERNAL_API_KEY \
  --port 8000
Restart=on-failure
RestartSec=10
KillSignal=SIGTERM
TimeoutStopSec=330
LimitNOFILE=65535
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

Two easy-to-miss settings: TimeoutStopSec must exceed the time the engine needs to drain in-flight requests (long-context requests can take tens of seconds), or systemd kills it outright and the graceful shutdown was pointless; and Restart=on-failure with RestartSec prevents crash storms, but pair it with alerting or it will hide problems.

docker-compose Fragment

services:
  vllm:
    image: vllm/vllm-openai:latest
    container_name: vllm
    runtime: nvidia
    environment:
      NVIDIA_VISIBLE_DEVICES: "0,1"
      NVIDIA_DRIVER_CAPABILITIES: compute,utility
      HF_HUB_OFFLINE: "1"
      TRANSFORMERS_OFFLINE: "1"
    command:
      - "--model=/models/DeepSeek-V3"
      - "--served-model-name=deepseek-v3"
      - "--tensor-parallel-size=2"
      - "--dtype=bfloat16"
      - "--max-model-len=16384"
      - "--gpu-memory-utilization=0.90"
      - "--max-num-seqs=64"
      - "--enable-prefix-caching"
      - "--api-key=$INTERNAL_API_KEY"
    ports:
      - "127.0.0.1:8000:8000"
    volumes:
      - /data/models:/models:ro
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 2
              capabilities: [gpu]
    ipc: host
    shm_size: 16gb
    restart: unless-stopped
    stop_grace_period: 330s

stop_grace_period is the compose equivalent of TimeoutStopSec: without it the default is 10 seconds, the container is killed, and every in-flight request fails. And writing ports as 127.0.0.1:8000:8000 rather than 8000:8000 keeps the port reachable only on the host, so all external traffic goes through nginx.

nginx Reverse Proxy

The proxy layer solves three things: TLS termination, access logging, and unbuffered streaming responses. The first two are easy; the third is where people get it wrong — the default response buffering makes SSE output accumulate and then dump in one burst, and the client looks like it "hangs".

upstream vllm_backend {
    server 127.0.0.1:8000;
    keepalive 64;
}

server {
    listen 443 ssl http2;
    server_name llm.internal.example.com;

    ssl_certificate     /etc/nginx/tls/llm.crt;
    ssl_certificate_key /etc/nginx/tls/llm.key;

    # LLM request and response bodies are both large
    client_max_body_size 32m;
    proxy_read_timeout  600s;
    proxy_send_timeout  600s;

    location / {
        # Auth: compare the request header. The map is generated by the deploy script
        # into its own file with 0400 permissions, and looks like:
        # map $http_authorization $llm_auth_ok { default 0; "Bearer xxxxx" 1; }
        include /etc/nginx/snippets/llm-auth.map;
        if ($llm_auth_ok = 0) {
            return 401 "unauthorized";
        }

        limit_req zone=llm_chat burst=40 nodelay;
        limit_conn llm_conn 64;

        proxy_pass http://vllm_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # Streaming: no buffering, pass through immediately
        proxy_buffering off;
        proxy_cache off;
        chunked_transfer_encoding on;
    }
}

Two more production notes: alongside proxy_buffering off, set proxy_request_buffering off so request bodies are not spooled to disk first; and log $request_time and $upstream_response_time separately, because the difference tells you directly whether the engine is slow or the network path is.

Rolling Upgrades and Two-Instance Cutover

When upgrading the model or the engine, avoid stop-upgrade-start. Use a two-instance blue-green cutover:

  1. Start the new version with exactly the same --served-model-name, wait for /v1/models to report ready, and run your benchmark.
  2. Point the nginx upstream at the new instance (or shift weights from 100% to 0%).
  3. Watch the core metrics for 10–15 minutes; keep at least one old instance around for instant rollback.
  4. Only decommission the old instance once you are satisfied.

The critical constraint: both instances must expose exactly the same --served-model-name, otherwise client configurations have to change and the switch is no longer zero-cost. If the business allows it, run old and new side by side and separate traffic by model name for canarying.

Choosing a Quantization: The VRAM, Quality, Speed Triangle

Quantization is the one decision in the chain that simultaneously affects whether it runs, how fast it runs, and whether it runs correctly. It has to be considered between stage two and stage three: compute whether VRAM is sufficient first, then pick a precision — not the other way around.

The VRAM Ledger

Break the requirement into four parts; counting only the weights is the classic mistake:

total VRAM = weights + KV cache + activation peak + framework and communication overhead

weights (GB)   ≈ parameter count (B) × bytes per parameter / 2^30
KV cache (GB)  ≈ concurrency × tokens per request × bytes per token / 2^30

Bytes per token is where DeepSeek's architecture pays off. In classic MHA/GQA layouts the KV cache grows with layers, KV heads, and head dimension, while DeepSeek's MLA (Multi-head Latent Attention) compresses KV into a low-dimensional latent vector, so KV volume per token is far smaller than in a conventional architecture of the same size. The measured figure quoted in the site's id=140 article is roughly 890 bytes per token, against roughly 3514 bytes for a comparable non-MLA design of the same generation — a quarter of the cache. That is exactly why DeepSeek suits long contexts and high concurrency, and it is a term you must include in the calculation.

VRAM Reference by Precision

The table below uses parameter count times bytes per parameter to give a theoretical floor. Real usage adds quantization metadata (scales, zero points) and framework overhead, so add 5–15% on top. Two common reference points are DeepSeek-V3 (671B total parameters, 37B activated) and V4.1-Flash (552B total parameters):

PrecisionBytes per paramWeight floor for 671BWeight floor for 552BHardware requirementQuality and speed
FP324about 2500 GBabout 2057 GBnot practicalnot used for inference
BF16 / FP162about 1251 GBabout 1028 GBcluster; 8×H100 80GB barely holds the weightsbaseline quality, no quantization loss
FP81about 626 GBabout 514 GBSM 8.9+ (Ada / Hopper)small quality loss, often faster than BF16
INT81about 626 GBabout 514 GBmost inference GPUsdistinguish FP8 weights from FP8 activations
INT4 (AWQ / GPTQ)about 0.5 plus metadataabout 336 GB floor, realistically 360–400 GBabout 276 GB floor, realistically 300–330 GBSM 8.0+ benefits most from the Marlin kernelmeasurable quality loss, largest memory and bandwidth win

Note the word "floor" in the table. It assumes every weight lives in VRAM. There is also a MoE-specific detail that trips people up: only a fraction of parameters are activated per token (37B out of 671B for V3), but all expert weights must stay resident, because routing is decided per token. MoE VRAM planning therefore behaves like a dense model — you cannot discount by the activated parameter count.

FP8: When It Is Worth It

FP8 is currently the best value tier: half the memory, usually acceptable quality loss, and often faster than BF16 on Hopper and Ada thanks to native FP8 Tensor Cores and higher memory bandwidth. The prerequisite is hardware with native FP8 support:

# Confirm compute capability; Ada is (8, 9), Hopper is (9, 0)
python -c "import torch; print(torch.cuda.get_device_capability(0))"

# Launch with FP8 weights and BF16 activations (weights quantized offline, compute stays high precision)
vllm serve /data/models/DeepSeek-V3-FP8 --quantization fp8 --dtype bfloat16

Note that weight precision and compute precision are separate parameters: --quantization fp8 says weights are stored as FP8, while --dtype bfloat16 says intermediate compute stays in BF16. If your card has no native FP8 (A100 is SM 8.0), the engine may take an emulated path and end up slower than BF16 — in that case use BF16 or AWQ instead.

INT4: Three Routes — AWQ, GPTQ, and bitsandbytes

  • AWQ: activation-aware weight quantization that keeps activations in FP16. It usually performs best on vLLM and is the common choice for DeepSeek MoE deployments.
  • GPTQ: layer-wise GPTQ quantization, with an earlier ecosystem and more literature; performance is close to AWQ.
  • bitsandbytes: runtime quantization with no pre-quantized weights required — handy for a quick trial. For production, prefer pre-quantized weights so startup does not spend minutes quantizing every time.
# Pre-quantize (example with AutoAWQ), producing a separate directory
pip install autoawq
python -m awq --model_path /data/models/DeepSeek-V3 --quant_type int4 \
  --output_dir /data/models/DeepSeek-V3-AWQ --calib_size 128 --q_group_size 128

# Launch
vllm serve /data/models/DeepSeek-V3-AWQ --quantization awq_marlin --dtype float16

AWQ quantization requires a calibration set, and that step is slow and introduces uncertainty: when the calibration distribution differs from production traffic, the quality loss is noticeably worse than the headline numbers suggest. This is why a quantized build must be evaluated on your own business samples rather than on a handful of generic benchmarks.

Quality Impact Must Be Measured, Not Assumed

The common mistake is "it looked fine after quantizing". The reliable approach is to build a small but representative evaluation set:

  1. Assemble 200–500 business samples that cover the real input length distribution, instruction types, and output format requirements.
  2. Define automatically checkable metrics: for exact-match tasks (JSON parsing, classification labels) use rules; for generative tasks use a fixed rubric plus human spot checks, or a stronger model as judge with calibration.
  3. Compare in pairs: run the same samples on BF16 and on the quantized build, and compare the differences and confidence intervals rather than absolute scores.
  4. Focus on long context and structured output: quantization error shows up there first — lower recall in long-context retrieval and a higher JSON validity failure rate.

A practical threshold: if a key business metric degrades by more than 5%, or JSON validity drops by more than 2 percentage points, do not ship that tier. Moving up to FP8 usually recovers most of the memory saving with far less quality damage.

Scenarios That Require High Precision

ScenarioRecommended precisionWhy
Code generation and automated repairBF16 or FP8Quantization error introduces small syntactic mistakes that evaluation scripts flag as failures
Structured output under strict JSON SchemaBF16 or FP8Format validity drops noticeably after quantization
Long-context information extractionBF16 or FP8Needle-in-a-haystack style tasks are precision-sensitive
Mathematical and multi-step reasoning evaluationBF16Any tiny deviation along the reasoning chain compounds
Internal drafts, classification, tagging at high concurrencyINT4 is fineLarge tolerance for error, and cost-sensitive

How Quantization Interacts with Context Length

One interaction is easy to miss: quantization frees up weight VRAM, but it also removes the space that would otherwise have gone to KV cache — and KV cache is the real bottleneck in long-context workloads. So "can I now serve a longer context after quantizing" is not a simple multiplication. Re-read the "Maximum concurrency" line in the startup log. The other interaction is the precision of the KV cache itself: --kv-cache-dtype fp8 halves KV space again, at the cost of recall accuracy on long contexts — evaluate it together with the quality measurements above.

A Minimal Runnable Deployment: From Zero to a Working curl

This section is the executable minimum. Assume an 8× H800 machine (80 GB per card) and the goal of bringing DeepSeek up and getting curl to talk to it. Run the commands in order; each step has a verification point.

Step 0: Hardware and System Checks

nvidia-smi
# Expect 8 cards at roughly 80GB each, driver version 550 or newer
df -h /data
free -g

Step 1: Install

python3 -m venv /opt/vllm/venv
/opt/vllm/venv/bin/pip install -U pip
/opt/vllm/venv/bin/pip install vllm
/opt/vllm/venv/bin/python -c "import vllm; print(vllm.__version__)"

If you intend to pin versions strictly, install with pip install vllm==specific-version and commit the lock file to your repository. Version drift in the inference stack is the main cause of "it worked yesterday". Also confirm the PyTorch CUDA wheel matches what the vLLM build expects:

/opt/vllm/venv/bin/python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available())"

Step 2: Launch

export HF_HUB_OFFLINE=1
export TRANSFORMERS_OFFLINE=1
export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7

/opt/vllm/venv/bin/vllm serve /data/models/DeepSeek-V3 \
  --served-model-name deepseek-v3 \
  --tensor-parallel-size 8 \
  --dtype bfloat16 \
  --max-model-len 16384 \
  --gpu-memory-utilization 0.90 \
  --max-num-seqs 32 \
  --enable-prefix-caching \
  --port 8000

The first launch loads weights and profiles memory, usually taking several minutes. Do not hit Ctrl+C and restart repeatedly: interrupting the load can leave a half-loaded state that makes the next attempt fail with VRAM-related errors. Let it finish, or confirm the error and exit completely.

Step 3: Verify

curl -s http://127.0.0.1:8000/v1/models
curl -s http://127.0.0.1:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model":"deepseek-v3","messages":[{"role":"user","content":"ping"}],"max_tokens":8}'

A normal JSON response means the chain is connected. Next verify streaming, so SSE works correctly:

curl -N http://127.0.0.1:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model":"deepseek-v3","messages":[{"role":"user","content":"count from 1 to 5"}],"stream":true,"max_tokens":64}'

Step 4: Connect with the OpenAI SDK

pip install openai
from openai import OpenAI

client = OpenAI(
    base_url="http://127.0.0.1:8000/v1",
    api_key="not-needed",
)

resp = client.chat.completions.create(
    model="deepseek-v3",
    messages=[{"role": "user", "content": "Explain PagedAttention in one sentence"}],
    max_tokens=200,
)
print(resp.choices[0].message.content)

Step 5: Convert to a systemd Service

Move the Step 2 command into a unit file (format in section 5.8) and run:

sudo cp vllm.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now vllm
sudo systemctl status vllm
sudo journalctl -u vllm -f

The Air-Gapped Variant

Offline environments are not "follow the online guide with the network off". Four differences must be handled up front: where packages come from, where images come from, how weights travel, and how you prove the installation is correct.

Offline Inventory

CategoryWhat is neededHow to obtain it
Python wheelsvllm, torch, transformers and every transitive dependencypip download on a connected machine into a local directory
Container imagesvllm/vllm-openai and its base imagedocker save into a tar
Model weightssafetensors shards plus config and tokenizertar split plus a sha256 manifest
Configurationsystemd unit, compose file, nginx config, .envmanaged in the configuration repository

Offline Installation Steps

# Connected machine: export all wheels
mkdir -p /tmp/offline/wheels
pip download vllm -d /tmp/offline/wheels --no-deps=false
# Fill in transitive dependencies
pip download -d /tmp/offline/wheels $(pip list --format=freeze | cut -d= -f1)

# Offline machine: install from the local directory only
pip install --no-index --find-links=/tmp/offline/wheels vllm

A more reliable approach uses pip download with --platform and --only-binary=:all: to export manylinux wheels matching the target machine, so the offline host never falls back to a source build (which would require nvcc and a full CUDA Toolkit).

Exporting and Importing Images

# Connected machine
docker pull vllm/vllm-openai:latest
docker save -o vllm-openai.tar vllm/vllm-openai:latest
gzip -k vllm-openai.tar

# Offline machine
gunzip vllm-openai.tar
docker load -i vllm-openai.tar
docker images | grep vllm

Images usually do not contain the weights — hundreds of GB does not belong in an image — so mount them separately. Also note that a latest tag is not reproducible; in an offline environment, record the concrete digest in the deployment document.

Moving Weights Offline

# Transfer and verify (see section 3.6 for details)
sha256sum -c DeepSeek-V3.tar.part.sha256
cat DeepSeek-V3.tar.part.* | tar -xf - -C /data/models/

Four Differences in Offline Environments

  • No online update checks: pin every dependency explicitly and never run pip install -U on the offline host.
  • Offline switches are mandatory: set HF_HUB_OFFLINE=1 and TRANSFORMERS_OFFLINE=1, otherwise the engine tries to reach the network to check repository versions and can stall for tens of seconds or time out.
  • Certificates and clock: if you run an internal CA, make sure the CA bundle is present inside the container; a skewed system clock breaks TLS validation.
  • Different verification method: offline machines cannot run online benchmarks, so maintain an offline golden set (inputs plus expected outputs) and run it on every upgrade as a regression check.

The Failure Mode Handbook

This section collects the classic failures from every stage into a searchable list. Keeping it in the on-call handbook is worthwhile.

Five Typical Out-of-Memory Failures

Error or symptomRoot causeFix, in priority order
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate X GiB during weight loadingThe weights themselves do not fitRaise --tensor-parallel-size, or switch to INT4/FP8 weights
ValueError: The model's max seq len (N) is larger than the maximum number of tokens that can be stored in KV cacheKV cache cannot hold the configured context lengthReduce --max-model-len, or raise --gpu-memory-utilization if VRAM really is free
RuntimeError: No available memory for the cache blocksKV block allocation failedReduce --max-num-seqs and --max-model-len, or use --kv-cache-dtype fp8
Engine core initialization failed (usually preceded by a traceback)Initialization ran out of VRAM, usually insufficient TP degree or another process holding the GPURead the last line of the traceback; confirm no other process occupies the GPU with nvidia-smi
Requests return 500 with CUDA error: out of memory and a flood of RECOMPUTE recordsConcurrency too high, so the prefill activation peak exceeds the limitLower --max-num-seqs; rate limit at the gateway; enable chunked prefill to process long prompts in batches

A general principle: prefer fixing out-of-memory problems with parameters rather than with more GPUs. In most cases, dropping --max-model-len from 32768 to 8192 and --max-num-seqs from 256 to 64 makes an OOM configuration run — at the cost of a smaller concurrency ceiling and a shorter context, which is usually far cheaper than another GPU.

A Triage Order for Slow Model Loading

Work through these in order; each step eliminates one class of cause:

  1. Is it slow to read, or is the model simply big?Watch the speed of the "Loading safetensors checkpoint shards" progress bar. If each shard takes minutes, the bottleneck is storage. Use iostat -x 1 for disk utilization, or measure sequential read bandwidth with dd.
  2. Is it network storage?Copy the weights to local NVMe and start again, then compare load times. If it improves clearly, the problem was IO, not compute.
  3. Is it doing graph capture or compilation?Some versions run torch.compile or CUDA graph warmup, visible in the log and costing minutes. Use --enforce-eager to skip it for a comparison run.
  4. Is it repeating the memory profiling pass?vLLM runs a dryrun to estimate available KV cache. If another process occupies the GPU, the estimate is unstable and may trigger retries.
  5. Is the CPU short?Deserialization and shard loading are CPU-bound, and multi-GPU loading can bottleneck on a single core. Check nproc and the load average.

How to Find Why Concurrency Will Not Scale

  1. Read "Maximum concurrency" in the startup log. That number is the theoretical ceiling. If it is in the teens, the bottleneck is KV cache, not GPU compute.
  2. Distinguish queueing from compute saturation.During load testing, watch nvidia-smi utilization at the same time: near 100% means compute-bound (quantize or add GPUs); only 30–50% with high TTFT means scheduling or KV-cache-bound (change parameters).
  3. Look at the shape of the TTFT curve.Linear growth as concurrency rises from 1 to N is normal. An exponential jump means you hit the concurrency ceiling or triggered preemption.
  4. Check for preemption.Grep the log for RECOMPUTE; any occurrence means KV cache is insufficient.
  5. Confirm prefix caching is working.In multi-turn scenarios, re-prefilling the entire history on every request inflates TTFT badly. Check the prefix cache hit rate in the log.

Output That Repeats, Garbles, or Never Stops

  • Repetition: most often numerical overflow from loading BF16 weights as FP16 — switch to --dtype bfloat16; second most common, max_tokens set far too high with a model that does not converge.
  • Garbled output: almost always a corrupted weight file. Re-run the three-layer verification from section 3.5, especially the sha256 comparison.
  • Never stops: check the stop sequences and max_tokens in the sampling parameters; if you use a chat template, confirm it loaded correctly (use --chat-template to point at a file).

Streaming Responses That Hang

First determine whether the problem is server-side or in the path:

  • Direct curl -N http://127.0.0.1:8000/v1/chat/completions also hangs — server-side problem; check the engine log for preemption or errors.
  • Direct works but nginx hangs — almost certainly proxy buffering. Verify proxy_buffering off is in effect and that proxy_read_timeout is long enough (the default 60 seconds is not enough for long generations).
  • Both look fine but the client appears stuck — check the client's own buffering, and whether an intermediary rewrote the X-Accel-Buffering header.

NCCL Hangs in Multi-GPU Runs

The symptom is a process stuck at initialization, with NCCL error or "watchdog caught collective operation timeout" in the log. Common causes and handling:

CauseHow to verifyWhat to do
Insufficient container shared memoryCheck whether --ipc=host or --shm-size is setAdd the parameter and recreate the container
P2P direct access unavailableRestart with NCCL_DEBUG=INFO and read the logRetry with NCCL_P2P_DISABLE=1
InfiniBand not enabledInspect NCCL_IB_DISABLE and NIC stateDisable IB and fall back to TCP to prove functionality, then tune
Mixed GPU modelsnvidia-smi -LSplit them into separate instances

Client-Side 502 and 504

  • 502 Bad Gateway: nginx cannot reach the upstream engine. Check that the engine process is alive, the port is listening, and no firewall blocks it.
  • 504 Gateway Timeout: the engine is still working but exceeded proxy_read_timeout. Raise it above 600 seconds for long generations.
  • Connection reset: the engine was restarted or killed by the OOM killer. Check journalctl -u vllm and the kernel log for OOM records.
  • Intermittent 502: with upstream keepalive, nginx can reuse a connection that the engine closed after a restart. Add proxy_next_upstream error timeout http_502 http_503; or shorten the keepalive timeout.

Capacity Planning and Load Testing

Going live is only the start; whether you can commit to an SLA depends on load-test data. Here is a minimum viable capacity method.

Three Metrics That Must Be Kept Apart

MetricDefinitionWhat drives itWhat the user feels
TTFT (time to first token)From request sent to first token returnedQueue depth, prefill compute, prefix cache hit rateThe main component of perceived speed
TPOT (time per output token)Interval between consecutive tokensBatch size, memory bandwidth, quantization pathHow smooth the output feels
ThroughputTotal tokens generated per unit timeBatch scale, compute, parallelism strategyWhether you can serve concurrent users

A common misconception is "throughput = concurrency / TPOT". That ignores prefill cost and queueing: prefill of long prompts consumes a large share of compute, so real throughput lands below the formula.

Converting Between Concurrency and VRAM

KV per request (GB) ≈ (input tokens + reserved output tokens) × bytes per token / 2^30

supported concurrency ≈ available KV cache (GB) × 2^30 ÷ (KV per request × 2^30)

You can invert the "GPU KV cache size: 243712 tokens" line from the startup log. If an average request occupies 8192 tokens (6000 in, 2000 out), then 243712 ÷ 8192 is about 29 concurrent requests. That is far more reliable than guessing "a hundred concurrent users".

Load Test Script

# Use the benchmark that ships with vLLM (the command name varies by version; check --help first)
python -m vllm.benchmarks.benchmark_serving \
  --backend vllm \
  --base-url http://127.0.0.1:8000 \
  --model deepseek-v3 \
  --dataset-name sharegpt \
  --request-rate inf \
  --num-prompts 200 \
  --max-concurrency 32

Three things to get right: use a realistic input length distribution (a test made of 10-token requests and one made of 8K requests produce opposite conclusions); ramp up gradually (concurrency 1, 4, 16, 32, 64, so you can see the knee); and watch the engine log during the run for RECOMPUTE records and for TTFT rising exponentially.

Capacity Conclusion Table

Observed behaviorWhere the bottleneck isFirst action
High TTFT, low GPU utilizationScheduling / KV cacheLower --max-model-len; enable prefix caching; reduce concurrency
High TTFT and high TPOT, GPU utilization near 100%ComputeMove to FP8/INT4; add GPUs; shorten inputs
Stable TPOT but throughput will not scaleNot enough concurrencyRaise --max-num-seqs, provided KV cache allows it
Many RECOMPUTE records during the testKV cache insufficientReduce --max-num-seqs or --max-model-len and stabilize before chasing throughput

Security and Compliance Boundaries

Self-hosting turns "data never leaves our premises" into reality, and moves the security responsibility to whoever deploys. Treat the following as hard requirements.

Sensitivity of Weights and Artifacts

  • Official weights are usually publicly downloadable, but your fine-tuned weights, LoRA adapters, and anything derived from production data are internal assets and belong under access control and auditing.
  • Model directories should be mounted read-only (the :ro in the compose file above) so a running process cannot modify weights by accident.
  • Inference logs may contain request content by default. Enabling --disable-log-requests stops the engine from printing every prompt, which is mandatory in compliance-sensitive environments.

Redacting Logs

If you must keep request logs for troubleshooting, redact at the gateway:

# nginx logs metadata only, never the request body
log_format llm '$remote_addr - $upstream_addr [$time_local] '
                '"$request" $status $body_bytes_sent '
                'rt=$request_time urt=$upstream_response_time '
                'upstream_status=$upstream_status';
access_log /var/log/nginx/llm_access.log llm;

For stricter environments, disable $request_body in the access log entirely and replace the Authorization header. nginx does not log request headers by default, but as soon as you reference $http_authorization in a log format your API key ends up in the log file.

Network Exposure Boundaries

Three hard rules: the engine port binds only to localhost or an internal address; nginx is the only external entry point and it must have TLS plus authentication plus rate limiting; and requests from different tenants or security domains must not share an engine instance, because vLLM has no native multi-tenant isolation and quota control can only live in the gateway.

Third-Party Dependencies and Image Sources

In offline or internal environments, run a private registry and pin images by digest; never pull latest in production. The same applies to PyPI: archive pip download output internally and lock sha256 hashes. Supply-chain risk is real here, because a tampered torch wheel can take over every inference request.

Boundary Conditions and Scenarios Where This Does Not Apply

What This Article Does Not Cover

  • Fine-tuning and training: LoRA/QLoRA training flows and the resource needs of full-parameter DeepSeek fine-tuning are out of scope. This article covers serving existing weights.
  • Multi-node cluster scheduling: what is described here is single-node (possibly multi-GPU). Topology-aware scheduling, failure domains, and weight placement belong to a dedicated inference platform.
  • AMD and CPU paths: ROCm and CPU-only deployments differ substantially in parameter semantics and optimization paths.
  • The internals of quantization algorithms: calibration mathematics, error compensation, and mixed-precision strategies are out of scope; only the engineering choice is discussed.

When You Should Not Self-Host

SituationRecommendationReason
Low call volume (under a few thousand requests per day)Use the official APIBuying and operating one GPU costs far more than API fees
No dedicated operations staffPrefer a hosted inference service or the official APISelf-hosting means owning drivers, weights, monitoring, and on-call duty
You need the strongest model capabilityUse the official APINew-model inference optimizations land upstream first; self-hosted support lags
Data must not leave the internal networkSelf-host — this is the core motivationThere is no alternative
Long-context calls are expensiveEvaluate official cache pricingCache-hit pricing is often cheaper than your own compute

Hybrid Deployment Patterns

In practice "all self-hosted" and "all API" are both rare. Routing by data sensitivity and task difficulty is the norm:

  • Sensitive data goes local: requests involving personal information, trade secrets, or unpublished financials route to the internal cluster.
  • Routine traffic goes to the official API: public-knowledge Q&A and ordinary writing tasks use the hosted API and benefit from cache-hit pricing and the newest models.
  • The routing layer is the critical piece: a lightweight router dispatches by content and policy, and it must keep model aliases, parameter semantics, timeouts, and retry behavior consistent across both sides — otherwise you cannot tell a routing bug from a model bug during an incident.

Freshness of Version Information

One last emphasis: version numbers, parameter names, default values, and log wording in this article may already have changed. Before deploying, confirm the real behavior of your installed version with these three commands and record the output in the deployment document:

vllm serve --help | grep -A2 -E "max-model-len|max-num-seqs|gpu-memory-utilization"
python -c "import vllm; print(vllm.__version__)"
pip show vllm | grep -E "Requires"

Pre-Launch Checklist

Environment and Dependencies

  • Driver version is sufficient and nvidia-smi is clean
  • torch.cuda.is_available() is True and torch.version.cuda matches the installed wheel
  • GPU compute capability confirmed; availability of FP8 and Marlin paths known
  • vLLM, PyTorch, transformers, tokenizers, and numpy versions pinned and recorded
  • For multi-GPU, --ipc=host or sufficient --shm-size verified

Weights and Integrity

  • Repository name confirmed to match the target model
  • No safetensors file smaller than 1KB (rules out LFS pointers)
  • sha256 manifest verified and archived
  • config.json consistent with the weights
  • A real load test has been performed
  • Enough disk headroom (model size × 1.5)

Service and Parameters

  • --dtype bfloat16; fp16 not used by mistake
  • --max-model-len set from real workload needs, not the model maximum
  • --max-num-seqs set explicitly and not above the "Maximum concurrency" from the startup log
  • --served-model-name is a stable alias
  • Startup log confirmed for GPU KV cache size and Maximum concurrency
  • Both regular and streaming requests verified

Production and Operations

  • The engine port is not exposed to the public internet
  • API keys configured at both gateway and engine layers
  • Gateway rate limit set below the engine concurrency ceiling
  • Liveness and readiness use different endpoints
  • Shutdown uses SIGTERM with a timeout longer than the drain time
  • Graceful shutdown window configured for systemd or Kubernetes
  • Monitoring connected: TTFT, TPOT, queue depth, preemption count, 5xx rate, restart count
  • Logs contain neither request content nor API keys
  • A working rollback path exists (two instances or a version snapshot)
  • An offline golden set exists for regression testing

Conclusion: Treat Deployment as a Chain You Can Regression-Test

The hard part of deployment was never getting the service to run; it is making that state reproducible, observable, and reversible. That is why this article split deployment into four stages and required a verifiable output from each one.

Minimum Landing Order

If time is short, work in this order, since each step is a prerequisite for the next:

  1. Environment self-check (section 2) — confirm the version matrix and archive the baseline output.
  2. Weights and verification (section 3) — all three verification layers pass; this step cannot be skipped.
  3. Minimal runnable deployment (section 7) — one instance, simple parameters, get curl working.
  4. Quantization and parameter tuning (sections 6 and 10) — decide the precision tier and context length using real business samples.
  5. Production hardening (section 5) — auth, rate limits, probes, graceful shutdown, monitoring, rolling upgrades.
  6. Load testing and capacity sign-off (section 10) — obtain TTFT, TPOT, and throughput numbers, then commit to an SLA.

The Three Decisions Most Often Overlooked

  1. Keep the model alias stable.Once --served-model-name is hardcoded in business code, changing models becomes a fleet-wide change.
  2. Set context length from the workload, not from the model maximum.Every extra doubling of --max-model-len halves the concurrency you can support, and most workloads never come close to that length.
  3. VRAM is a concurrency budget, not spare capacity.Setting --gpu-memory-utilization to 0.95 feels tidy, but it actually hides your concurrency capacity — which is exactly the class of problem that is hardest to diagnose in production.

Get these three right, and most deployment problems surface during load testing instead of during customer complaints.