AI Infrastructure & Systems

A comprehensive, engineering-first guide to serving LLMs and modern AI models in production: continuous batching, PagedAttention, KV cache memory hierarchies, quantization trade-offs, chunked prefill scheduling, benchmarking methodology, and reference architectures.

1. Introduction — The Model Is Not the System

In modern artificial intelligence engineering, there is a dangerous cognitive trap: conflating a high-performing model checkpoint with a working production system. Offline benchmarks like MMLU, HumanEval, and LMSYS Chatbot Arena evaluate model capabilities in isolation under synthetic, unconstrained conditions — usually single-request, unbatched execution on dedicated high-memory GPUs with zero concurrency.

Production reality represents an entirely different class of engineering problems. When a model is deployed into a real software product, its mathematical capabilities mean nothing if the service exhibits unacceptable Time to First Token (TTFT), sluggish Time Per Output Token (TPOT), catastrophic tail latency under concurrent traffic spikes, GPU Out-Of-Memory (OOM) crashes, or prohibitive cloud infrastructure costs.

Serving a 70-billion-parameter language model across an 8-GPU node costs between $8,000 and $30,000 per month in cloud infrastructure. If your serving architecture wastes 60% of GPU memory on internal fragmentation or leaves tensor cores idle while stalled on high-bandwidth memory (HBM) transfers, that capability transforms into an unsustainable operational liability.

Inference Engineering is the technical discipline dedicated to bridging this chasm. It is the practice of designing, optimizing, scheduling, and observing model execution so that capable neural networks deliver measurable, predictable, cost-effective, and reliable utility under real-world multi-tenant workloads.

2. What Is Inference Engineering?

To engineer inference systems effectively, software and infrastructure engineers must clearly delineate the stages of the machine learning lifecycle:

• Model Training: Compute-bound, distributed batch optimization over weeks or months. Training workloads prioritize aggregate floating-point operations per second (FLOPs/s) and gradient all-reduce throughput across thousands of accelerators, with zero sensitivity to per-request latency.

• Model Evaluation: Offline statistical validation on static test sets. Evaluates perplexity, accuracy, and task-specific metrics without user concurrency or streaming constraints.

• Model Serving: The packaging and exposing of a model checkpoint via an HTTP/gRPC interface (e.g., standard FastAPI or Flask wrappers). Serving answers how to reach the model, but does not optimize how the model executes.

• Inference Optimization: Low-level computational speedups applied to the neural graph: kernel fusion, operator replacement (e.g., FlashAttention-2/3), post-training quantization, and compiler compilation passes (e.g., TensorRT, torch.compile).

• The Production Inference System: The holistic discipline that orchestrates dynamic scheduling, virtual memory management, request queueing, admission control, tensor parallelism, client cancellation handling, streaming delivery, and telemetry.

While this article focuses heavily on autoregressive Large Language Models (LLMs) due to their severe memory bandwidth and context-length constraints, inference engineering encompasses the broader spectrum of production AI: high-throughput embedding models (ColBERT, BGE), computer vision encoders (CLIP, ViT), speech synthesis/transcription (Whisper), and real-time tabular gradient boosted trees (XGBoost). Each workload exhibits distinct compute-to-memory ratios and SLA profiles.

3. Anatomy of a Production Inference Pipeline

Understanding a production inference service requires tracing the complete lifecycle of a request from client dispatch to token completion. Unlike traditional stateless web APIs where request processing is uniform, an LLM request alternates between two drastically different computational phases: the Prefill Phase and the Decode Phase.

The lifecycle proceeds through eight distinct architectural boundaries:

1. Client Request: An application client or SDK opens an HTTP/2 or HTTP/3 connection, sending prompt text, sampling hyperparameters (temperature, top_p), and requesting a persistent Server-Sent Events (SSE) stream.

2. API Gateway & Ingress: The gateway terminates TLS, validates API tokens, applies tenant-level rate limits, and verifies token credit balances before forwarding the payload to the inference cluster.

3. Tokenization & Input Validation: The inference frontend converts raw natural-language strings into discrete integer token IDs using Byte-Pair Encoding (BPE) or SentencePiece algorithms, prepends system chat templates, and validates that input length does not exceed maximum context boundaries.

4. Admission Control & Scheduling: The request enters a centralized priority queue. The scheduler evaluates active GPU Key-Value (KV) cache memory availability. If sufficient physical memory blocks exist, the request is scheduled for execution; otherwise, it is queued or shed under backpressure.

5. Prefill Phase (Prompt Processing): The model processes all input tokens concurrently in a single forward pass. Because the entire prompt sequence is known upfront, this phase executes dense matrix-matrix multiplications (GEMM) that heavily saturate GPU Tensor Cores (compute-bound execution with high arithmetic intensity).

6. KV Cache Allocation & PagedAttention: During prefill, the attention Key and Value projection tensors for all prompt tokens are computed and stored in GPU High-Bandwidth Memory (HBM) using non-contiguous virtual memory blocks managed by PagedAttention.

7. Decode Phase (Autoregressive Token Generation): The model enters a sequential generation loop. In each iteration, the model takes the single newly generated token, queries the historical KV cache across all prior tokens, and computes the probability distribution for the next token. This executes matrix-vector multiplications (GEMV) that are strictly bound by GPU memory bandwidth (arithmetic intensity < 5 FLOPs/byte).

8. Detokenization, Streaming & Telemetry: Output token IDs are mapped back to UTF-8 characters, evaluated against stop sequences, and pushed immediately to the client socket as SSE chunks. Generation metrics (TTFT, inter-token intervals, prompt/decode token counts) are emitted to the observability pipeline.

REQUEST LIFECYCLE FLOW
8 PIPELINE STAGES
01 · INGRESS

Client Request

HTTP POST /chat/completions with stream=true

02 · INGRESS

Gateway & Auth

TLS termination, token quotas, tenant rate limiting

03 · FRONTEND

Tokenization

BPE encode prompt, context truncation, format chat template

04 · RUNTIME

Admission & Queue

Chunked prefill planning, KV cache reservation check

05 · EXECUTION

Prefill Phase

Compute-bound parallel GEMM over prompt tokens

06 · MEMORY

PagedAttention KV

Non-contiguous block tables in GPU HBM / VRAM

07 · EXECUTION

Decode Iteration

Memory-bandwidth bound GEMV generating next token

08 · STREAMING

Stream Delivery

Detokenize logits, SSE chunk dispatch, Prometheus trace

Figure 1: Anatomy of a production LLM inference pipeline with continuous batching and PagedAttention.

4. Understanding the Metrics That Matter

Traditional web applications measure performance primarily through request-response latency (e.g., p95 HTTP response duration). In production inference engineering, overall request duration is a coarse and deceptive metric. A 2,000-token generation request naturally takes longer than a 50-token request without indicating system degradation.

Production inference systems must be evaluated across distinct, fine-grained metrics:

• Time to First Token (TTFT): The duration from when the client submits the HTTP request to when the first generated token arrives at the client socket ($T_{\text{first}} - T_{\text{submit}}$). TTFT is governed by ingress network latency, queue waiting time, prompt tokenization, and the prefill execution phase. For human-facing conversational applications, TTFT directly determines perceived responsiveness.

• Time Per Output Token (TPOT): The time required to generate each subsequent token during the autoregressive decode phase ($[T_{\text{finish}} - T_{\text{first}}] / [N_{\text{output\_tokens}} - 1]$). TPOT is dictated by GPU memory bandwidth and active concurrent batch size. Typical human reading speed corresponds to 15–25 tokens per second (TPOT of 40–65 ms).

• Inter-Token Latency (ITL) & Jitter: The time delta between consecutive tokens in a live stream. Even if average TPOT is 30 ms, if a long prefill request suddenly preempts the GPU, the stream can stall for 500 ms before resuming. High ITL jitter produces jarring, stuttering user interfaces.

• End-to-End (E2E) Latency: Total request turnaround: $T_{\text{E2E}} = \text{TTFT} + (N_{\text{output}} - 1) \times \text{TPOT}$. Useful for offline batch pipelines, but secondary to TTFT/TPOT in interactive products.

• Throughput (Requests/sec vs. Tokens/sec): System capacity must be bifurcated into Input Tokens per Second (prefill throughput) and Output Tokens per Second (generation throughput). High output token throughput maximizes infrastructure return on investment.

• GPU Saturation vs. Memory Utilization: A GPU running at '99% Utilization' in nvidia-smi often merely indicates that the compute cores are stalled waiting on memory transfers from HBM. Real system health requires monitoring the KV Cache Allocation Factor — the fraction of physical VRAM currently holding active KV blocks.

MetricTarget Profile (Interactive)Target Profile (Batch/RAG)Primary Hardware BottleneckKey Engineering Levers
Time to First Token (TTFT)p50 < 350 ms, p99 < 800 msp50 < 3.5 s, p99 < 8.0 sCompute bound (Tensor Cores) & Queue depthChunked prefill, Prefix caching, Tensor parallelism
Time Per Output Token (TPOT)p50 < 30 ms, p99 < 50 ms (30+ tps)p50 < 80 ms (throughput focused)Memory bandwidth bound (HBM transfer)Continuous batching, FP8 quantization, Speculative decoding
Inter-Token Latency (ITL)Standard deviation < 8 msUnconstrainedPrefill interference during decode stepsChunked prefill budget, Iteration-level scheduling
KV Cache VRAM Headroom15% - 25% safety buffer5% - 10% safety bufferGPU VRAM Capacity (80 GB per SXM GPU)PagedAttention, Grouped-Query Attention (GQA), CPU offload
Cost per 1M Output TokensOptimized for SLA complianceMinimized for maximum volumeTotal Cost of Ownership (GPU hourly rate)High continuous batch concurrency, Model distillation

Table 1: Illustrative comparison of inference performance profiles and hardware constraints across operational workloads.

5. The Core Optimization Techniques

Optimizing production inference is fundamentally an exercise in navigating hardware trade-offs between compute capacity, memory capacity, and memory interconnect bandwidth. Over the past three years, several breakthrough techniques have transformed LLM serving from a fragile academic setup into a resilient engineering discipline.

1. Continuous Batching (Iteration-Level Scheduling): Traditional deep learning serving engines relied on static batching: grouping $N$ requests together, padding all sequences to the length of the longest request, and executing forward passes until every sequence generated its end-of-sequence (EOS) token. If one request generated 1,000 tokens while others finished at 20 tokens, the short requests were trapped, wasting GPU cycles on empty padding. Systems like Orca (Yu et al., 2022) introduced continuous (iteration-level) batching: the batch is updated after every single decode step. Completed sequences are evicted instantly, and newly arrived requests are dynamically inserted into the batch without waiting for previous jobs to terminate.

2. KV Caching & Grouped-Query Attention (GQA): In standard autoregressive self-attention, generating token $t$ requires computing dot products between the current query and the key/value representations of all preceding tokens $1 \dots t-1$. Recalculating keys and values at every step incurs an intractable $O(N^2)$ computational penalty. A KV Cache retains the computed keys and values in GPU memory, reducing subsequent decode steps to $O(N)$ operations.

However, the KV cache grows linearly with context length and concurrency. The precise memory consumption per active token across a model is governed by:

$$\text{Memory}_{\text{KV}} = 2 \times 2 \times n_{\text{layers}} \times n_{\text{heads\_kv}} \times d_{\text{head}} \times \text{precision bytes}$$

For an FP16 model with 80 layers, 8 KV heads (Grouped-Query Attention), head dimension 128, each token requires $2 \times 2 \times 80 \times 8 \times 128 \times 2 = 655,360 \text{ bytes} \approx 640 \text{ KB}$. A concurrency of 64 requests running 4,000 tokens each consumes over 163 GB of pure VRAM solely for the KV cache — surpassing the entire memory capacity of two 80 GB GPUs!

3. PagedAttention & Virtual Memory Management: Prior to the landmark vLLM paper (Kwon et al., SOSP 2023), serving systems pre-allocated contiguous VRAM for each request based on its maximum potential context length (e.g., allocating a full 4,096-token buffer even if the request only used 300 tokens). This caused severe internal fragmentation (wasting 60–80% of GPU memory) and external fragmentation. Inspired by operating system virtual memory, PagedAttention divides the KV cache into fixed-size physical memory blocks (typically 16 or 32 tokens). Logical sequence blocks are mapped to non-contiguous physical blocks via a dynamic block table. This eliminates fragmentation, bringing wasted memory under 4% and enabling multi-turn copy-on-write sharing.

4. Model Quantization: Floating-point representations dictate weight footprint and memory bus transfer speeds. In decode phases, where throughput is strictly memory-bandwidth bound, reading 140 GB of FP16 weights across HBM limits generation speed. Quantization compresses numerical representations:

• Weight-Only Quantization (AWQ, GPTQ - INT4/INT8): Compresses weights while keeping activations in FP16/BF16. Reduces weight size by 50–75%, cutting memory transfer time in half during the decode phase.

• Weight-and-Activation Quantization (FP8, SmoothQuant INT8): Quantizes both weights and input activations to 8-bit formats. This unlocks high-throughput FP8 Tensor Core matrix operations, dramatically accelerating the compute-bound prefill phase on modern architectures (NVIDIA Hopper H100/H200, Ada Lovelace).

• Trade-offs: Quantization can degrade reasoning capabilities, code syntax generation, and long-context perplexity if outlier channels are not carefully preserved.

5. Speculative Decoding: Introduced by Leviathan et al. (2023), speculative decoding pairs a small, fast 'draft model' (e.g., a 1B–3B parameter model) with a large 'target model' (e.g., a 70B parameter model). The draft model speculatively generates $K$ candidate tokens quickly. The large target model then evaluates all $K$ candidates simultaneously in a single parallel forward pass using modified rejection sampling. If $m \le K$ tokens are accepted, the system generates $m+1$ tokens in the time of a single large model step. Speculative decoding provides genuine speedups (1.5x–2.5x) under low concurrency, but its benefits vanish under high concurrent batches where the GPU is already compute-saturated.

6. Parallelism Strategies (TP vs. PP): When a model checkpoint exceeds the memory of a single GPU (e.g., a 70B model in 16-bit precision requires ~140 GB, exceeding an 80 GB GPU):

• Tensor Parallelism (TP): Shards individual linear weight matrices across GPUs within the same server node. Each attention head or MLP row is computed in parallel, followed by an All-Reduce collective communication step across NVLink (900 GB/s on H100). TP introduces microsecond-level synchronization overhead; running TP across PCIe or network switches causes catastrophic latency penalties.

• Pipeline Parallelism (PP): Partitions sequential transformer layers across separate nodes or machines. Requests pass sequentially through pipeline stages. While PP requires lower interconnect bandwidth, it suffers from 'pipeline bubble' overhead where GPUs sit idle waiting for preceding stages.

7. Automatic Prefix Caching (Radix Attention): Many production applications feature heavily repeated prompts: multi-tenant system instructions, API documentation context in RAG applications, or prior dialogue history in chatbots. Prefix caching indexes KV blocks in a Radix Tree. When a new request arrives with a matching prefix, the engine bypasses the prefill phase entirely, reusing the pre-computed KV states directly from VRAM. This drops TTFT from hundreds of milliseconds to under 15 milliseconds for cached contexts.

BASHProduction vLLM engine configuration demonstrating memory allocation, chunked prefill, and prefix caching parameters
# Launching production-grade vLLM server with advanced optimizations:
# - Chunked prefill to eliminate ITL jitter
# - Automatic prefix caching for multi-turn conversations
# - Tensor parallelism across 4x NVLink-connected GPUs
# - FP8 KV caching for memory footprint reduction

python3 -m vllm.entrypoints.openai.api_server \
  --model meta-llama/Llama-3.1-70B-Instruct \
  --tensor-parallel-size 4 \
  --max-model-len 8192 \
  --gpu-memory-utilization 0.92 \
  --enable-chunked-prefill \
  --max-num-batched-tokens 2048 \
  --enable-prefix-caching \
  --kv-cache-dtype fp8 \
  --host 0.0.0.0 \
  --port 8000

6. Scheduling, Queueing, and Admission Control

A common architectural misconception is assuming that inference latency is purely determined by the raw arithmetic speed of GPU hardware. In production, serving performance is dominated by scheduling policies and queue dynamics.

The core difficulty arises from extreme prompt and output variance. Unlike standard database transactions that exhibit predictable execution envelopes, LLM requests are bimodal: one user submits a 50-token query expecting a 500-token answer, while another submits a 15,000-token PDF prompt expecting a concise 50-token summary.

In a naive continuous batching engine, inserting a 15,000-token prompt into the active batch monopolizes the GPU Tensor Cores for several consecutive iterations. Active conversational decode requests are starved, causing their Inter-Token Latency to spike from 25 ms to 800 ms — a phenomenon known as Decode Starvation.

Modern serving runtimes mitigate this through Chunked Prefill (e.g., Sarathi-Serve, Agrawal et al., OSDI 2024). Instead of processing a massive prompt in one giant step, the prefill is split into bounded chunks (e.g., 512 tokens) and scheduled alongside decode tokens within each forward pass. This flattens latency variance and preserves tight ITL guarantees.

Beyond iteration scheduling, a robust inference service requires rigorous Admission Control at the application boundary:

• Bounded Queuing & Load Shedding: Never allow an unbounded in-memory request queue. When queue wait times exceed defined user SLA deadlines (e.g., TTFT budget of 2 seconds), immediately return HTTP 429 (Too Many Requests) or route overflow to a secondary serverless fallback provider.

• Client Cancellation Propagation: If a user closes their browser window or navigates away while a generation is in progress, the edge server must detect the socket disconnect and signal cancellation downstream to the inference scheduler. Without cancellation propagation, the GPU worker will blindly continue computing tokens until reaching maximum length, burning valuable VRAM and compute cycles on discarded output.

• Prioritization & Fairness: Production platforms must separate interactive conversational traffic from background asynchronous batch tasks. Batch indexing jobs should be assigned lower queue priority and prefill budgets to ensure interactive user TTFT is never compromised.

PYTHONFastAPI streaming endpoint implementing admission control and immediate client disconnect propagation to abort GPU execution
import asyncio
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse

app = FastAPI()

@app.post("/v1/chat/completions")
async def chat_stream(request: Request):
    # 1. Admission Control: Check system saturation before accepting
    if global_scheduler.is_saturated():
        return {"error": "Server overloaded. Please retry with backoff."}, 429

    payload = await request.json()
    request_id = payload.get("id", str(uuid.uuid4()))

    async def token_generator():
        try:
            # Enqueue request to vLLM engine
            stream = await engine.generate(payload["prompt"], request_id=request_id)
            async for token in stream:
                # 2. Cancellation Check: Abort GPU computation if client disconnected
                if await request.is_disconnected():
                    await engine.abort(request_id)
                    break
                yield f"data: {json.dumps({'text': token})}\n\n"
        except asyncio.CancelledError:
            # Handle task cancellation
            await engine.abort(request_id)
            raise

    return StreamingResponse(token_generator(), media_type="text/event-stream")

7. Choosing an Inference Serving Stack

Selecting an inference serving stack requires matching application latency requirements, traffic scale, internal engineering bandwidth, and hardware infrastructure. There is no universally superior engine; each stack occupies a distinct Pareto point regarding throughput, flexibility, and operational complexity.

• vLLM: The de-facto open-source standard for flexible LLM serving. Implemented in Python with performance-critical CUDA/C++ kernels. Excellent community momentum, native support for PagedAttention, chunked prefill, speculative decoding, and automatic prefix caching. Ideal for teams requiring broad open-weights architecture support and fast iteration cycles.

• NVIDIA TensorRT-LLM: NVIDIA's enterprise-grade serving compiler and runtime. Deeply fused CUDA kernels, heavily optimized in-flight batching, and custom GEMM algorithms engineered specifically for NVIDIA Tensor Core architectures. Delivers the absolute highest raw tokens-per-second throughput on pure NVIDIA hardware, but demands higher operational complexity, specialized build containers, and slower model weight reloading times.

• Hugging Face Text Generation Inference (TGI): A battle-tested production solution combining a high-performance Rust web frontend with a PyTorch/FlashAttention backend. Excellent enterprise integration with Hugging Face Hub, built-in OpenTelemetry tracing, and clean Docker deployment targets.

• Native Framework Serving (PyTorch / torch.compile): Useful for academic prototyping, model architecture development, and custom research. Lacks native multi-request continuous batching and virtualized KV memory management, making it unsuitable for high-concurrency production deployments.

• Managed Cloud APIs (AWS Bedrock, Azure AI, Groq, Together, Fireworks): Fully managed serverless or provisioned throughput endpoints. Eliminates cluster provisioning, cold-start management, and GPU hardware contracts. Ideal for fast time-to-market and low-to-medium variable workloads, but presents data governance constraints, strict provider rate limits, and higher long-term operational costs at sustained enterprise scale.

Serving StackPrimary Use CaseHardware & DeploymentOperational ComplexityFlexibilityKey Trade-offs
vLLMProduction LLM serving, fast multi-model deployment, research-to-prod transitionNVIDIA (A100, H100, L40S, RTX), AMD ROCm, AWS Neuron; standard Docker / K8sModerate (Clean Python/C++ codebase, OpenAI-compatible REST server)Very High (Rapid support for newly released architectures and custom samplers)Slightly lower raw hardware saturation than TRT-LLM; higher memory management agility
TensorRT-LLMUltra-high-throughput enterprise serving on dedicated NVIDIA clustersStrictly NVIDIA GPUs with high Tensor Core capability (Hopper, Ada, Ampere)High (Requires engine compilation, specialized C++ runtime, Triton backend)Moderate (Model architectures must be supported by NVIDIA TensorRT converters)Maximum tokens/sec and lowest TPOT; rigid deployment and slower iteration cycles
Hugging Face TGIEnterprise deployments integrated with Hugging Face model registry and security toolsNVIDIA GPUs, Intel Gaudi, AWS Inferentia; official OCI container imagesLow to Moderate (Single binary Rust orchestrator, clean CLI flags)High (Standard transformer support, built-in watermark and guardrail hooks)Strong token streaming performance; slightly less bleeding-edge research features than vLLM
Native PyTorchLocal debugging, proof-of-concept features, custom architectural researchAny hardware supporting PyTorch (Metal, CPU, CUDA, ROCm)Very Low (Standard Python imports, native debugging tools)Unrestricted (Can execute arbitrary custom PyTorch tensors and hooks)Severe lack of continuous batching, memory fragmentation, unusable under concurrency
Managed Cloud APIsRapid prototyping, zero-ops infrastructure, variable or spiky demandServerless multi-tenant cloud hardware managed by vendorMinimal (REST API integration, zero cluster management)Low (Constrained to vendor-hosted models and proprietary parameters)Instant time to market; higher unit cost at scale, external data privacy boundaries

Table 2: Technical evaluation matrix of leading LLM serving engines and operational deployment models.

8. Benchmarking Inference Systems Correctly

Inference benchmarking in the AI community is notoriously plagued by 'benchmark theater': marketing claims quoting astronomical tokens-per-second numbers achieved under unrealistic conditions (e.g., batch sizes of 512, synthetic prompt lengths of 8 tokens, zero streaming, and ignoring tail latency entirely).

A reproducible, engineering-grade benchmark must simulate realistic production constraints:

1. Open-Loop vs. Closed-Loop Traffic: A closed-loop test maintains a fixed number of concurrent virtual clients: client $i$ issues a request, waits for the complete response, and immediately fires another. This artificially masks queue buildup. Real-world traffic is open-loop: requests arrive according to a stochastic Poisson process independent of when the server completes previous requests. Benchmarking under open-loop arrival rates exposes true system saturation and queue collapse points.

2. Bimodal Prompt Distributions: Testing solely with uniform 512-in / 128-out requests produces deceptively smooth latency graphs. Real benchmarks must sample from realistic distributions: short conversational queries (100-in / 300-out) mixed with long document summarization (4,000-in / 200-out).

3. Rigorous Warm-Up Periods: GPU kernels require compilation, CUDA contexts must initialize, and memory page tables must allocate memory pools during initial forward passes. Discard all measurements from the first 2–5 minutes of load testing to measure steady-state performance.

4. Percentile Distributions (p50, p95, p99): Never report mean latency alone. A system with a mean TTFT of 200 ms but a p99 TTFT of 3,500 ms will severely degrade user retention during traffic peaks.

Test ScenarioWorkload ProfileTarget Concurrency / RateKey Metrics to CaptureFailure Condition to Monitor
Interactive Chat PeakShort prompt (150 tokens), Medium output (350 tokens)Poisson arrival: 10 to 80 req/secTTFT (p50/p95/p99), TPOT, ITL jitterTTFT exceeding 800 ms SLA, Queue depth buildup
RAG Document IngestionLong prompt (4,000 - 8,000 tokens), Short output (150 tokens)Batch concurrency: 16 to 48 concurrent workersPrefill token throughput (tok/sec), VRAM allocationGPU Out-Of-Memory (OOM) crash, Decode starvation
Mixed Production RealismBimodal mix: 70% Short Chat, 30% Long RAGPoisson arrival: 25 req/sec with random burst spikesp99 TTFT, p99 TPOT, Error rate (HTTP 429/500)Memory page allocation failure, Thread starvation

Table 3: Recommended experimental matrix for reproducible inference system load testing.

BASHExecuting an open-loop Poisson arrival benchmark with realistic multi-turn prompt distributions
# Reproducible open-loop benchmark using vLLM's official benchmark client
# Simulates a Poisson arrival process with realistic ShareGPT prompt distributions

python3 -m vllm.benchmarks.benchmark_serving \
  --backend vllm \
  --host localhost \
  --port 8000 \
  --dataset-name sharegpt \
  --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json \
  --request-rate 25.0 \
  --num-prompts 1000 \
  --max-concurrency 64 \
  --metric-percentiles 50,90,95,99 \
  --save-result \
  --result-dir ./benchmark_results/

9. Production Reliability and Observability

Operating an inference cluster in production requires elevating reliability and observability to the level of standard Tier-1 infrastructure. When serving large language models, failures manifest differently than in traditional microservices.

The Four Golden Signals of Production Inference:

• Latency Distributions: Separate instrumentation for TTFT, TPOT, and overall E2E duration. Monitor p99 latency regressions continuously.

• Traffic & Token Velocity: Total requests per second, active concurrent sequences, prompt tokens/sec, and generated tokens/sec.

• Error Signatures: GPU Out-Of-Memory (OOM) events, HTTP 429 rate limit triggers, client disconnect terminations, and CUDA driver kernel panics.

• Saturation Metrics: KV Cache Allocation Factor (percentage of VRAM holding active KV blocks), number of requests waiting in the scheduler queue, and host-to-device memory bus utilization.

Managing GPU Out-Of-Memory (OOM) Events: Unlike CPU processes that can swap seamlessly to disk, an unexpected GPU memory allocation fault triggers an unrecoverable CUDA kernel panic, crashing the entire model worker process and abruptly dropping all concurrent in-flight streams. Production engines prevent this by reserving a fixed VRAM allocation budget upfront (e.g., --gpu-memory-utilization 0.90) and enforcing strict admission controls that refuse new sequences when physical KV block pools are exhausted.

Liveness vs. Readiness Probes: A model container that has booted its HTTP server is not ready to serve traffic. Initializing CUDA contexts, loading 140 GB of model weights from NVMe storage into VRAM, and executing warm-up compilation passes takes between 45 seconds and 4 minutes. A readiness probe must verify that model weights are pinned in VRAM and that a dummy inference pass completes successfully before the load balancer routes production user traffic to that replica.

Autoscaling Constraints (Cold Starts): Standard Kubernetes Horizontal Pod Autoscalers (HPA) assume containers scale out in seconds. For LLMs, scaling out an 8xH100 node involves provisioning a high-end cloud VM, downloading 140 GB of safetensors checkpoints across the network, and initializing tensor parallel communicators — a cold start taking 3 to 8 minutes. Production autoscaling architectures must maintain warm standby capacity, utilize localized high-speed NVMe weight caches, and scale proactively based on queue depth metrics rather than reactive CPU/GPU utilization.

YAMLProduction Prometheus alerting rules monitoring KV cache saturation, request queue depth, and TTFT SLA breaches
# Prometheus Alerting Rules for Production vLLM Cluster
groups:
  - name: inference_sla_alerts
    rules:
      # Alert when KV Cache memory pool is nearing exhaustion (> 90%)
      - alert: HighKVCacheMemorySaturation
        expr: vllm:gpu_cache_usage_factor > 0.90
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "GPU KV Cache VRAM saturated on {{ $labels.instance }}"
          description: "KV Cache utilization is {{ $value | humanizePercentage }}. Risk of request queueing or drop."

      # Alert when requests are stuck waiting in queue (> 5 requests for over 30s)
      - alert: InferenceQueueBacklogSpike
        expr: vllm:num_requests_waiting > 5
        for: 30s
        labels:
          severity: warning
        annotations:
          summary: "Inference queue buildup on {{ $labels.instance }}"
          description: "Queue depth is {{ $value }} waiting requests. Autoscaling trigger recommended."

      # Alert when p95 TTFT breaches user SLA budget (> 1000ms)
      - alert: HighTimeToFirstTokenP95
        expr: histogram_quantile(0.95, sum(rate(vllm:time_to_first_token_seconds_bucket[5m])) by (le)) > 1.0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "p95 TTFT SLA breached (> 1.0s)"
          description: "Users are experiencing sluggish initial responsiveness."

10. An End-to-End Engineering Workflow

Engineering an inference system requires a disciplined, measurement-driven methodology. Blindly applying speculative decoding, FP8 quantization, and large batch sizes without profiling baseline constraints inevitably results in wasted engineering cycles and degraded user experiences.

Production engineering teams should follow this 10-step systematic workflow:

1. Define Latency Budgets & Target SLAs: Establish rigid user-facing constraints upfront (e.g., TTFT < 400 ms at p95; TPOT < 35 ms at p95; maximum tolerable error rate < 0.05%).

2. Characterize the Workload: Analyze expected input-to-output token ratios, peak vs. average request rates, prompt reuse potential (RAG templates vs. ad-hoc inputs), and streaming vs. batch delivery requirements.

3. Establish an Unoptimized Baseline: Deploy the model checkpoint using standard 16-bit precision on a baseline GPU topology without advanced caching. Measure baseline TTFT, TPOT, and throughput under low concurrency.

4. Select Runtime & Hardware Topology: Determine the optimal accelerator configuration (e.g., single L40S for 8B models, 4x A100 for 70B models with Tensor Parallelism) and select the serving engine (vLLM vs. TensorRT-LLM).

5. Identify the Dominant Bottleneck: Profile whether the workload is bottlenecked by compute (high prefill token volume), memory bandwidth (long decode sequences), or queue contention (unbalanced burst arrivals).

6. Apply Optimizations Incrementally: Introduce one optimization at a time: first Continuous Batching, then PagedAttention, followed by Chunked Prefill, Automatic Prefix Caching, and finally Model Quantization.

7. Run Controlled Open-Loop Load Tests: Benchmark the system using realistic Poisson arrival distributions to verify that throughput gains do not compromise tail TTFT/TPOT latency.

8. Validate Numerical Accuracy & Perplexity: Run evaluation test suites (e.g., LM-Evaluation-Harness, MMLU, GSM8K) on quantized checkpoints to verify that precision reductions did not degrade reasoning capabilities.

9. Execute Chaos & Fault-Tolerance Tests: Simulate client disconnects during generation, kill individual GPU worker processes, and trigger sudden 5x traffic surges to verify that admission control and load shedding behave gracefully.

10. Deploy Canary & Monitor Golden Signals: Roll out the optimized inference service behind a canary load balancer, monitoring real-time Prometheus histograms, GPU memory headroom, and user satisfaction metrics before full traffic migration.

Verification Criteria:

  • SLA Definition: Rigid TTFT and TPOT latency targets defined at p50, p95, and p99.
  • Admission Control: Bounded in-memory queue depth with automatic HTTP 429 backpressure handling.
  • Cancellation Plumbing: Client socket disconnects cleanly propagate to abort GPU generation iterations.
  • Memory Safety: GPU memory utilization factor set with at least 10% VRAM buffer to prevent CUDA OOM panics.
  • Chunked Prefill: Enabled to prevent decode starvation and suppress inter-token latency jitter.
  • Readiness Verification: Health probes validate that model weights are fully pinned in VRAM before routing traffic.
  • Observability Instrumentation: Prometheus exporters scraping TTFT, TPOT, and KV cache allocation factors.
  • Zero-Downtime Rollout: Rolling blue-green update strategy ensuring active streams drain gracefully before container termination.

11. A Practical Reference Architecture

To operationalize these principles, we present a resilient, modular reference architecture for a high-throughput, low-latency LLM inference service. This architecture decouples stateful client connection management from distributed GPU worker execution.

The architecture is organized across four distinct functional tiers:

• Tier 1 — Ingress & Edge Gateway: Powered by Envoy, Nginx, or an API gateway. Handles TLS termination, API key authentication, rate limiting, and request quota tracking. It exposes clean REST/gRPC interfaces and shields upstream workers from direct internet exposure.

• Tier 2 — Application Orchestration & Routing: A lightweight service (typically written in Go, Rust, or asynchronous Python/FastAPI). It performs BPE tokenization, validates context lengths, manages conversational session histories, and routes requests intelligently based on prompt prefixes. Critically, it manages persistent Server-Sent Events (SSE) connections to clients and monitors socket disconnects to trigger immediate downstream cancellation.

• Tier 3 — Inference Serving Runtime: The GPU cluster running an optimized engine (vLLM or TensorRT-LLM). Houses the iteration-level continuous batching scheduler, the PagedAttention virtual block memory manager, and model worker processes. Communicates across local GPUs via high-bandwidth NVLink interconnects using Tensor Parallelism (TP=4 or TP=8).

• Tier 4 — Weights, Storage & Telemetry: Backed by high-speed local NVMe storage arrays containing pre-converted safetensors weight files for rapid cold-start initialization, backed by an object storage model registry (S3, GCS, or OCI registry). Telemetry collectors scrape Prometheus metrics and trace token lifecycles via OpenTelemetry collectors.

Scaling Dynamics: For small deployments (e.g., internal tools or prototypes), Tiers 2 and 3 can be co-located within a single Docker container on a single GPU instance. For high-throughput enterprise platforms serving millions of tokens daily, Tiers 1 and 2 scale horizontally on elastic CPU nodes, while Tier 3 scales independently across dedicated multi-GPU accelerator clusters behind an intelligent load-balancing proxy.

PRODUCTION REFERENCE ARCHITECTURE
4 ARCHITECTURAL TIERS
1. CLIENT & INGRESS TIER
CLIENT

Client Applications

Web, Mobile, REST/gRPC SDKs

GATEWAY

API Gateway (Envoy)

Auth, TLS, Rate limits, Quotas

2. ORCHESTRATION & ROUTING
ROUTER

Inference Router

Prefix routing, admission control

PROXY

SSE Stream Proxy

Chunk buffering & disconnect abort

OBSERVE

Telemetry / Prometheus

TTFT, TPOT, VRAM metrics, OTEL

3. SERVING RUNTIME & ACCELERATORS
RUNTIME

vLLM / TRT-LLM Engine

Continuous batching & chunked prefill

MEMORY

PagedAttention KV Cache

Virtual block allocator (GPU VRAM)

HARDWARE

GPU Workers (TP=4/8)

NVLink All-Reduce tensor parallel

4. WEIGHTS & STORAGE
STORAGE

Local NVMe Weight Cache

High-speed safetensors cold start

REGISTRY

S3 / OCI Model Registry

Versioned checkpoints & configs

Figure 2: Modular reference architecture for a high-throughput, low-latency LLM inference system.

12. Conclusion — Optimize the System, Not Just the Model

Building effective AI products in production requires a profound mindset shift: the model provides the raw latent capability, but the inference system delivers the actual product experience.

A model with world-class reasoning capabilities delivers zero business value if high TTFT frustrates end users, if memory fragmentation crashes workers during traffic spikes, or if the serving architecture burns cloud capital faster than the business generates revenue. Excellence in production AI requires balancing the complete engineering equation: latency, throughput, memory, numerical quality, cost, reliability, and operational complexity.

Inference engineering is not a collection of isolated optimization tricks; it is the rigorous, systems-level practice of harmonizing hardware mechanics, virtual memory virtualization, continuous scheduling, and distributed networking. As models grow increasingly capable and context windows expand toward infinity, the competitive advantage in software will belong not to those who merely download the latest checkpoint, but to the engineers who master the systems that serve them.

13. Authoritative References & Further Reading

For engineers seeking to deepen their understanding of production inference systems, the following papers, technical specifications, and official documentation represent the foundational literature:

• PagedAttention & vLLM: Woosuk Kwon, Zhuohan Li, Siyuan Shen, et al. Efficient Memory Management for Large Language Model Serving with PagedAttention. Proceedings of the 29th ACM Symposium on Operating Systems Principles (SOSP 2023). Paper link · vLLM Documentation

• Continuous Batching & Orca: Gyeong-In Yu, Joo Seong Jeong, Geon-Woo Kim, et al. Orca: A Distributed Serving System for Transformer-Based Generative Models. 16th USENIX Symposium on Operating Systems Design and Implementation (OSDI 2022). Paper link

• Chunked Prefill & Sarathi-Serve: Amey Agrawal, Nitin Kedia, Ashish Panwar, et al. Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve. 18th USENIX Symposium on Operating Systems Design and Implementation (OSDI 2024). Paper link

• NVIDIA TensorRT-LLM: NVIDIA Developer Architecture Guide, Kernel Fusion, and In-Flight Batching Documentation. TensorRT-LLM GitHub · Official Documentation

• Speculative Decoding: Yaniv Leviathan, Matan Kalman, Yossi Matias. Fast Inference from Transformers via Speculative Decoding. International Conference on Machine Learning (ICML 2023). Paper link

• Activation-Aware Weight Quantization (AWQ): Ji Lin, Jiaming Tang, Haotian Tang, et al. AWQ: Activation-aware Weight Quantization for On-Device LLM Compression and Acceleration. MLSys 2024. Paper link

• FlashAttention-2: Tri Dao. FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning. International Conference on Learning Representations (ICLR 2024). Paper link

• Hugging Face Text Generation Inference (TGI): Hugging Face Production Inference Toolkit and Architecture Specification. TGI Documentation

Related Articles

/dragos-canary-tokens-ai-inference-supply-chain

Dragos Canary Tokens Expose Compromised AI Inference Providers: What AI Router Customers Should Do Now

A five-month Dragos investigation led by HD Moore seeded two million prompts with canary tokens across AI routers and marketplaces, uncovering three silently breached inference providers, reseller logging, and bypassed Zero Data Retention (ZDR) guarantees.

/cve-2026-123890-vmware-vcenter-auth-bypass-zero-day

CVE-2026-123890 (CVSS 9.8): VMware vCenter Zero-Day Auth Bypass Exploited by ARMORY CASTLE

Technical breakdown of CVE-2026-123890 (VMSA-2026-0009), a critical CVSS 9.8 authentication bypass in VMware Directory Service (vmdir) actively exploited as a zero-day since September 2026 and added to the CISA KEV catalog.

← Back to blog