Production-grade guide to llm serving infrastructure covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Llm serving infrastructure is the layer that translates a static model checkpoint into a responsive API. It sits between the raw weights—typically stored in formats like Safetensors or Checkpoint—and the client code that sends prompts and expects completions. This infrastructure handles model loading, request routing, tokenization, batching, KV cache management, and exposure of an HTTP or gRPC endpoint. It matters whenever a team moves beyond notebook experimentation and needs predictable latency, concurrent access, or integration with production pipelines. Without it, a model remains a research artifact; with it, the same weights can be served to thousands of users, batch-processed in jobs, or chained into retrieval‑augmented generation workflows.
The following sections are organized around common reader tasks, using standard tooling that exists across the ecosystem. No product‑specific CLI, config key, or internal mechanism is invoked.
A minimal serving deployment begins with a container that exposes an HTTP port and can locate model weights on disk. The most portable approach is a Docker run invocation that binds a model directory, publishes a port, and starts the inference engine:
docker run -d \
-p 8080:8080 \
-v /path/to/weights:/models \
--gpu all \
serving-base-image:latest \
--model-path /models/llama-2-7b \
--port 8080
The container is expected to read the --model-path argument (or an equivalent environment variable) and serve the checkpoint found there. If the image follows common conventions, it will also respect a --tokenizer-path flag or a TOKENIZER_DIR environment variable pointing to a tokenizers.json and associated files.
In a Kubernetes environment, the same stack is expressed as a Deployment and Service pair. A typical manifest does not embed product‑specific flags; instead it declares container image, resource limits, and volume mounts:
apiVersion: apps/v1
kind: Deployment
metadata:
name: llm-serving
spec:
replicas: 1
selector:
matchLabels:
app: llm-serving
template:
metadata:
labels:
app: llm-serving
spec:
containers:
- name: server
image: serving-base-image:latest
ports:
- containerPort: 8080
env:
- name: MODEL_PATH
value: /models/llama-2-7b
- name: PORT
value: "8080"
volumeMounts:
- name: models
mountPath: /models
volumes:
- name: models
persistentVolumeClaim:
claimName: model-pvc
---
apiVersion: v1
kind: Service
metadata:
name: llm-serving
spec:
selector:
app: llm-serving
ports:
- protocol: TCP
port: 80
targetPort: 8080
Apply the manifest with kubectl apply -f serving.yaml. Once the pod is running, verify readiness with kubectl wait --for=condition=ready pod -l app=llm-serving --timeout=120s.
To test the endpoint without writing client code, curl can hit the exposed port:
curl -s http://localhost:8080/health
A 200 OK response with an empty JSON body or a {"status":"healthy"} payload indicates the server is listening. If the response is 503 Service Unavailable or the connection is refused, the container likely failed to mount the model directory, encountered an unsupported checkpoint format, or hit a GPU allocation error during startup.
Once the serving process is accepting connections, clients send JSON payloads to a completion endpoint. A typical request POST looks like this:
curl -s POST http://localhost:8080/v1/completions \
-H "Content-Type: application/json" \
-d '{"prompt":"Once upon a time", "max_tokens":64, "temperature":0.7}'
The server is expected to parse the prompt field, tokenize it using the bundled tokenizer, execute the model forward pass, and return a JSON object with at least id, object, created, choices (each containing text and index), and usage. Deviations from this shape—missing choices, extra top‑level fields, or non‑JSON bodies—are common sources of client‑side parsing errors.
Many deployments add a thin reverse‑proxy or API‑gateway in front of the raw serving container. Such a proxy may enforce request size limits, API keys, or rate caps. A request that exceeds the configured requests-per-minute limit will typically receive 429 Too Many Requests with a Retry-After header. If the proxy is misconfigured to forward the Authorization header unchanged but the downstream server expects a bearer token in an Authorization: Bearer <token> format, the server may reject the request with 401 Unauthorized even though the token is valid. The mismatch lives in the header‑forwarding policy, not in the serving logic itself.
When a proxy sits between the client and the server, curl may need the --resolve flag to test against a specific host‑port combination without DNS lookup:
curl -s --resolve api.example.com:8080/127.0.0.1 http://api.example.com:8080/v1/completions \
-H "Content-Type: application/json" \
-d '{"prompt":"test"}'
Serving infrastructure must manage which model versions are resident in memory, especially when multiple models or versions coexist on the same hardware. A common pattern is a lazy‑load mechanism: the server starts with no model loaded, and the first request for a given model triggers a blocking load. The load sequence typically involves:
If the serving system supports model unload, a POST /v1/models/unload payload containing a name field can instruct the runtime to free the GPU memory associated with that model. The request may return 200 OK if the unload succeeded, or 409 Conflict if the model is currently processing a request. Attempting to unload a model that is mid‑inference can result in silent token corruption or a hard crash of the serving process, so production systems usually guard unload operations with a “drain” period that finishes in‑flight requests before releasing resources.
Swapping models often requires a rolling restart or a hot‑swap flag, depending on the engine. A rolling restart can be triggered via kubectl rollout restart deployment/llm-serving, which replaces pods one at a time, allowing the new pod to load the target model before the old one is terminated. If the new model has a different context window or tokenizer, the restart may expose mismatches: a prompt that was valid for the previous model may be truncated or tokenized differently, leading to unexpected output or 400 Bad Request responses from the server.
Concurrency is the primary lever for throughput. Most serving runtimes expose a max-concurrency or max-requests-per-instance flag. Setting this too low underutilizes the GPU; setting it too high can cause the KV cache to grow unbounded, exhausting device memory and triggering OOM kills. A practical starting point is to calculate the per‑request KV cache size:
cache-size-tokens = context-length × per‑request‑batch-size
gpu-memory-for-cache = cache-size-tokens × per‑token‑memory-footprint
If the GPU reports 24 GB of free memory and each token’s KV cache consumes approximately 0.5 MB (for a 7B model in fp16), a conservative limit of 40 000 tokens per instance leaves headroom for the model weights and prefill overhead.
Batching strategy also affects latency. Static batching collects requests up to a fixed size before executing a forward pass, which amortizes token‑level overhead across many prompts. Dynamic batching accepts requests of varying lengths and terminates the batch when the first token finishes decoding. The choice between the two is often a per‑deployment flag (e.g., --enable-static-batching or --use-dynamic-batching). Misalignment between the chosen strategy and the client’s request pattern—such as sending many short prompts with static batching set to a high size, or many long prompts with dynamic batching and a low max-batch-size—can inflate latency beyond acceptable thresholds.
GPU resource requests in Kubernetes are expressed as:
resources:
limits:
nvidia.com/gpu: "1"
memory: "16Gi"
cpu: "4"
requests:
nvidia.com/gpu: "1"
memory: "12Gi"
cpu: "2"
If the limits exceed what the node can provide, the pod enters Pending status. If requests are set too low, the scheduler may pack multiple serving pods onto a single GPU, leading to contention for memory and compute that manifests as increased latency or sporadic OOM errors. The kubectl describe pod llm-serving-abc123 output will show Status: Running but also Warnings: GPUOutOfMemory if the runtime logs capture a cache‑spill event.
A production‑ready serving stack exports at least three categories of metrics: request rate (counts per minute per endpoint), latency percentiles (p50, p95, p99 per request type), and resource utilization (GPU memory, CPU percent, VRAM‑free). Prometheus‑scrapable endpoints are typically exposed on /metrics at the HTTP port. A sample curl fetch:
curl -s http://localhost:8080/metrics | grep llm_requests_total
should return a counter line such as llm_requests_total{endpoint="/v1/completions",status="200"} 1234. If the metrics endpoint returns 404 Not Found or the response body is HTML instead of Prometheus format, the serving image may not have been built with the metrics collector, or the port mapping is incorrect.
Health checks in Kubernetes are defined via livenessProbe and readinessProbe. A common liveness probe against a serving container is:
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 10
periodSeconds: 10
If the /health route returns anything other than 200 OK, Kubernetes will restart the container. A readiness probe often probes the same route but may include an additional query parameter or differ in timeout behavior. Misconfigured probes—such as a timeoutSeconds value shorter than the model‑load duration—cause the pod to transition to CrashLoopBackOff immediately after startup, even though the server would become healthy once the model finishes loading.
Debugging a misbehaving serving instance often begins with kubectl logs -f deployment/llm-serving -c server. Typical log messages include:
Loading model /models/llama-2-7b … done in 3.2sGPU memory allocated: 18.7 GiB / 24 GiBBatching: static batch size 32, dynamic timeout 4msRequest 57 failed: tokenization error – unknown token ID 50324When logs lack detail, kubectl exec -it <pod> -- sh provides a shell inside the running container. From there, nvidia-smi reports current GPU memory allocation, and ps aux lists child processes. If the serving binary supports a --verbose or --log-level debug flag, starting a new instance with that flag can surface request‑level details such as tokenizer warnings or batch‑formation skips.
Several failure modes are easy to miss until they surface in production:
tokenizers.json dated 2023‑06 and the serving container loads a newer tokenizer from a different release, token IDs may map to different pieces, causing token ID out of range errors or silent truncation of prompts at the boundary of the new vocab.utilization% while actually being bottlenecked by prefill throughput. Adjusting max-batch-size or enabling chunked-prefill (if the engine supports it) often resolves the imbalance.docker-compose.yml or a ConfigMap) can override flags passed on the docker run command line or the container’s entrypoint. If PORT=9090 is set in a Compose file but the image expects PORT to set the listening socket, the server may bind to the default 8080 while the proxy forwards traffic to 9090, resulting in ECONNREFUSED from the client side and listen: socket bind: address already in use on the server side.model-00.ckpt, model-01.ckpt, … model-10.ckpt, the order will be 00, 01, … 09, 10 rather than 00, 01, … 09, 1, 10. This can lead to a corrupted model load or a silent fallback to a default/fallback checkpoint, especially if the engine checks for the existence of a specific shard name pattern.nvidia-smi -r or a node reboot) is often the only remediation.429 with a Retry-After header expressed in seconds. If the client library does not parse that header and instead retries immediately, the gateway may accumulate a backlog of 429 responses, eventually causing a cascading failure where the serving container receives a burst of requests beyond its concurrency cap and OOMs.Understanding these edges comes from watching the system under load, reading the runtime’s stdout/stderr logs, and correlating metric spikes with the configuration flags that control batching, cache sizing, and model‑load ordering. There is no substitute for a staged rollout—start with a single model, a single replica, and a modest concurrency target, then incrementally increase load while monitoring the per‑request latency histogram and GPU memory graphs.
This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy