Design a Globally Scalable, High-Availability Generative AI Serving Platform
Machine LearningModel answerLast updated
Design a production-grade infrastructure for real-time generative AI inference that supports streaming, low-latency SLOs, multi-region failover, and efficient GPU utilization.
Design an enterprise-grade inference platform for hosting large language models (LLMs) at global scale. The system must support real-time token streaming, meet strict latency service-level objectives (SLOs), and maintain high availability even during regional infrastructure outages or sudden traffic spikes.
Operational Requirements & Goals
- API & Functionality: Provide a low-latency streaming endpoint (
POST /v1/chat/completions) supporting multiple model sizes (e.g., 8B and 70B parameter models), configurable decoding parameters, context prefix reuse, and multi-tenant rate limiting. - Performance Constraints:
- Time to First Token (TTFT): $p_{99} < 1.0\text{ s}$
- Time Per Output Token (TPOT): $p_{99} < 50\text{ ms}$
- Availability Target: 99.95% uptime globally.
- Target Throughput: 2,000 requests/second globally at peak (average 1,000 prompt tokens and 300 output tokens per request).
- Core Architectural Areas to Address:
- High-level platform architecture and request flow.
- Inference execution strategies (batching, KV cache management, prefill vs. decode disaggregation).
- Smart request routing (prefix-aware hashing, load-based load balancing).
- Autoscaling metrics, GPU topology-aware scheduling, and cold-start mitigation.
- Multi-region disaster recovery and active-active failover handling.
- Release management (canary deployments, shadow traffic, immutable artifacts).
Hints
Hint 1
Quantify KV cache memory footprints alongside compute bounds; memory bandwidth and capacity are almost always the primary bottlenecks in LLM generation.
Hint 2
Contrast static batching with continuous/in-flight batching and explain why prefill and decode phases benefit from compute/memory disaggregation.
Hint 3
Differentiate standard CPU/memory autoscaling metrics from LLM-specific signals like KV-cache block usage and pending queue wait time.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & System Scale
Functional Requirements
- Streaming API: Server-Sent Events (SSE) interface streaming tokens as they generate.
- Model Routing: Multi-model execution (e.g., fast 8B tier, flag-ship 70B tier) with explicit snapshot/version pin support.
- Context Preservation: Efficient handling of long context windows and common system prompts.
- Tiered Tenants: Rate-limiting and priority queuing based on tenant entitlements (e.g., interactive real-time vs. offline batch).
Scale & Back-of-the-Envelope Estimation
- Traffic Load: Peak $2,000 \text{ req/s}$.
- Input throughput: $2,000 \times 1,000 = 2,000,000 \text{ prompt tokens/s}$ (Compute-bound prefill).
- Output throughput: $2,000 \times 300 = 600,000 \text{ generation tokens/s}$ (Memory bandwidth-bound decode).
- KV Cache Sizing (70B Model):
- Model uses Grouped-Query Attention (GQA): 80 layers, 8 KV heads, head dimension 128.
- Per-token KV cache memory (FP16): $2 \text{ (K+V)} \times 80 \times 8 \times 128 \times 2 \text{ bytes} \approx 327.68 \text{ KB/token}$.
- For a 4,000-token context window: $\approx 1.31 \text{ GB}$ per concurrent request.
- Takeaway: A node's concurrency limit is defined by available GPU VRAM allocated to PagedAttention KV blocks, not purely by compute FLOPs.
2. Platform Architecture
┌─────────────────────────────────────────┐
│ Client │
└──────────────────┬──────────────────────┘
│ HTTPS / SSE
▼
┌─────────────────────────────────────────┐
│ Global Anycast / GeoDNS │
└──────────────────┬──────────────────────┘
│
┌──────────────────────────┴──────────────────────────┐
▼ (Region A) ▼ (Region B)
┌───────────────────────────────┐ ┌───────────────────────────────┐
│ Regional L7 Gateway │ │ Regional L7 Gateway │
│ (Auth, Token-Rate Limit) │ │ (Auth, Token-Rate Limit) │
└───────────┬───────────────────┘ └───────────┬───────────────────┘
│ │
▼ ▼
┌───────────────────────────────┐ ┌───────────────────────────────┐
│ Prefix & KV-Aware Router │ │ Prefix & KV-Aware Router │
└───────────┬───────────────────┘ └───────────┬───────────────────┘
│ │
┌───────┴──────────────────┐ ┌───────┴──────────────────┐
▼ ▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Prefill Pool │ │ Decode Pool │ │ Prefill Pool │ │ Decode Pool │
│ (Compute-Int) │ │ (Memory-Int) │ │ (Compute-Int) │ │ (Memory-Int) │
└───────────────┘ └───────────────┘ └───────────────┘ └───────────────┘
Request Lifecycle
- Edge Gateway: Validates authentication tokens, extracts tenant tier, checks token-bucket rate limits (Tokens-Per-Minute and Requests-Per-Minute), and parses payload.
- Prefix-Aware Smart Router: Hashes the prompt system context. Routes the request to a worker node holding matching KV cache blocks (prefix caching) while ensuring node queue depth remains within bounds.
- Disaggregated Serving Engine:
- Prefill Engine: Executes the parallel forward pass on input prompt tokens. Computes initial KV states.
- KV Transfer: Streams generated KV blocks via RDMA / RoCE to designated Decode workers.
- Decode Engine: Iteratively generates tokens using continuous batching until stopping criteria are reached.
3. Serving Optimization & Worker Mechanics
Continuous Batching & Memory Allocation
Traditional static batching forces workers to wait for the slowest sequence in a batch to finish, leaving GPUs idle.
- Iteration-Level (Continuous) Batching: Steps the engine forward one token at a time across all active prompts. Completed requests are evicted immediately, and pending requests are inserted into the current iteration step.
- PagedAttention: Non-contiguous physical allocation of KV cache blocks (similar to virtual memory page tables in OS design). Eliminates memory fragmentation and enables dynamic KV allocation across dynamic sequence lengths.
Prefill/Decode Disaggregation
- Problem: Prompt processing (prefill) is compute-heavy ($O(N^2)$ cross-attention scaling over sequence length $N$), whereas token generation (decode) is memory-bandwidth bound. Mixing both on the same GPU instance causes prefill spikes to stall decoding iterations, degrading the $p_{99}$ TPOT SLO.
- Solution: Split hardware clusters:
- Prefill Nodes: Provisioned for maximum compute utilization (e.g., high tensor parallelism, short duration per batch).
- Decode Nodes: Optimized for high VRAM capacity and memory bandwidth.
- Workers stream KV caches asynchronously across high-speed interconnects (NVLink/NVSwitch intra-node, RoCE v2 inter-node) prior to starting the generation phase.
4. Autoscaling & GPU Scheduling
Scaling Signals
Standard CPU utilization or raw HTTP request counters fail for LLM inference because memory consumption varies vastly with prompt length.
- Primary Scaling Metrics:
- KV Cache Block Utilization: Percentage of allocated PagedAttention blocks currently reserved. Scaling triggers when utilization exceeds 80%.
- Pending Queue Latency: Duration requests spend waiting in the scheduling queue before prefill processing starts.
- P95 TTFT Trend: Proactively scale when prompt ingestion latency drifts beyond the baseline threshold.
Cold-Start Mitigation & Pod Scheduling
Loading a 70B FP8 model requires transferring ~70 GB of weights into GPU VRAM. Standard object-store pulls introduce 3–5 minute cold starts.
- Local Storage Pre-staging: Model weights are stored on local NVMe RAID arrays attached to Kubernetes nodes.
- Warm Standby Pools: Retain a minimum baseline of pre-warmed, active replicas to absorb step-function traffic spikes.
- Container Image Optimization: Ship inference engine frameworks (e.g., vLLM / TensorRT-LLM binaries) separately from weight volumes. Use host-path mounts for weights.
- Topology-Aware Placement: Kubernetes scheduler rules must ensure that all GPUs backing a single Tensor Parallelism (TP) rank reside within the same PCIe tree or NVSwitch domain (never cross socket boundaries or un-switched bridges for TP).
5. High Availability & Multi-Region Failover
Multi-Region Active-Active Setup
Deploy identical worker pools across 3 geographically distinct regions.
┌─────────────────────────┐
│ Client App │
└────────────┬────────────┘
│
┌─────────────┴─────────────┐
▼ ▼
┌─────────────────────┐ ┌─────────────────────┐
│ Region A (Active) │ │ Region B (Active) │
│ Capacity: 50% Peak │ │ Capacity: 50% Peak │
└─────────────────────┘ └─────────────────────┘
- Capacity Sizing: Each of the 3 regions is provisioned for ~50% of peak global demand. If one region suffers a total outage, the remaining two absorb 100% of global traffic without emergency scaling delay.
- Synthetic Health Probes: Health endpoints perform short, real end-to-end token generations every few seconds. Plain TCP/HTTP 200 health checks miss hung CUDA kernels or GPU memory allocation failures (Out-Of-Memory soft crashes).
Resiliency Under Outages
- Stateless Engine Layer: Models do not hold permanent conversation history in GPU VRAM. All context history is passed back in the request context or pulled from a globally replicated session store (e.g., DynamoDB/Cassandra).
- Graceful Degradation & Load Shedding: Under total capacity saturation:
- Shed low-priority batch traffic via HTTP
429 Too Many Requestsor HTTP503 Service UnavailablewithRetry-After. - Disable speculative decoding overhead if draft model validation contention becomes a bottleneck.
- Enforce max output token caps dynamically on non-enterprise tiers.
- Shed low-priority batch traffic via HTTP
6. Release Management & Versioning
Immutable Model Deployment Unit
Deployments treat model artifacts as immutable tuples: $$\text{Deployment Artifact} = {\text{Weights URI}, \text{Tokenizer Hash}, \text{Chat Template}, \text{Engine Version}, \text{TP/PP Config}}$$
Progressive Rollout Pipeline
- Offline Quality & Safety Gates: Benchmark regression testing against standard datasets (e.g., MMLU, toxicity filters).
- Shadow Deployment: Route real production input traffic asynchronously to the candidate release. Compare generated output distribution and performance metrics without returning candidate responses to end users.
- Canary Strategy:
- Direct 1% of production traffic to the new version pool.
- Monitor error rates, TTFT, TPOT, and model safety guardrail triggers.
- Progressively scale from 1% $\rightarrow$ 10% $\rightarrow$ 50% $\rightarrow$ 100%. Automatic rollback triggers immediately if TTFT $p_{99}$ exceeds 1s or error rate rises by $>0.05%$.
7. Operational Trade-Offs & Pitfalls
| Strategy | Trade-off / Complexity | Mitigation |
|---|---|---|
| Prefill/Decode Disaggregation | High network complexity; requires high-bandwidth RDMA between pools to stream KV states. | Fallback to monolithic worker pods (prefill + decode on same instance) for smaller models (e.g., 8B). |
| Prefix-Aware Routing | Creates sticky state in routing layer; risks hot-spotting individual worker nodes. | Implement Power-of-Two-Choices balancing; redirect traffic to least-utilized worker if target KV usage $>85%$. |
| Aggressive Quantization (FP8/INT4) | Unlocks $2\times$ memory throughput and larger batch sizes, but can introduce accuracy drift on edge cases. | Continuous shadow evaluation comparing full-precision output logits against quantized engine output. |