Chapter 25
Production Architecture, Capacity, and Reliability
On this page
- Data plane and control plane
- Artifact build and compatibility
- Startup, warmup, and readiness
- Capacity planning
- Autoscaling signals
- Observability
- Failure taxonomy
- Graceful degradation
- Rollout and rollback
- Security and abuse resistance
- Cost and energy
- Production readiness checklist
- Design Exercises
- Worked Solutions
- Further Study and Primary References
- Final Inference Principle
A fast engine becomes a dependable service only when artifacts, control planes, observability, overload, failure recovery, security, and rollout are designed around its stateful streaming behavior.
The earlier chapters examined request phases, individual mechanisms, and fleet layouts. Now the service must meet its two SLOs through bursts, failures, and rollouts. Use the lifecycle's timestamps to assign ownership and reserve capacity at each boundary. The following engine chapter then shows where these responsibilities appear in real implementations.
Data plane and control plane¶
The data plane handles live requests: gateway, tokenizer, router, scheduler, model workers, KV transfer, sampling, and stream transport. The control plane manages model and adapter artifacts, placement, configuration, health, rollout, autoscaling, quotas, and policy.
Keep routine placement and rollout management off the synchronous hot path. Workers can consume versioned configuration snapshots during a temporary management-plane outage. This does not permit stale authorization: a revocation-sensitive service still needs the authoritative check or fail-closed mechanism defined by its disclosure contract. The control plane, in turn, needs enough data-plane telemetry to stop routing to unhealthy or incompatible workers.
Define ownership at boundaries. The gateway owns authentication and client semantics; the router owns eligible placement; the scheduler owns local admission and execution order; the worker owns model state and token commit; the allocator owns KV lifetime. Ambiguous ownership produces double admission, leaked pages, or duplicate streaming during retries.
Artifact build and compatibility¶
A deployable model is a bundle, not one weight file. It may include:
- model and tokenizer with immutable digests;
- chat templates and special-token configuration;
- quantization scales and packing layout;
- compiled engines or kernels by hardware capability and shape;
- parallelism and placement metadata;
- adapter compatibility schema;
- sampling and grammar versions;
- quality, performance, and security attestations.
Build artifacts reproducibly, sign or verify them, and publish atomically. A worker should reject a partial or incompatible bundle before serving traffic. Engine caches and CUDA graphs are derived artifacts and must be invalidated when their relevant inputs change.
Deserialization is a security boundary. Safetensors stores tensor data without pickle's arbitrary-object execution model; it does not certify the model, surrounding Python code, or custom kernels. PyTorch's serialization guidance explains that weights_only=True restricts unpickling but is not a complete defense against malicious files. Do not disable a loader restriction or allowlist an unknown class simply to make an imported checkpoint open.
Fetch and inspect artifacts in a restricted build environment without production credentials. Verify a digest against an authenticated release manifest, not a checksum supplied by the same untrusted download alone. Review any required model code separately, pin dependencies, bound memory and file sizes, and promote the verified bundle. A signature identifies the signing authority; it does not establish task quality or freedom from defects.
Startup, warmup, and readiness¶
Startup includes artifact fetch, deserialization, memory allocation, weight placement, communicator creation, compilation or autotuning, graph capture, cache initialization, and warmup. Readiness should require representative model execution, not only a listening socket.
Warm the important precision, batch, context, adapter, and graph variants without trying to enumerate an unbounded shape space. Keep a fallback path for a cold shape. Record cold-start stages so autoscaling knows whether a new replica will arrive in seconds or minutes.
A rolling restart temporarily removes capacity and cache locality. Drain admissions, let bounded in-flight work finish, migrate or recompute state by policy, and maintain enough reserve that the remaining fleet does not enter overload.
Capacity planning¶
Start from the workload and SLO, not peak hardware FLOPs. For each request class estimate:
- uncached input and encoder work;
- output tokens and decode context trajectory;
- KV bytes and lifetime;
- prefix and adapter locality;
- phase service curves by batch and topology;
- arrival rate, bursts, and target percentiles.
At a stable high level, Little's Law relates average in-system concurrency N, arrival rate lambda, and average time in system T:
N = lambda T
It is an accounting identity, not a tail-latency guarantee. Use it to cross-check concurrency and memory, then use replay or a queueing model for variability and percentiles.
For an illustrative capacity check, suppose a representative replay measures a mean time in system of 25 seconds. If the replica could maintain a mean of 200 in-system requests under the SLOs, Little's Law would give lambda = N / T = 8 requests per second. The roughly 200-conversation KV estimate alone does not establish that rate: it is a resident-state limit based on a median-sized example, whereas Little's Law uses averages over the same population, including queued work. Measure mean residence, KV lifetime, and compute capacity before using the result as a plan.
For a worker, enforce:
weights + adapters + active KV + reusable KV + workspaces + reserve <= usable memory
Use usable memory after runtime and fragmentation measurements, not device nameplate capacity. For the fleet, include at least one relevant failure or maintenance scenario and the startup delay of replacement capacity.
Autoscaling signals¶
GPU utilization is a lagging and ambiguous signal. Combine:
- queued predicted prefill and decode work;
- first-token and token-cadence SLO risk;
- active and reserved KV occupancy;
- arrival forecasts and tenant quotas;
- adapter/cache locality pressure;
- replica warmup time and failure reserve.
Scale early enough to cover startup. Scale down by draining workers and accounting for cache coldness that remaining replicas will experience. Hysteresis and minimum residency avoid oscillation when traffic hovers near a threshold.
In disaggregated fleets, scale stages separately but coordinate the handoff queue and destination memory. In model-parallel groups, add or remove complete compatible groups rather than individual ranks.
Observability¶
The minimum operational view includes:
- arrival, admission, rejection, cancellation, and completion by class;
- queue delay, first-token, inter-token, and end-to-end distributions;
- input/output tokens, goodput, and batch/iteration shape;
- active, reserved, reusable, fragmented, and offloaded KV bytes;
- prefix hit tokens and actual time saved;
- adapter load, hit, eviction, and mixed-batch behavior;
- speculative proposal, acceptance, committed progress, and cycle cost;
- per-phase device time, collective skew, transfer time, and host gaps;
- errors by stage, model version, worker group, and termination reason.
Control metric cardinality. Put request IDs and exact shapes in sampled traces, not unbounded metric labels. Histograms need buckets that resolve the SLO region; averages are insufficient.
Failure taxonomy¶
Separate failures by recoverability and commit point:
- before admission: reject or route elsewhere;
- queued: retry safely if deadline permits;
- during prefill before output: retry on a compatible replica, perhaps using cached prefix;
- after streaming begins: resume only with exact committed state and transport protocol, otherwise terminate clearly;
- allocator or OOM pressure: stop admissions, reclaim, and protect active reservations;
- rank or link failure: fail the whole synchronized group and replace it;
- control-plane isolation: continue from a safe snapshot for a bounded interval;
- semantic corruption: quarantine the artifact and roll back, not merely restart.
Test fault injection at token-commit, KV handoff, cancellation, adapter eviction, and rollout boundaries. Many leaks and duplicates require a rare race, not a steady benchmark.
Graceful degradation¶
Overload actions that preserve admitted requests' generation semantics include rejecting new work, queueing within a bound, routing to a compatible replica, shedding queued batch traffic, lowering exact speculative effort, and evicting reusable caches. Disabling best-of changes candidate selection and therefore requires an authorized degradation policy, as do changes to model, precision, context, safety filters, or sampling. Record the selected mode in response metadata.
Protect already admitted requests according to the published contract, but do not let an unbounded generation monopolize the service. Enforce declared maximum output and context, tenant budgets, stream idle timeouts, and cancellation.
Rollout and rollback¶
Version model, tokenizer, templates, quantization, engine, sampling, and scheduler configuration independently but deploy them as tested compatibility sets. A rollout sequence can be:
- offline semantic and performance validation;
- shadow execution on representative traffic without user impact;
- canary by tenant or request slice with separate cache namespace;
- gradual traffic increase under automated guardrails;
- drain old state only after rollback risk falls;
- retain a tested rollback artifact and capacity path.
Compare SLOs, goodput, error slices, output distributions, safety, cache behavior, and cost. A scheduler change can alter batching and therefore RNG traces even when the model is unchanged; use the correct equivalence criterion.
Rollback is harder with state. New-version KV and adapters may be incompatible with old workers. Either keep version-sticky requests until completion, reconstruct state from tokens on rollback, or maintain an explicitly compatible format. Never reinterpret state across versions by assumption.
Security and abuse resistance¶
Enforce authentication, quotas, maximum context/output, media limits, grammar complexity limits, adapter authorization, and bounded streaming buffers before scarce accelerator work is committed. Tokenization and grammar compilation can themselves be denial-of-service targets.
Isolate tenant cache keys and adapter state. Scrub or overwrite memory according to the threat model before reallocation, avoid logging prompts or reversible low-entropy hashes, and propagate deletion across prefix caches, offload, traces, and backups.
Side channels include timing differences from cache hits, model or adapter residency, and co-tenant load. Reduce observable detail, namespace reuse, and offer dedicated capacity where stronger isolation is required.
Cost and energy¶
Useful cost metrics include accelerator-hours per good request, dollars per million accepted output tokens under an SLO, and energy per completed request. Include idle reserve, failed and rejected work, draft computation, cache transfer, and host/network resources. A higher-throughput configuration can cost more per good request if it misses latency or needs a larger failure reserve.
Optimize total service cost after semantic and reliability constraints. The cheapest kernel is irrelevant if its artifact takes too long to roll out safely or its shape specialization multiplies operational burden.
Production readiness checklist¶
| Area | Required evidence |
|---|---|
| Semantics | Reference logits/sampling/stop/constraint tests and declared approximation |
| Performance | Open-loop replay, SLO-goodput curve, cold and warm behavior |
| Memory | Capacity model, allocator invariants, cancellation and OOM tests |
| Distribution | Topology plan, collective/transfer profiling, group-failure recovery |
| Operations | Metrics, traces, alerts, runbooks, load shedding, autoscaling |
| Rollout | Versioned artifacts, cache isolation, canary guardrails, tested rollback |
| Security | Auth, quotas, tenant isolation, deletion, abuse limits, audit trail |
Design Exercises¶
- Produce a capacity plan for a new LLM endpoint from workload traces and SLOs.
- Why is GPU utilization insufficient for autoscaling?
- Design readiness, draining, and rollout for stateful model workers.
- How should the service respond to failure after some tokens have streamed?
- What observability distinguishes a scheduler regression from a kernel or network regression?
- Design an overload and rollback policy that preserves explicit semantics.
Worked Solutions¶
1. Capacity plan¶
Segment traces by prompt, output, context, model, adapter, feature, locality, and burst. Benchmark phase service curves and memory per live token on candidate group layouts. Replay open-loop arrivals to find the highest rate meeting first-token, cadence, error, fairness, and quality SLOs with KV and failure reserve. Convert this to complete replica/group count, add startup and maintenance headroom, validate one-group loss, and report cost per good request with assumptions and sensitivity ranges.
2. Autoscaling signals¶
Utilization says a device is busy, not whether useful deadlines are met or how much queued work and state is arriving. It can be high during inefficient kernels or doomed overload, and low while memory is full of paused requests. Scale from predicted queued phase work, SLO risk, KV reservations, arrival forecast, locality, warmup delay, and failure reserve, using utilization as supporting evidence rather than the control objective.
3. Stateful worker lifecycle¶
Readiness requires verified artifact identity, memory/communicator setup, representative warm execution, and registration with compatible capacity. Draining stops new admissions, preserves or transfers committed state by policy, completes bounded in-flight work, and releases cache ownership before termination. Rollout uses separate version/cache namespaces, shadow and canary stages, automatic semantic/performance guardrails, enough old capacity for rollback, and explicit treatment of in-flight KV compatibility.
4. Failure after streaming¶
Track the last logically committed and acknowledged token. Resume only if a compatible worker can reconstruct exactly the model, sampling/RNG, constraint, and KV state and the transport can suppress duplicate output. Otherwise terminate with a clear partial-response error and stable request identifier; blindly restarting could duplicate or contradict visible text. Release state idempotently and record the commit point for diagnosis and billing.
5. Observability diagnosis¶
Scheduler regressions change queue delay, batch composition, phase mixing, iteration gaps, reservation failures, and fairness while per-shape kernels may remain stable. Kernel regressions raise device time or reduce achieved bandwidth/compute for the same shape. Network regressions raise collective or KV-transfer time, skew ranks, and correlate with links or paths. Join per-request spans with scheduler decisions, shape-tagged phase timing, per-rank collectives, host gaps, and version/config identity.
6. Overload and rollback¶
Bound queues and memory reservations, reject early with retry guidance, protect admitted interactive work, shed queued batch work, reduce exact speculative effort, and enforce tenant quotas. Disabling best-of or changing model, precision, context, sampling, or safety requires an authorized degradation mode and response metadata. Rollout isolates versions and caches, preserves a warm rollback path, drains incompatible in-flight state or reconstructs from tokens, and triggers on goodput, semantic, quality, error, and memory guardrails rather than utilization alone.
Further Study and Primary References¶
- Orca: A Distributed Serving System for Transformer-Based Generative Models - iteration-level scheduling and selective batching.
- Efficient Memory Management for Large Language Model Serving with PagedAttention - paged KV memory and serving throughput.
- Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve - chunked prefill and stall-free scheduling.
- DistServe - phase disaggregation and goodput-oriented placement.
- Fast Inference from Transformers via Speculative Decoding - exact speculative sampling.
- SGLang: Efficient Execution of Structured Language Model Programs - radix prefix reuse and structured execution.
- SmoothQuant and AWQ - activation-aware quantization methods.
- Punica: Multi-Tenant LoRA Serving - shared-base multi-adapter serving.
- TensorRT-LLM Documentation - maintained engine features, KV reuse, quantization, and deployment guidance.
- NVIDIA Dynamo, LMCache, llm-d, and Mooncake - maintained reference implementations for KV-aware routing, tiered cache storage, and prefill-decode disaggregation.
- MLPerf Inference Documentation - benchmark scenarios and reproducibility requirements.
Final Inference Principle¶
The next chapter applies the running service's KV and latency estimates to vLLM, SGLang, TensorRT LLM, and cache backends. It distinguishes implementation changes from workload changes when comparing engines.