LLM Deployment and Serving
From checkpoint files to an endpoint your product can call at 3 a.m. without waking anyone.
InfrastructurePrerequisites
- !GPU memory and model parallelism basics
- !Container and Kubernetes fundamentals
- !REST APIs and streaming responses
What You'll Learn
- 1Identify the four layers that make up a production serving path
- 2Pick an inference engine from throughput, latency and operational cost
- 3Explain tensor parallelism versus data parallelism and when each applies
- 4Write an autoscaling policy that reacts to queue depth, not just CPU
The path a request takes before tokens appear
A deployment is more than a model in a container. Between the user and the weights sit four layers, each with its own failure mode. The gateway handles authentication, rate limits and routing. The queue or scheduler decides which requests enter the next batch. The engine holds the model in memory and runs the forward pass. The orchestrator keeps replicas alive, restarts crashed pods and moves traffic during rollouts.
Most outages trace back to a layer nobody instrumented. If the gateway has no request queue, a traffic spike becomes an instant timeout. If the scheduler admits requests without a memory check, the engine dies with an out-of-memory error under load rather than gracefully shedding. If rollout replaces every replica at once, you get a full outage instead of a slow drain.
The design principle is that tokens are produced at a fixed rate governed by memory bandwidth, so everything in front of the engine must smooth demand rather than amplify it. Backpressure â a bounded queue, a 429 with retry-after, a capped concurrency per tenant â is a feature, not an admission of weakness.
Each layer should also degrade in a defined way when overloaded. A gateway can fall back to a smaller model for simple intents, a queue can drop or defer low-priority batch jobs, and an engine can refuse new admissions while finishing the sequences already running. Systems that degrade deliberately keep paying customers online during a spike; systems that fail all-or-nothing convert a traffic peak into an outage report.
Picking an inference engine
Four engines cover almost every production case, and the differences are operational rather than algorithmic. All of them implement continuous batching and a paged KV cache; what varies is how much control they expose and how much you maintain.
| Engine | Best for | Throughput | Ops burden | Notes |
|---|---|---|---|---|
| vLLM | High-concurrency APIs | Very high | Low | OpenAI-compatible server out of the box |
| TGI | Stable, well-supported serving | High | Low | Ships with token streaming and metrics |
| TensorRT-LLM | Latency-critical workloads | Highest | High | Requires an engine build per model shape |
| llama.cpp | CPUs, Apple Silicon, edge | Medium | Very low | Excellent for local and single-user use |
Launching an engine is a one-line decision with long consequences, because the flags you choose define your memory envelope:
# vLLM behind an OpenAI-compatible endpoint
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Llama-3.1-8B-Instruct \
--tensor-parallel-size 2 \
--gpu-memory-utilization 0.90 \
--max-model-len 8192 \
--max-num-seqs 64 \
--enable-prefix-caching \
--served-model-name assistant
Prefix caching deserves special attention for chat products: when every session starts with the same system prompt, caching the shared prefix removes most of the prefill work from each new conversation.
Fitting a model that does not fit on one GPU
Two parallelism axes exist and confusing them wastes weeks. Tensor parallelism splits individual weight matrices across GPUs so each card computes a slice of the same layer; it is mandatory when one model cannot fit in one device's memory, and it requires fast interconnects because every layer needs a collective all-reduce. Data parallelism keeps a full copy of the model on each GPU and splits the batch; it raises throughput but does nothing for a model that will not fit.
from vllm import LLM, SamplingParams
llm = LLM(
model="meta-llama/Llama-3.1-8B-Instruct",
tensor_parallel_size=2, # weights split across two GPUs
gpu_memory_utilization=0.9,
max_num_seqs=32,
)
params = SamplingParams(temperature=0.6, top_p=0.9, max_tokens=512)
outputs = llm.generate(
["Summarize the incident report.", "Draft a release note."],
params,
)
for out in outputs:
print(out.outputs[0].text)
A practical rule: use tensor parallelism only as far as memory forces you, because the communication overhead grows with every added device. Once the model fits, add replicas for throughput instead.
The API surface clients actually depend on
Teams often ship a bare POST that returns a JSON blob, then discover that clients need cancellation, streaming and partial failures handled. An OpenAI-compatible schema avoids that discovery phase: chat completions, SSE token streaming, usage counts and error codes already have a de facto contract that every SDK understands.
import openai
client = openai.OpenAI(base_url="http://llm-gateway:8000/v1", api_key="unused")
stream = client.chat.completions.create(
model="assistant",
messages=[{"role": "user", "content": "Explain paged attention."}],
stream=True,
extra_body={"timeout": 30},
)
for event in stream:
delta = event.choices[0].delta.content or ""
print(delta, end="", flush=True)
Streaming changes perceived latency more than any engine swap: users see the first characters in a few hundred milliseconds while the rest of the answer continues in the background. Pair it with a client-side timeout and an explicit cancellation path so abandoned requests free their batch slots.
Scaling replicas without multiplying the bill
Autoscaling on CPU is close to meaningless for GPU inference â the processor idles while the accelerator works. Scale on what actually predicts overload: tokens per second per replica, queue depth, and time spent waiting for a batch slot. A policy that reacts to queue length absorbs a burst before users notice, while a CPU-based policy waits until the node is already saturated.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: llm-replicas
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: llm-engine
minReplicas: 2
maxReplicas: 12
metrics:
- type: Pods
pods:
metric:
name: queue_depth
target:
type: AverageValue
averageValue: "8"
behavior:
scaleUp:
stabilizationWindowSeconds: 30
scaleDown:
stabilizationWindowSeconds: 300
Keep a floor of at least two replicas so a single node failure never leaves the endpoint cold, and scale down slowly because loading a 70B model takes minutes, not seconds. Preloading weights into a warm standby during the scale-up window turns a painful cold start into a rolling promotion.
Rollouts, health checks and what to watch
A model rollout is a data migration in disguise: the new weights change output distribution as well as performance. Canary a fraction of traffic, compare task-level metrics â not just error rates â and promote only when the new version matches or beats the incumbent on your evaluation set.
Health checks need two levels. A liveness probe that only checks the port stays green while the engine is thrashing for memory; add a readiness probe that actually runs a one-token generation and fails if it exceeds a latency threshold. The metrics worth graphing are time to first token, inter-token latency, queue depth, GPU memory utilization, batch occupancy and error rate by cause. Together they tell you whether a problem is demand, configuration or hardware â three situations that look identical when all you monitor is request count.
Cost deserves the same discipline as reliability. Attribute GPU hours to the endpoint and the tenant that consumed them, because a single unbounded summarization job can quietly double a month's bill while every latency chart still looks healthy. Teams that pair per-request cost with per-request latency make better scaling decisions than teams that discover the invoice three weeks later.
â ī¸Cold starts dominate autoscaling cost
A fresh replica can take several minutes to download and load weights. Use warm pools or pre-initialized snapshots, otherwise every scale-up event pays that tax while requests pile up in the queue.
Common Mistakes
Autoscaling on CPU utilization for GPU workloads
Fix: Scale on queue depth and tokens per second per replica â CPU stays idle while the GPU is saturated.
Setting gpu-memory-utilization to 1.0 to squeeze out capacity
Fix: Leave roughly ten percent headroom for activation memory and the KV cache, or long prompts will OOM the process.
Replacing all replicas at once during a model rollout
Fix: Canary a small slice of traffic, compare evaluation metrics, then promote gradually with a fast rollback path.
Best Practices
- Serve an OpenAI-compatible schema so existing SDKs and tools work without adapters
- Enable prefix caching whenever conversations share a system prompt
- Probe readiness with a real generation, not a TCP port check
- Track time to first token and inter-token latency separately from throughput
- Keep two warm replicas minimum and scale down far more slowly than you scale up
Key Takeaways
- Serving has four layers â gateway, scheduler, engine, orchestrator â and each needs its own metrics
- Engine choice is an operational decision: all major engines batch and page memory, few differ on quality
- Tensor parallelism solves capacity; data parallelism and replicas solve throughput
- Streaming and prefix caching change user-perceived latency more than hardware upgrades
- Autoscale on queue depth and token rate, keep a warm floor, and roll out models as canaries