Skip to content

Large Scale Infrastructure

Building systems that serve millions of users requires more than a single server. This file covers scalability patterns, distributed systems fundamentals, microservices, data pipelines, rack-scale GPU domains, tiered KV-cache offloading, automated fault recovery, database scaling, search and vector systems, observability, reliability engineering, and CI/CD.

  • A model serving 1 request per second can run on a laptop. Serving 100,000 requests per second with 99.9% availability requires distributed systems, automated failover, and carefully designed data pipelines. This file covers the patterns that bridge that gap.

Scalability

  • Vertical scaling (scale up): get a bigger machine. More CPU, more RAM, bigger GPU. Simple but has hard limits (the biggest available machine) and a single point of failure.

  • Horizontal scaling (scale out): add more machines. Each handles a fraction of the traffic. No single-machine limit, but requires: load balancing (file 01), data partitioning, and handling distributed state.

  • Stateless services are horizontally scalable by default. Add more instances behind a load balancer. A model inference server that loads weights at startup and processes requests independently is stateless — any instance can handle any request.

  • Stateful services (databases, KV-cache, feature stores) are harder to scale. The state must be partitioned across machines (sharding, file 01) and replicated for fault tolerance.

  • The scalability equation: for a system with \(n\) servers:

    • Ideal: throughput scales linearly (\(n\) servers → \(n\times\) throughput).
    • Actual: overhead from coordination, load balancing, and data transfer means throughput scales sub-linearly. Amdahl's law (chapter 16) applies: the serial fraction (shared state, coordination) limits the speedup.

Distributed Systems

  • A distributed system is a group of machines that coordinate to provide a service. The fundamental challenges:

  • Network partitions: machines cannot always communicate. A network cable is cut, a switch fails, a data centre loses power. The system must handle partial failures.

  • Clock skew: machines have different clocks. "Event A happened at 10:00:01 on machine 1" and "Event B happened at 10:00:01 on machine 2" does not mean they happened simultaneously. Logical clocks (Lamport timestamps, vector clocks) establish ordering without relying on physical clocks.

  • Consensus: how do multiple machines agree on a value (e.g., who is the leader)? Raft is the standard consensus algorithm. A cluster of nodes elects a leader. The leader handles all writes. If the leader fails, the remaining nodes elect a new leader. Requires a majority (3 out of 5 nodes) to operate, so it tolerates \(\lfloor(n-1)/2\rfloor\) failures.

  • Distributed locks: ensure only one machine performs a critical operation. Redlock (Redis-based) acquires locks across multiple Redis instances. If a majority of instances grant the lock, it is acquired. Used for: preventing duplicate model deployments, ensuring only one training job writes to the checkpoint.

Microservices

Microservices ML architecture: API gateway routes to feature, model, and logging services, each with its own database, connected via message queue

  • Microservices decompose a system into small, independently deployable services. Each service owns one domain:
┌─────────────┐  ┌──────────────┐  ┌─────────────┐
│ API Gateway │→ │ Feature Svc  │→ │ Feature DB  │
└─────────────┘  └──────────────┘  └─────────────┘
       │
       ├────────→ ┌──────────────┐  ┌─────────────┐
       │          │ Model Svc    │→ │ Model Store │
       │          └──────────────┘  └─────────────┘
       │
       └────────→ ┌──────────────┐  ┌─────────────┐
                  │ Logging Svc  │→ │ Log Store   │
                  └──────────────┘  └─────────────┘
  • Advantages: independent deployment (update the model service without touching the feature service), independent scaling (scale model servers based on request load, feature servers based on feature store read rate), technology freedom (model service in Python, feature service in Go).

  • Disadvantages: network overhead (every service call is a network round trip), complexity (debugging spans multiple services), data consistency (no cross-service transactions).

  • Service discovery: how does the API gateway find the model service? Options: DNS-based (each service registers a DNS name), K8s services (built-in), or a service registry (Consul, Eureka).

  • Saga pattern: for operations spanning multiple services (create user + allocate resources + send welcome email), use a saga: a sequence of local transactions with compensating actions if any step fails.

Data Pipelines

  • ML systems consume enormous amounts of data. Data pipelines move, transform, and serve this data:

Batch Processing

  • Process large volumes of data at regular intervals (hourly, daily).

  • MapReduce: the original batch paradigm. Map (transform each record independently) → Shuffle (group by key) → Reduce (aggregate per group). Conceptually simple but verbose to implement.

  • Apache Spark: the modern batch engine. In-memory processing (100x faster than MapReduce for iterative algorithms). Supports SQL, DataFrames, and ML pipelines. The standard for feature engineering at scale.

  • Example: compute user features for a recommendation system. Input: 1B user activity events from the last 30 days. Output: 100M user feature vectors. Run daily as a Spark job, output to the feature store.

Stream Processing

  • Process data in real-time as it arrives (sub-second latency).

  • Apache Flink: the leading stream processing engine. Exactly-once processing, event-time handling (process events by when they happened, not when they arrived), windowing (tumbling, sliding, session windows).

  • Kafka Streams: lightweight stream processing built into Kafka. Good for simpler transformations (filtering, aggregation) without deploying a separate cluster.

  • Example: real-time fraud detection. Each credit card transaction is a Kafka event. A Flink job computes running statistics (transaction frequency, location changes) and flags anomalies within 100ms.

Lambda Architecture

  • Combine batch and stream processing. The batch layer provides accurate, comprehensive results (but with delay). The speed layer provides approximate, real-time results. A serving layer merges both.

  • In practice, many teams now use the Kappa architecture: stream processing only, treating the stream as the source of truth. The stream is replayable (Kafka retains events), so batch can be simulated by replaying the stream.

ML Training Infrastructure

  • Training a frontier model (100B+ parameters) is a large-scale infrastructure problem: thousands of GPUs running for months, consuming megawatts of power, generating petabytes of data, and costing tens of millions of dollars. The infrastructure determines whether training succeeds or fails.

GPU Clusters

  • A training cluster is a collection of GPU servers connected by high-speed networks. Key components:

GPU cluster: each node has 8 GPUs connected by NVLink, nodes connected by InfiniBand in a fat tree topology, scaling from 64 to 16,000+ GPUs

  • GPU servers (nodes): each server has 4-8 GPUs. A typical configuration: 8 × H100 GPUs, 2 × AMD EPYC CPUs, 2 TB RAM, 30 TB NVMe SSD. The GPUs within a node are connected by NVLink (900 GB/s per GPU on H100), which is 30x faster than PCIe.

  • Cluster sizes: a small training cluster has 64-256 GPUs (8-32 nodes). A frontier model training cluster has 4,000-32,000 GPUs (500-4000 nodes). Meta's Llama 3 used 16,384 H100 GPUs. Google trains on TPU pods with 8,000+ chips.

  • Back-of-envelope: training a 70B model requires ~\(2M in compute. Training a 400B+ frontier model requires ~\)50-100M. The cluster hardware itself costs ~\(500M-\)1B at H100 prices ($30K per GPU × 16,000 GPUs = $480M).

Rack-Scale GPU Domains

  • Traditional GPU clusters treated an 8-GPU server as the hard boundary of ultra-fast NVLink communication, dropping sharply down to slower scale-out InfiniBand or Ethernet whenever parallelism crossed nodes. Modern frontier infrastructure breaks through that 8-GPU ceiling with rack-scale GPU domains, exemplified by the NVIDIA GB200 NVL72.

  • Rather than wiring nine independent servers together over top-of-rack Ethernet, a GB200 NVL72 integrates 36 Grace CPUs and 72 Blackwell GPUs inside a single direct liquid-cooled rack interconnected by 5th-generation NVLink (NVLink 5) and dedicated NVLink Switch trays. Each Blackwell GPU enjoys 1.8 TB/s of bidirectional NVLink bandwidth (double Hopper's 900 GB/s), producing 130 TB/s of aggregate bidirectional fabric bandwidth and roughly 13.8 TB of unified HBM3e across one coherent memory domain. Locally, each Grace CPU links to its paired Blackwell GPUs over coherent NVLink-C2C, extending high-bandwidth memory access cleanly across the host boundary.

  • From a systems perspective, the entire 72-GPU rack behaves like one giant unified accelerator (which orchestrators can also slice dynamically into isolated multi-tenant partitions when needed). Trillion-parameter models can run high-bandwidth tensor parallelism, wide expert parallelism (chapter 20 file 05), and low-latency disaggregated KV-cache handoffs completely inside the NVLink 5 fabric without hitting cross-node network bottlenecks, reserving scale-out InfiniBand or lossless Ethernet solely for connecting racks together into multi-thousand-GPU superclusters.

Networking Topology

  • The network between GPU nodes is the most critical infrastructure component. If GPUs cannot exchange gradients fast enough, they sit idle waiting for communication to complete.

  • InfiniBand is the standard for GPU cluster networking. NVIDIA's Quantum-2 InfiniBand provides 400 Gb/s per port. Each node typically has 8 InfiniBand ports (one per GPU), giving 400 GB/s total bisection bandwidth per node.

  • RDMA (Remote Direct Memory Access): InfiniBand supports RDMA, which transfers data directly between GPU memory on different nodes without involving the CPU. This reduces latency from ~100μs (TCP) to ~1μs and is essential for efficient gradient all-reduce (chapter 6).

  • Network topology matters: a fat tree (Clos network) provides full bisection bandwidth (any GPU can communicate with any other at full speed). Cheaper topologies (rail-optimised, 3D torus) provide less bandwidth but cost less. The topology must match the parallelism strategy:

    • Data parallelism: all-reduce across all GPUs → needs high bisection bandwidth (fat tree).
    • Tensor parallelism: communication within a node → NVLink handles this (no network needed).
    • Pipeline parallelism: communication between adjacent pipeline stages → needs bandwidth only between specific node pairs (rail-optimised is fine).
  • Ethernet alternatives: RoCE v2 (RDMA over Converged Ethernet) provides RDMA over standard Ethernet infrastructure. Cheaper than InfiniBand but with higher latency and more congestion. Google uses RoCE for some TPU pod networks. Ultra Ethernet Consortium is developing lossless Ethernet for AI workloads.

Storage for Training

  • Training requires three storage tiers:

    • Dataset storage: the training corpus (1-100 TB of text, or petabytes of multimodal data). Stored in distributed file systems or object storage. Must support high-throughput sequential reads (the data loader reads data in large batches). Lustre and GPFS are common HPC file systems; cloud alternatives include FSx for Lustre (AWS) and Filestore (GCP).

    • Checkpoint storage: training state (model weights + optimiser state + scheduler state) saved periodically. For a 70B model in mixed precision with Adam optimiser: ~560 GB per checkpoint (70B × 4 bytes × 2 for optimiser). Saving hourly for a 3-month run = ~2000 checkpoints = 1.1 PB. In practice, only the latest N checkpoints are kept, and old ones are deleted. Must be fast enough that checkpointing does not significantly slow training.

    • Logging and metrics: experiment tracking data (loss curves, learning rate schedules, gradient norms). Relatively small but must be written in real-time. W&B, MLflow, or TensorBoard handle this.

  • The storage bottleneck: a 16,000-GPU cluster loading a training batch needs to read ~100 GB/s of data continuously. If the file system cannot sustain this throughput, GPUs sit idle waiting for data. Data pipeline optimisation (prefetching, caching, format optimisation using WebDataset or Mosaic Streaming) is critical.

Job Scheduling

  • A GPU cluster serves multiple teams and projects. A job scheduler allocates GPUs to training jobs:

  • SLURM: the standard HPC job scheduler. Users submit jobs specifying GPU count, memory, and time limit. SLURM allocates resources and manages the queue. Supports priority-based scheduling, preemption, and fair-share allocation between teams.

  • Kubernetes with GPU scheduling (chapter 21 file 02): cloud-native approach. K8s GPU device plugins expose GPUs as schedulable resources. Volcano and Run:ai add ML-specific scheduling features: gang scheduling (allocate all GPUs for a job at once, not one at a time), priority queues, and GPU time-sharing.

  • Scheduling challenges:

    • Fragmentation: a cluster with 1000 GPUs might have 200 free, but spread across 50 nodes (4 free per node). A job needing 128 contiguous GPUs cannot run, even though there are enough total GPUs. Defragmentation (migrating jobs to consolidate free GPUs) or topology-aware scheduling (allocate GPUs that are well-connected) address this.
    • Priority and preemption: urgent experiments should preempt lower-priority jobs. But preempting a training job that has been running for 2 days wastes the compute. The scheduler must balance priority with efficiency.
    • Fair share: teams should get their allocated fraction of compute over time, even if a team submits more jobs than its share.

Automated GPU Fault Detection and Fast Elastic Checkpointing

  • At the scale of thousands of GPUs running for months, hardware failures are routine rather than exceptional. Mean time between failures on a 16,000-GPU cluster is measured in hours, and training Meta's Llama 3 (16,384 H100s over 54 days) logged roughly 466 job interruptions. Keeping effective training time above 90% of wall-clock time depends on automated fault detection and sub-minute recovery rather than manual firefighting.

  • Explicit hardware faults include uncorrectable ECC memory errors, dropped NVLink or InfiniBand lanes, overheating accelerators, power-supply faults, and failing NVMe drives. Automated node health checkers monitor GPU telemetry continuously and run quick synthetic GEMM and communication probes before admitting nodes into a training job.

  • Silent Data Corruption (SDC) is far more insidious than a hard crash. Occasionally a degraded Tensor Core, SRAM bank, or interconnect silently flips bits or produces corrupted floating-point results without triggering any ECC error or hardware exception. During distributed training, that single poisoned gradient propagates across every GPU via all-reduce, manifesting as sudden loss spikes, NaN explosions, or quietly degraded model quality. Large clusters defend against SDC through scheduled fleet-wide deterministic arithmetic tests, lightweight per-step gradient-norm anomaly detectors, and automatic node quarantine whenever a suspect GPU diverges from reference kernels.

  • NCCL timeouts and collective hangs are the signature failure mode of massive synchronous runs. Because CUDA kernels execute asynchronously, a single hung or degraded rank causes thousands of healthy GPUs to block indefinitely at the next AllReduce or AllGather barrier until the NCCL watchdog fires a timeout and tears down the entire job. Without rich diagnostics, every rank reports the same generic timeout. Modern infrastructure embeds lightweight ring-buffer telemetry (such as PyTorch Flight Recorder and ByteDance MegaScale-style network tracing) that records the exact start and completion of every collective call so automated controllers can pinpoint the straggler GPU or faulty network link in seconds.

  • Fast asynchronous and elastic checkpointing slashes the compute lost to every interruption. Traditional synchronous checkpointing stalls all GPUs for minutes while hundreds of gigabytes of weights and optimiser states flush to parallel storage. Asynchronous checkpointing (implemented in frameworks like TorchSnapshot and PyTorch Distributed Checkpoint) copies sharded tensors from GPU HBM into fast host CPU DRAM in a few seconds and immediately unblocks GPU training while background threads persist shards to local NVMe and object storage. At frontier scale, clusters also maintain in-memory peer checkpoints replicated across neighbouring nodes' host RAM so recovery reloads weights directly over RDMA without waiting on shared file systems.

  • Combined with elastic orchestration and pools of hot spare nodes, the control plane detects an unhealthy GPU or NCCL hang, cordons the bad node automatically, swaps in a verified healthy spare (or resizes the world dynamically), and resumes from the latest snapshot with minimal human intervention.

Inference Storage and Tiered KV-Cache Offloading

  • Long-context assistants, multi-turn agents, and shared document workflows turn KV-cache capacity into a first-class infrastructure bottleneck. GPU HBM delivers blistering bandwidth (several terabytes per second), yet remains scarce and costly. Dropping a paused user's KV cache forces expensive prefill recomputation on the next turn, while keeping millions of idle conversations resident in HBM is economically impossible.

  • Modern LLM serving fleets resolve this with tiered KV-cache offloading, arranging memory into a seamless three-tier hierarchy governed by prefix hit rates and access recency.

    • Tier 1 (GPU HBM) retains active KV pages for currently decoding sequences and the hottest shared system prefixes.
    • Tier 2 (Host CPU DRAM) supplies hundreds of gigabytes to multiple terabytes of fast overflow memory per server (reaching ultra-high transfer rates over coherent NVLink-C2C on Grace-Blackwell nodes or PCIe Gen5 elsewhere). Evicted prefixes and preempted sessions spill into host RAM and stream back into HBM far faster than recomputing long-context prefill from scratch.
    • Tier 3 (Local NVMe SSDs and distributed KV pools) aggregates spare host memory and flash storage across the entire serving cluster into a shared, content-addressed cache (as in Mooncake Store and enterprise KV-cache managers). Any prefill or decode worker can fetch a cached document or conversation prefix asynchronously over RDMA, transforming KV caching from a single-GPU memory trick into a cluster-wide shared memory fabric.

Cost and Efficiency

  • Training infrastructure cost is dominated by GPU hours:
Component % of Total Cost
GPU compute 70-80%
Networking (InfiniBand) 10-15%
Storage 5-10%
Cooling and power 5-10%
  • GPU utilisation (Model FLOPs Utilisation, MFU) measures what fraction of the GPU's theoretical peak performance is actually used for useful computation. Peak H100 is 989 TFLOPS (FP8). Achieving 40-50% MFU is good; 50-60% is excellent. The gap is due to: communication overhead (all-reduce, pipeline bubbles), memory bandwidth limitations, and idle time during checkpointing and data loading.

  • Improving MFU: overlap computation and communication (chapter 6), use efficient attention (Flash Attention, chapter 19), optimise data loading (prevent GPU starvation), reduce checkpoint overhead (async checkpointing, checkpoint to fast NVMe first, then background-copy to persistent storage).

  • Build vs buy: at small scale (<256 GPUs), cloud is cheaper (no upfront cost, pay per hour). At large scale (>1000 GPUs, sustained use for 6+ months), owning hardware is cheaper (~2-3x lower TCO over 3 years). Most AI companies use a mix: owned clusters for sustained training, cloud for burst capacity and experimentation.

Database Scaling

  • Read replicas: route read queries to replicas of the primary database. The primary handles writes, replicas handle reads. Since most workloads are read-heavy (95%+ reads), this scales read throughput linearly with the number of replicas.

  • Partitioning (sharding, from file 01): split data across multiple databases. Each partition is independent, enabling parallel reads and writes. The challenge is cross-partition queries (join data from different shards).

  • Connection pooling: databases have limited connection capacity. A connection pool (PgBouncer for PostgreSQL) reuses connections across requests, preventing connection exhaustion when hundreds of service instances each try to connect.

Search and Vector Systems

  • Inverted index: the foundation of text search. For each word, store a list of documents containing that word. A query intersects the lists for each query word. Elasticsearch is the standard: distributed, real-time, supports full-text search, aggregations, and geospatial queries.

  • BM25: the standard text retrieval scoring function. Scores documents by term frequency, inverse document frequency, and document length normalisation. Simple but effective — still competitive with neural methods for keyword-heavy queries.

  • Vector databases store embeddings (high-dimensional vectors) and support fast approximate nearest neighbour (ANN) search. Given a query embedding, find the \(k\) most similar stored embeddings.

  • FAISS (Facebook AI Similarity Search): a library (not a database) for ANN search. Supports multiple index types:

    • Flat: exact search, \(O(n)\). Used for small datasets or as ground truth.
    • IVF (Inverted File): partition vectors into clusters, search only the nearest clusters. \(O(n/k)\) per query.
    • HNSW (Hierarchical Navigable Small World): graph-based. Build a hierarchical graph, navigate from coarse to fine. Extremely fast and accurate, the default choice for most applications.
    • Product Quantisation (PQ): compress vectors into compact codes for memory-efficient search. Trade accuracy for memory.
  • Managed vector databases: Pinecone, Weaviate, Milvus, Qdrant. They handle scaling, replication, and real-time updates that FAISS does not.

  • For RAG (Retrieval-Augmented Generation): user query → embed with a text encoder → search the vector database for relevant documents → prepend retrieved documents to the LLM prompt. The quality of the retrieval directly determines the quality of the LLM's response.

Observability

  • Observability is the ability to understand what is happening inside your system from its external outputs. Three pillars:

Logging

  • Structured logs (JSON) are searchable and parseable. Unstructured logs ("ERROR: something failed") are not. Always log: timestamp, service name, request ID (for tracing across services), severity, and the relevant context.

  • ELK stack (Elasticsearch, Logstash, Kibana): the standard logging pipeline. Logstash collects and transforms logs, Elasticsearch indexes them, Kibana visualises and searches.

Metrics

  • Metrics are numerical measurements over time: request rate, error rate, latency percentiles, GPU utilisation, queue depth. Prometheus scrapes metrics from services; Grafana visualises them in dashboards with alerting.

  • The RED method for services: Rate (requests/second), Errors (error rate), Duration (latency). Monitor these for every service.

  • The USE method for resources: Utilisation (% in use), Saturation (queue depth), Errors. Monitor these for every resource (CPU, GPU, memory, disk, network).

Tracing

  • Distributed tracing follows a single request across multiple services. A user request hits the API gateway → feature service → model service → postprocessing. A trace records the timing of each hop, showing where latency is spent.

  • OpenTelemetry: the open standard for traces, metrics, and logs. Instrument your code once, export to any backend (Jaeger, Zipkin, Datadog).

Reliability

  • SLO (Service Level Objective): the target reliability. "99.9% of requests complete in <200ms." This gives a concrete error budget: 0.1% of requests (about 43 minutes per month) can be slow or fail.

  • SLI (Service Level Indicator): the measurement. "The 99th percentile latency over the last 5 minutes."

  • SLA (Service Level Agreement): the contractual promise with consequences. "If availability drops below 99.95%, the customer gets a credit."

  • Error budgets: if your SLO is 99.9% and you are at 99.99%, you have budget for risky changes (deploy a new model, migrate databases). If you are at 99.85%, freeze all changes and focus on reliability. Error budgets turn reliability from an abstract goal into a measurable resource.

  • Chaos engineering: deliberately inject failures (kill a server, add network latency, corrupt data) to test whether your system handles them correctly. Netflix's Chaos Monkey randomly terminates production instances. If the system stays up, it is resilient. If it falls over, you found a bug before your users did.

CI/CD

  • Continuous Integration: automatically build and test every code change. Every push triggers: lint, type check, unit tests, integration tests. If any fail, the change is rejected. This catches bugs before they reach production.

  • Continuous Deployment: automatically deploy changes that pass CI. Deployment strategies:

    • Blue-green: run two identical environments (blue = current, green = new). Switch traffic from blue to green instantly. If green fails, switch back to blue (instant rollback).

    • Canary: route a small fraction of traffic (1-5%) to the new version. Monitor for errors. Gradually increase traffic if metrics look good. This limits the blast radius of a bad deployment.

    • Feature flags: deploy new code but hide it behind a flag. Enable the flag for a subset of users (internal testers, then beta users, then everyone). Decouple deployment (code is live) from release (users see the feature).

  • For ML: CI/CD includes model-specific steps. A model change triggers: unit tests (shape tests, gradient checks), evaluation on a held-out set (accuracy must not regress), shadow deployment (run the new model alongside the old one, compare outputs), and gradual rollout (canary from 1% → 100%).