Multi-Tenant Cloud AI Serving Platform

Hard · ML System Design · Software Engineer · HR Screen

Prompt

Architect a multi-tenant cloud serving platform capable of executing both low-latency interactive AI requests (including streaming Large Language Models and classic ML predictors) and asynchronous bulk batch jobs.

Walk through how models move from registration to production serving on top of Kubernetes and a central artifact registry, addressing:

  • Artifact packaging, immutability, and compute selection: How model weights, runtimes, and configurations are versioned, validated, and matched to appropriate CPU or GPU accelerators.
  • Traffic management, elasticity, and tenant boundaries: How incoming calls are routed across replicas, how pools scale dynamically with demand, and how compute, memory, and network resources are isolated across competing customer organizations.
  • Service-level targets and unit economics: Concrete latency and throughput objectives per workload tier, alongside cost-efficiency levers such as automated profile sizing and preemptible/spot capacity.
  • Production operations and resilience: Progressive release workflows (shadow mirroring, staged canary promotion, and instant rollback), end-to-end telemetry (distributed traces and hardware/service metrics), failure recovery, and how your architecture compares against managed cloud ML platforms and open-source serving frameworks.

Scope & Expectations

  • Define clear service-level objectives, API/event contracts, and durable control-plane entities separating immutable model artifacts from live traffic routing weights.
  • Size GPU memory, bandwidth, and CPU-vs-GPU cost crossovers with back-of-the-envelope math, showing how Kubernetes orchestrates caching, scheduling, and multi-tenant isolation tiers.
  • Explain LLM-specific data-plane mechanics—such as prefix-aware load balancing, KV-cache-driven autoscaling, and batch backfill—alongside safe rollouts, observability, and fault handling.

Step-by-step walkthrough

  1. Clarify requirements, workload classes, and SLOs

    An AI inference platform cannot use a single serving architecture because classic machine learning models, interactive Large Language Models (LLMs), and offline batch jobs fail in completely different ways. Start by splitting traffic into three workload classes and pinning down concrete Service Level Objectives (SLOs) — measurable latency and availability targets agreed with customers — for each class.

    Assumed scale (confirm with the interviewer): A multi-region GPU cloud provider operates the platform across 3 geographic regions for ~300 tenant organizations. Tenants deploy their own models (open-weight fine-tunes, custom neural networks, gradient-boosted trees) or call platform-hosted open-weight LLMs.

    Workload class      Typical examples                         Target SLO & traffic scale
    ------------------  ---------------------------------------  ---------------------------------------------------
    Real-time classic   Fraud scoring, search ranking, small NLP p99 server latency <= 50 ms
                                                                 30,000 req/s peak across ~1,500 endpoints
    Real-time LLM       Chatbots, coding assistants, agents      TTFT p95 <= 500 ms (prompts <= 2,000 tokens)
                        (streamed token by token)                TPOT p95 <= 50 ms (>= 20 tokens/s per user stream)
                                                                 1,000 req/s peak (avg 1,000 input / 250 output tok)
    Offline batch       Document embeddings, bulk scoring, evals Complete within 24 hours at minimum cost per item
                                                                 200 million items/day
    

    For streaming LLMs, one end-to-end latency number is misleading because a 500-token answer naturally takes longer than a 20-token answer. Instead, we measure two separate phases: - TTFT (Time To First Token): How long the user waits before seeing the first word, dominated by queueing plus prefill (processing all input prompt tokens in parallel to build the model's initial attention state). - TPOT (Time Per Output Token): The gap between consecutive output tokens during decode (generating output tokens one step at a time); 50 ms equals 20 tokens/second, comfortably faster than human reading speed.

    Functional requirements: - Model registry & packaging: Register immutable model versions (weights + config, or custom serving containers) with automated validation and hardware benchmarking. - Real-time & streaming endpoints: REST, gRPC, and OpenAI-compatible streaming APIs; automatic or explicit CPU/GPU selection; configurable min/max replicas including scale-to-zero. - Safe rollouts: Traffic splitting across versions for shadow testing, staged canaries, sticky A/B tests, and instant rollback. - Batch execution: Read large input datasets from object storage, write outputs back, and report shard progress and cost. - Governance: Multi-tenant isolation tiers, rate limits, quotas, usage billing, and per-tenant metrics and traces.

    Hard correctness boundaries vs. best-effort objectives: - Hard correctness boundaries (must never be violated): Zero cross-tenant leakage of model weights, prompts, completions, or cached attention state; immutable content-addressed version mapping (deploying version v3 always loads the exact audited bytes); idempotent billing and non-stream retries (repeating a request with the same ID never double-executes or double-charges); and never mixing or silently truncating active token streams. - Best-effort statistical objectives (governed by error budgets): 99.9% monthly endpoint availability (~43.2 minutes downtime budget per 30 days), <= 5 ms p99 platform routing overhead, TTFT/TPOT latency targets, prefix-cache hit rates, and spot-instance cost savings. - Explicit exclusions (out of scope): Model pre-training or fine-tuning clusters, human dataset labeling workflows, and end-user chat interfaces. Because training happens upstream, "model quality" enters our platform as deployment gates (offline evaluation suites, live shadow/canary comparisons, and a /feedback API that joins delayed user outcomes back to model versions).

  2. Back-of-the-envelope capacity, memory, and CPU-vs-GPU math

    Before drawing boxes, size the bottleneck resources: GPU High-Bandwidth Memory (HBM) (ultra-fast memory stacked directly on the GPU package), memory bandwidth, prefill compute, and the cost crossover between CPUs and GPUs.

    Reference hardware & LLM: Take an NVIDIA H100 SXM GPU (80 GB HBM, 3.35 TB/s = 3,350 GB/s memory bandwidth, ~990 TFLOPS — trillion floating-point operations per second — of dense 16-bit compute) serving an 8B-parameter LLM (32 transformer layers, 8 key/value heads of dimension 128 using Grouped-Query Attention, similar to Llama-3-8B) stored in BF16 (16-bit brain floating point, 2 bytes per parameter).

    During generation, the engine keeps a KV cache — saved Key and Value attention vectors for every previous token in the conversation — so each new decode step only attends to stored vectors instead of re-processing the entire prompt from scratch.

    1. Memory per H100 GPU (80 GB total):
       Model weights     = 8 x 10^9 params x 2 bytes                    = 16.0 GB
       KV cache / token  = 32 layers x 8 KV heads x 128 dims x 2 (K,V) x 2 bytes
                         = 131,072 bytes (~0.131 MB per token)
       Usable KV budget  = 80 GB - 16 GB weights - 6 GB (activations, CUDA buffers)
                         = 58 GB -> holds ~442,000 tokens per GPU
    
    2. Why decode is memory-bandwidth-bound:
       Every single decode step must read ALL 16 GB of weights plus the active batch's KV cache from HBM.
       Suppose 120 active streams hold an average of 1,125 tokens (1,000 prompt + half of 250 output):
       KV read per step  = 120 streams x 1,125 tokens x 0.131 MB        = ~17.7 GB
       Total HBM read    = 16.0 GB weights + 17.7 GB KV                 = ~33.7 GB per step
       Minimum step time = 33.7 GB / 3,350 GB/s                         = ~10.1 ms (roofline ceiling: ~11,900 tok/s)
       Practical rate    = 120 streams / 0.040 s step                   = 3,000 output tokens/s per decode GPU
                           (40 ms step leaves headroom for attention kernels, scheduling, and TPOT <= 50 ms)
    
    3. Fleet size at peak (1,000 req/s, 1,000 input tokens, 250 output tokens):
       Decode capacity   = (1,000 req/s x 250 output tok) / 3,000 tok/s = ~84 GPU-equivalents
       Prefill compute   = 1,000 req/s x 1,000 tok x (2 x 8 x 10^9 FLOPs/tok)
                         = 1.6 x 10^16 FLOP/s; at ~400 TFLOP/s (~40% MFU) = ~40 GPU-equivalents
       Active GPU total  = 84 + 40 = 124 GPUs; add ~30% for bursts & N+1 zone loss = 160 H100s (20 nodes x 8 GPUs)
    
    4. Little's Law sanity check (Concurrency = Arrival Rate x Time in System):
       At 40 ms TPOT, each 250-token answer spends 250 x 0.04 s = 10.0 s decoding.
       Active streams    = 1,000 req/s x 10.0 s = 10,000 concurrent streams across the fleet.
       Spread across 124 active unified GPUs (each spending ~1/3 of each step on prefill, ~2/3 on decode):
       ~81 streams/GPU x 1,125 avg tokens x 0.131 MB = ~11.9 GB KV cache/GPU (well under the 58 GB ceiling),
       and 124 GPUs x (81 streams / 0.040 s) = ~251,000 output tok/s -> matches 1,000 req/s x 250 tok!
    

    Here MFU (Model FLOPs Utilization) is the fraction of theoretical peak GPU compute sustained after accounting for memory transfers and kernel launches. A 70B-parameter model in BF16 needs 70B × 2 B = 140 GB just for weights, exceeding a single 80 GB GPU. It requires tensor parallelism — splitting each layer's matrix multiplications across 4 to 8 GPUs connected by high-speed intra-node NVLink interconnects — or FP8 quantization (compressing weights to 8-bit floating point, 1 byte per weight = 70 GB) when offline quality gates pass.

    Cost per million tokens: At an illustrative $2.50 per H100 GPU-hour, 124 busy GPUs cost $310.00/hour and generate 250,000 tok/s × 3,600 s = 900 million output tokens/hour, or $0.34 per 1M output tokens at 100% utilization. At 40% average utilization, idle hardware pushes cost to $0.86 per 1M tokens ($0.344 / 0.40). Raising fleet utilization from 40% to 50% cuts cost per token by 20% ($0.86 -> $0.69), making GPU utilization the primary business lever.

    CPU vs. GPU crossover for smaller models: Consider a 110M-parameter text classifier (~22 GFLOPs per 128-token input). Suppose our benchmark suite measures: - 4-vCPU pod ($0.20/h, INT8 ONNX Runtime): sustains 20 req/s (72,000 req/h -> $2.78 per 1M requests). - NVIDIA L4 GPU ($0.80/h, FP16 + dynamic batching): sustains 1,500 req/s (5.4M req/h -> $0.15 per 1M requests).

    At full saturation the GPU is 18x cheaper per request, but you cannot rent 0.05 of a GPU — one L4 costs $0.80/h even at 1 req/s. Four 4-vCPU pods also cost 4 × $0.20 = $0.80/h and serve 4 × 20 = 80 req/s. Thus CPU wins below ~80 req/s (~160 req/s when enforcing a 2-replica cross-zone high-availability minimum), and GPU wins above it.

    Cold-start transfer numbers: Reading 16 GB of weights from object storage at ~1.5 GB/s takes ~11 s (~93 s for a 140 GB 70B model), versus ~3 s from a node-local NVMe SSD at ~5 GB/s. Pulling an uncached 8 GB runtime container image at 500 MB/s adds another ~16 s.

  3. API contracts, internal events, and registry data model

    Separate the data plane (the live request path where every millisecond counts, which must keep serving even if management databases go down) from the control plane (registration, benchmarking, deployments, and rollouts).

    Data plane (Client -> API Gateway -> Inference Router -> Serving Replicas)
      POST /v1/endpoints/{endpoint}/predict        Classic models: JSON or gRPC binary tensors
      POST /v1/chat/completions                    LLM API {model, messages, max_tokens, stream: bool}
                                                   If stream=true, streams Server-Sent Events (SSE) chunks
                                                   carrying request_id + final {prompt_tokens, completion_tokens}
      POST /v1/batch-jobs                          {model_version, input_uri, output_uri, deadline_hours: 24}
      GET  /v1/batch-jobs/{job_id}?cursor=...      -> {state, completed_shards, total_shards, failed_items, cost_usd}
      Headers: Authorization: Bearer <key>, Idempotency-Key (UUID for safe non-stream/batch retries), traceparent
      Errors:  400 (schema/context limit), 429 + Retry-After (tenant quota or queue full), 503 (no healthy replicas)
    
    Control plane (Client -> Control API -> Registry DB & Kubernetes CRDs)
      POST /v1/models/{name}/versions              {artifact_uri | image_digest, runtime, schema} -> starts CI
      GET  /v1/models/{name}/versions?cursor=...   Cursor-paginated version history + benchmark summaries
      POST /v1/endpoints                           {name, model_version, hardware: "auto" | profile,
                                                    min_replicas, max_replicas, scale_to_zero,
                                                    isolation_tier: "shared" | "dedicated" | "isolated"}
      POST /v1/endpoints/{name}/rollouts           {target_version, strategy: "shadow" | "canary" | "ab",
                                                    steps_pct: [1, 5, 25, 50, 100], guardrails}
      POST /v1/endpoints/{name}/rollback           Atomically flips release weights back to previous warm deployment
      POST /v1/endpoints/{name}/feedback           {request_id, score, label} -> joins delayed outcomes for evals
    
    Internal event contracts (Control Plane / Router -> Kafka / Event Bus)
      ArtifactValidated   (manifest_sha256, schema_ok, scan_ok) -> triggers automated hardware benchmark
      BenchmarkCompleted  (manifest_sha256, hardware_profile, max_qps_within_slo, recommended_profile)
      ReleaseWeightsSet   (endpoint_id, split_version, weights[]) -> pushed to routers with monotonic version
      ReplicaLeaseExpired (replica_id, deployment_id, node_id) -> router ejects replica; operator replaces pod
      InvocationMetered   (request_id PK, tenant_id, deployment_id, in_tok, cached_tok, out_tok, gpu_ms, status)
    

    Core durable entities, immutable vs. mutable fields, and lifecycle states:

    1. model_version (Artifact — owned by tenant_id)
       ID: (tenant_id, model_name, version_num) | Immutable: manifest_sha256, artifact_uri, runtime, quantization
       Mutable state: REGISTERED -> VALIDATED -> BENCHMARKED -> PRODUCTION -> ARCHIVED (or REJECTED)
    
    2. deployment (Concrete serving pool for one version — owned by endpoint_id)
       ID: deployment_id | Immutable: endpoint_id, manifest_sha256, hardware_profile, tp_degree
       Mutable: min_replicas, max_replicas, desired_replicas | State: PROVISIONING -> READY -> DRAINING -> TERMINATED
    
    3. release_weights (Traffic routing table — owned by endpoint_id)
       ID: (endpoint_id, split_version) | Immutable once written (new rollout writes split_version + 1):
       entries: list of (deployment_id, weight_pct, role: "primary" | "canary" | "shadow") summing primary+canary=100
    
    4. replica_lease (Liveness & capacity ownership — owned by K8s operator + replica agent)
       ID: replica_id | Immutable: deployment_id, node_id, gpu_uuids | Mutable: lease_epoch, expires_at, kv_used_pct
       State: WARMING -> ACTIVE (renewed every 2s; expires after 6s missed) -> DRAINING -> EXPIRED
    
    5. request_record (Idempotency & async status for non-stream / batch — owned by tenant_id)
       ID: (tenant_id, idempotency_key) -> request_id | Immutable: request_sha256, endpoint_id
       Mutable state: QUEUED -> RUNNING / STREAMING -> COMPLETED | FAILED | CANCELED
    
    6. usage_ledger & usage_minute (Billing & audit — owned by platform billing)
       usage_ledger: immutable append-only row keyed by request_id (deduplicates retries), rolled up into
       usage_minute (tenant_id, endpoint_id, minute_utc) -> requests, input_tokens, cached_tokens, output_tokens, gpu_s
    

    Every registered model artifact is frozen under its cryptographic manifest_sha256 digest (covering weights, tokenizer, and serving config). Mutable tags like :latest are banned in deployment specs: PRODUCTION is simply the active pointer in release_weights, making rollback a millisecond database pointer swap rather than a 140 GB file copy. Hardware-specific compiled engines (such as TensorRT-LLM) are cached separately under (manifest_sha256, gpu_arch, driver_version) because an engine compiled for an H100 cannot execute on an L4.

  4. End-to-end architecture, Kubernetes integration, and request walk-through

    Each cloud region is partitioned into independent cells — separate Kubernetes clusters of at most ~1,000–2,000 nodes (well below Kubernetes' 5,000-node ceiling) — so a bad cluster upgrade or control-plane outage affects at most one cell of tenants.

                               Client SDKs / HTTPS / gRPC / SSE
                                              |
                            Global Anycast / Geo-DNS (healthy region)
                                              |
    +--------------------------------- Regional Cell ---------------------------------+
    |  [ API Gateway ]  TLS, API key -> tenant_id, local token-bucket rate limits     |
    |         |                                                                       |
    |         v                                                                       |
    |  [ Inference Router ]  watches ReleaseWeightsSet + active ReplicaLeases;        |
    |         |              applies canary/shadow split + bounded-load prefix ring   |
    |         +---------------------------------------+                               |
    |         v                                       v                               |
    |  [ GPU Node Pools (8x H100, L4) ]        [ CPU Node Pools ]                     |
    |    vLLM / TensorRT-LLM / Triton            ONNX Runtime / LightGBM              |
    |    ^  read-only mount from:                                                     |
    |  [ DaemonSet NVMe Weight Cache ] <--- intra-zone P2P / Object Storage           |
    |                                                                                 |
    |  [ K8s Platform Operator ] reconciles ModelDeployment CRDs into                 |
    |    Pods / LeaderWorkerSets, ReplicaLeases, Autoscalers, PDBs, NetworkPolicies   |
    |         ^                                                                       |
    |  [ Control API & Registry DB ] <---> [ Validation & Benchmark CI ]              |
    |  [ Batch Controller & Spot Workers ] <--> Object Storage (input/output shards)  |
    |  [ Event Bus (Kafka) ] -> Billing Rollup, OTel Traces, Prometheus + DCGM GPU    |
    +---------------------------------------------------------------------------------+
    

    How the platform integrates with Kubernetes: - Custom Resource Definition (CRD) & Operator: A CRD extends the Kubernetes API with a custom ModelDeployment resource storing the model digest, hardware profile, replica bounds, and isolation tier. A Kubernetes Operator (a background controller loop that continuously reconciles desired vs. actual state) creates and updates Pods — or multi-node gang-scheduled pod groups via LeaderWorkerSet for multi-node models — along with PodDisruptionBudgets (PDBs) (rules preventing node maintenance from evicting too many replicas simultaneously), NetworkPolicy firewall rules, and autoscalers. - GPU scheduling & taints: The NVIDIA device plugin advertises nvidia.com/gpu resources. GPU nodes carry Kubernetes taints (node markers that repel ordinary CPU pods unless a pod carries a matching toleration), hardware labels (gpu-type=h100-80gb), and cross-zone spread constraints. - Node-local weight caching: A DaemonSet (one background agent pod per node) pulls model digests onto local NVMe SSDs and shares blocks peer-to-peer across nodes in the same availability zone, mounting weights read-only into serving containers so 8 replicas on one host download the weights once, not 8 times.

    Walk-through of one representative streaming LLM request: 1. Admission: The client sends POST /v1/chat/completions (stream=true) with Authorization and traceparent. The API Gateway authenticates tenant_id and checks the tenant's requests-per-second and tokens-per-minute buckets. 2. Version resolution: The Inference Router looks up the endpoint's cached release_weights (split_version = 42), picks the primary deployment (95% weight), and asynchronously clones a fire-and-forget copy to any shadow deployment. 3. Locality + load-aware routing: Among replicas holding an unexpired ACTIVE replica_lease, the router hashes (tenant_id, first_prefix_blocks) onto its consistent hash ring and selects the home GPU replica if its queued + active token load is within 1.25x of the pool average (otherwise spilling clockwise). 4. Prefill & streaming decode: The replica reuses any matching prefix blocks in its paged KV cache, runs chunked prefill on remaining prompt tokens, and streams SSE token deltas straight back through the router and gateway to the client. 5. Metering & cleanup: When generation finishes (or the client disconnects early, triggering immediate stream cancellation to free KV blocks), the router emits one InvocationMetered event keyed by request_id to Kafka for ClickHouse billing rollups and Prometheus/OpenTelemetry dashboards.

  5. Model packaging, automated right-sizing, and Multi-LoRA

    Three-layer decoupling: Never bake multi-gigabyte model weights inside container images. Instead, assemble three independent layers at pod startup: 1. Serving runtime image: A small set of pre-pulled, platform-maintained images (vllm, trtllm, triton, onnxruntime) or a security-scanned tenant custom image. 2. Content-addressed model artifact: Weights stored in safetensors or ONNX format (which store pure tensor buffers and JSON headers, unlike Python pickle files that can execute arbitrary malicious code on load), mounted read-only from the node NVMe cache. 3. Deployment configuration: Max context length, concurrency limits, quantization mode, and tensor-parallel degree.

    Automated hardware selection loop (hardware: "auto"): When a version is registered, a CI pipeline validates its input/output schema, checks golden test prompts, and runs a 4-step sizing loop: 1. Memory fit filter: Verify weights + KV_cache(target_concurrency) + 10% buffer <= 0.90 × GPU_VRAM. If a 70B model exceeds 80 GB, test FP8 quantization against the tenant's accuracy suite or step up to 4× / 8× H100 tensor parallelism. 2. Replay benchmark: Replay synthetic requests matching the tenant's prompt-length and output-length distributions across candidate profiles (4-vCPU, 16-vCPU, 1× L4, 1× H100, 4× H100) to find max_qps_within_slo before p95 TTFT or TPOT breaches target. 3. Total-cost minimization: Compute hourly cost max(min_ha_replicas, ceil(expected_qps / (0.70 × max_qps_within_slo))) × hourly_price and pick the cheapest profile. 4. Continuous right-sizing: Re-trigger sizing if production telemetry shows prompt distributions drifting (for example, average prompts growing from 1,000 to 8,000 tokens multiply KV memory per stream by ~6.6x).

    High-density fine-tunes with Multi-LoRA: Many tenants fine-tune the same open-weight 8B model using LoRA (Low-Rank Adaptation), which freezes the 16 GB base weights and trains tiny rank-r adapter matrices on each attention projection (Q and O of shape 4096 -> 4096; K and V of shape 4096 -> 1024). For rank r = 16 across 32 layers: - Per layer: 2 × 16 × (4096 + 4096) [Q, O] + 2 × 16 × (4096 + 1024) [K, V] = 425,984 parameters - Across 32 layers in BF16: 425,984 × 32 × 2 bytes ≈ 27.3 MB

    Because 27.3 MB is ~600x smaller than 16 GB, one shared pool of base-model GPUs can hold dozens of tenant LoRA adapters in VRAM at once and apply each request's adapter inside the same continuous GPU batch, replacing hundreds of mostly idle dedicated GPUs.

  6. Deep dive: token-aware routing, prefix caching, and continuous batching

    Why standard load balancing breaks for LLMs: Round-robin routing fails for two reasons. First, request cost varies by 100x (a 50-token prompt with a 20-token reply vs. an 8,000-token document prompt with a 1,000-token reply). Second, LLM workloads repeatedly send identical prefixes (system prompts, tool definitions, multi-turn chat history). Modern engines support prefix caching — reusing KV cache blocks computed by earlier requests on that same GPU to skip prefill compute and slash TTFT — which round-robin destroys by scattering identical prefixes across every replica.

    Solution: Consistent hashing with bounded load. Place replicas onto a consistent hash ring (a sorted circle of hashed positions so adding or removing one replica remaps only 1/N of keys) and hash (tenant_id, prompt_prefix_blocks) to route matching prefixes to the same home replica — unless that replica's outstanding token load exceeds 1.25x the pool average, in which case walk clockwise to the first replica with headroom. Including tenant_id in both the router hash and the engine's internal block key prevents a cross-tenant timing side channel (where Tenant B could detect fast TTFT to infer whether Tenant A recently queried a sensitive prompt).

    Prompt hash lands at ring pos 410 -> points to replica-B (load = 9,500 tokens)
    Pool average load    = (4,000 + 9,500 + 4,500) / 3 = 6,000 tokens
    Load cap (1.25x + 1) = 7,501 tokens -> replica-B (9,500 > 7,501) is overloaded!
    Walk clockwise       -> next ring slot is replica-C (4,500 <= 7,501) -> route to replica-C
    
    import bisect
    import hashlib
    
    
    def ring_position(key_text: str) -> int:
        """Hash a string to a deterministic 64-bit integer position on the ring."""
        digest_hex = hashlib.sha256(key_text.encode("utf-8")).hexdigest()[:16]
        return int(digest_hex, 16)
    
    
    def build_ring(replicas: list[str], virtual_nodes: int = 100) -> list[tuple[int, str]]:
        """Place each replica at many sorted virtual positions so keys spread evenly."""
        ring = []
        for replica in replicas:
            for slot in range(virtual_nodes):
                pos = ring_position(f"{replica}#{slot}")
                ring.append((pos, replica))
        ring.sort()
        return ring
    
    
    def pick_replica(
        ring: list[tuple[int, str]],
        active_replicas: list[str],
        outstanding_tokens: dict[str, int],
        tenant_id: str,
        prefix_fingerprint: str,
        max_load_ratio: float = 1.25,
    ) -> str:
        """Prefer the prefix's home replica unless its token load exceeds max_load_ratio * average."""
        if not ring or not active_replicas:
            raise RuntimeError("No healthy replicas with active leases")
    
        # Compute average in-flight token load across healthy replicas (defaulting new pods to 0).
        total_tokens = sum(outstanding_tokens.get(r, 0) for r in active_replicas)
        avg_load = total_tokens / len(active_replicas)
        # Add +1 so an idle cluster (avg_load == 0) still admits the very first request.
        load_limit = max_load_ratio * avg_load + 1
    
        # Salt the prefix key with tenant_id so tenants never share prefix-cache timing signals.
        routing_key = f"{tenant_id}|{prefix_fingerprint}"
        start_idx = bisect.bisect_left(ring, (ring_position(routing_key), ""))
    
        # Guaranteed to terminate: at least one active replica has load <= avg_load < load_limit.
        for offset in range(len(ring)):
            _, candidate = ring[(start_idx + offset) % len(ring)]
            if outstanding_tokens.get(candidate, 0) <= load_limit:
                return candidate
        raise RuntimeError("Unreachable when ring and active_replicas match")
    

    Inside each GPU replica: - Continuous (iteration-level) batching: Instead of holding a static batch until its longest answer finishes, completed sequences exit immediately and newly arrived requests join at the very next 40 ms decode step. - Paged KV cache: Memory is allocated on demand in fixed-size blocks (for example, 16 tokens per page, just like OS virtual memory pages) as an answer grows, eliminating the 60–80% memory waste of pre-reserving max_tokens contiguously. - Chunked prefill: An unsplit 8,000-token prompt would stall one GPU for ~150 ms, spiking TPOT for 80 concurrent decode streams. Splitting long prompts into 512-token chunks and piggybacking one chunk onto each decode iteration keeps every step under 50 ms. - Backpressure, fairness, and stream cancellation: Replicas piggyback queue depth and KV occupancy on 100 ms heartbeats. When estimated queue wait (queued_prefill_tokens / prefill_rate) exceeds 250 ms across all replicas, the router sheds excess load early with 429 Retry-After rather than letting queued users time out. Shared pools schedule waiting requests via per-tenant weighted fair queueing (measured in tokens), and if a client closes an SSE stream mid-answer, the router immediately aborts that sequence on the replica to reclaim its KV pages.

    Batch execution path: A batch controller splits large input datasets into 10,000-item shards sorted by token length (minimizing sequence padding waste) and enqueues them. Spot or idle GPU workers write deterministic part-<shard_id>.parquet files and commit completion in a manifest, making shard retries idempotent whenever a spot node is reclaimed.

  7. Deep dive: autoscaling signals, cold starts, and cost controls

    Scale on true bottlenecks, never raw GPU utilization: On an LLM engine, GPU Streaming Multiprocessor (SM) activity ("GPU compute utilization") jumps to 95–100% whether the batch holds 2 streams or 120 streams, because streaming 16 GB of weights out of HBM keeps the hardware active either way. Autoscale per workload class instead: - LLM replicas: Scale on KV cache occupancy (target 70%), p95 queue wait (target < 100 ms), and active sequences vs. benchmarked ceiling. For example, if 10 replicas hit 92% KV occupancy against a 70% target, the autoscaler requests ceil(10 × 0.92 / 0.70) = ceil(13.14) = 14 replicas. - Classic GPU replicas: Scale on in-flight dynamic batch queue depth per replica. - Classic CPU replicas: Scale on CPU utilization (65% target) plus request rate.

    Use asymmetric stabilization windows: scale up immediately with zero delay (up to 2x every 30 s), and scale down slowly over a 10-minute window so slow-starting GPUs never thrash up and down.

    Beating GPU cold starts while keeping utilization high:

    Cold-start scenario                              Ready time    Mitigation
    -----------------------------------------------  ------------  ----------------------------------------------
    Warm node + cached runtime image + NVMe weights  ~20 - 45 s    30% KV headroom absorbs spikes during startup
    Weights missing on node (pull from object store) +11 to +93 s  DaemonSet pre-stages popular digests + P2P copy
    Runtime image missing on node (~8 GB)            +16 s         Pre-pull standard serving images on all nodes
    No free GPU node in cluster                      +3 to 8 min   Warm spare pool kept busy running batch shards
    

    Rather than leaving spare GPUs idle (burning $2.50/h), schedule all pods across four Kubernetes PriorityClasses so offline batch jobs soak up spare capacity and yield within seconds when real-time traffic spikes: 1. Priority 1000 — Dedicated real-time: Reserved tenant capacity; never preempted. 2. Priority 800 — Shared real-time: Preempts batch workers immediately on scale-up. 3. Priority 400 — Deadline-at-risk batch: Promoted automatically if (remaining_items / current_rate) > time_to_deadline. 4. Priority 100 — Best-effort / spot batch: Backfills every idle GPU in the fleet; evicted first.

    Additional cost controls: Hardware MIG (Multi-Instance GPU) slices partition one H100 into up to 7 hardware-isolated mini-GPUs (with separate memory controllers and caches) for low-QPS models; scale-to-zero shuts down dev/staging endpoints after 30 idle minutes (an activator proxy holds the waking request up to 120 s); and spot instances run batch workers plus surge replicas above an endpoint's on-demand baseline floor.

  8. Deep dive: multi-tenant isolation, progressive rollouts, and observability

    Three priced multi-tenant isolation tiers:

    Tier       What tenants share                  Target workload                  Isolation boundaries
    ---------  ----------------------------------  -------------------------------  ------------------------------------------
    Shared     GPU replicas & continuous batches   Platform open-weight LLMs        Tenant-salted prefix cache, token-fair
               (priced per 1M input/output tok)    & Multi-LoRA adapters            queues, per-tenant token rate buckets
    Dedicated  Cluster control plane & physical    Custom weights with strict       Whole GPUs or hardware MIG slices (NEVER
               host (priced per GPU-hour)          latency SLOs                     software GPU time-slicing), K8s namespaces,
                                                                                    ResourceQuotas, default-deny NetworkPolicy
    Isolated   Nothing inside data plane           Regulated data (HIPAA/finance)   Dedicated tainted nodes, gVisor / Kata
               (dedicated node pool + premium)     & untrusted custom containers    microVMs, read-only rootfs, zero internet
                                                                                    egress, KMS per-tenant encryption keys
    

    Software GPU time-slicing is forbidden across tenants because standard CUDA context switching provides neither memory fault isolation nor tail-latency isolation. Custom tenant containers are treated as untrusted code: running them inside microVM sandboxes (lightweight virtual machines with isolated guest kernels) with outbound internet egress blocked prevents a malicious container from exfiltrating prompts or weights. Prompts and completions are never written to disk unless a tenant explicitly enables audit logging with an expiration TTL.

    Safe progressive rollouts: 1. Offline CI gates: Schema checks, golden prompt checks, throughput benchmark within 10% of production, and quality suites (holdout AUC/calibration for classic models; task accuracy, LLM-as-judge win rate, and safety refusal rates for LLMs). 2. Shadow deployment: Asynchronously mirror 5–10% of live traffic to the candidate deployment, discard its HTTP response, and check latency, errors, and output distribution drift with zero user impact. 3. Staged canary (1% -> 5% -> 25% -> 50% -> 100%): Hold each step for >= 15 minutes and compare canary pods against primary pods in the exact same time window (so time-of-day prompt-length changes never cause false rollbacks). Any breach in p99 TTFT, TPOT, 5xx rate, or GPU OOM count atomically resets canary weight to 0%, while old primary replicas stay warm for 1 hour after 100% promotion. 4. Sticky A/B testing: Hash end_user_id consistently to measure business lift via /feedback events joined on request_id. Using the standard two-proportion sample-size formula (where 1.96 and 0.84 are the normal-distribution cutoffs for 95% confidence and 80% statistical power), detecting a +1 percentage point lift from a 60% thumbs-up baseline requires n ≈ 2 × (1.96 + 0.84)^2 × 0.6 × 0.4 / 0.01^2 ≈ 37,600 rated responses per variant.

    Observability & SLO burn-rate alerting: - Metrics & tracing: Collect request rates, error codes, TTFT/TPOT/queue histograms, KV occupancy, and NVIDIA DCGM hardware counters (ECC memory bit-flip errors, Xid GPU driver fault codes, thermal throttling) labeled by (tenant, endpoint, deployment) — never request_id, which explodes time-series cardinality. Propagate W3C traceparent across gateway -> router -> queue -> prefill -> decode using tail-based sampling (keeping 100% of error or slow p99 traces and 1% of normal traces). - Error-budget burn-rate alerts: For a 99.9% monthly SLO (0.1% error budget over 720 hours), page on-call when 2% of the monthly budget burns in 1 hour — a 0.02 × 720 = 14.4x burn rate (1.44% error rate), sustained over 5 minutes so brief blips do not wake engineers.

  9. Failure handling, 10x scaling bottlenecks, and industry comparison

    Failure mode                      Detection signal                    Automated recovery
    --------------------------------  ----------------------------------  -------------------------------------------------
    GPU hardware fault (Xid 79 / ECC) DCGM exporter, NaN logits, hang     Expire lease, cordon & taint node, replace pod
    Partitioned / frozen replica      Missed 2s heartbeats (> 6s TTL)     ReplicaLease expires; router stops sending traffic
    Crash mid-LLM stream              Replica TCP reset before [DONE]     Retry on peer ONLY if 0 tokens flushed to client;
                                                                          once tokens streamed, emit clean SSE error event
    Slow "gray failure" replica       Step latency > 3x pool median       Router outlier detection ejects replica for 60 s
    Fleet-wide traffic overload       All replicas above queue budget     Shed per-tenant excess (429), preempt batch, scale
    Poison request crashing engine    Same request hash crashes 2 pods    Quarantine hash in router blocklist, return 400
    Control plane / Registry outage   DB or K8s API unreachable           Gateway & router keep serving from cached snapshot
    

    Automatic retries are restricted to requests carrying Idempotency-Key before any stream bytes are flushed, bounded by a 10% cluster retry budget so a partial outage never snowballs into a retry storm.

    Scaling bottlenecks as the fleet grows 10x: 1. Mass weight pulls during zone failover: Launching 50 replicas of a 70B model moves 7 TB (50 × 140 GB) across storage links. Pre-stage popular digests on NVMe caches across 3 availability zones and distribute blocks peer-to-peer inside each zone (using Dragonfly or Kraken). 2. Router heartbeat fan-in: 2,000 GPU replicas reporting load every 100 ms generate 20,000 updates/s. Partition router pools by endpoint shard so each router tracks only its assigned subset of endpoints. 3. Distributed rate-limit hot keys: Global per-request lockstep counters add cross-zone latency; run local token buckets on each gateway pod and sync refill quotas asynchronously every 100 ms.

    Comparison with industry offerings & trade-off summary: - Hyperscaler managed platforms (AWS SageMaker, Google Vertex AI, Azure ML): Integrated registries, real-time/batch modes, and traffic splitting out of the box, but tied to one cloud's VM SKUs, high GPU markups, and generic HTTP load balancers that lack prefix-aware LLM routing. - Open-source Kubernetes stacks (KServe, Ray Serve / KubeRay + vLLM, SGLang, TensorRT-LLM, Triton): Portable across clouds and bare metal with state-of-the-art serving kernels, but leave multi-tenant microVM isolation, token billing, NVMe peer-to-peer weight caching, and priority batch backfill for you to assemble. - Serverless token APIs: Zero infrastructure management for small workloads, but restricted model catalogs, no untrusted custom containers, and steeper marginal cost at steady high volume.

    Our design combines a declarative Kubernetes control plane and immutable digest registry with an LLM-native data plane (bounded-load prefix routing, Multi-LoRA density, replica leases, three isolation tiers, and priority batch backfill) — maximizing utilization of an owned GPU fleet while giving tenants strict isolation and predictable latency.

Intuition & how it works

Think of a cloud AI inference platform like running a metropolitan transit hub that coordinates express turnstiles, city buses, and overnight freight on the same road network. Small classic models (such as fraud scorers) act like express turnstiles where each passenger taps through in a few milliseconds. Streaming Large Language Models (LLMs), by contrast, work like city buses: loading a passenger's luggage onto the bus is prefill (processing all input prompt tokens in parallel), and driving stop-by-stop is decode (generating output one token at a time while reading all model weights from GPU memory on every single stop). Instead of forcing a bus to empty completely before boarding anyone new, continuous batching lets finished passengers step off at their stop and waiting passengers hop on at the very next stop, while preemptible batch jobs fill empty seats during quiet hours and yield immediately when commuter rush hour arrives.

A naive web-service design fails badly on AI workloads. Baking 16–140 GB model weights inside Docker images turns every deployment or scale-up into a multi-minute network bottleneck; round-robin load balancing sends 8,000-token prompts to already-busy GPUs while missing cached prompt prefixes on neighboring GPUs; and autoscaling on raw "GPU compute utilization" is blind because even one active LLM stream keeps GPU memory reads near 100% busy. Together, those mistakes cause multi-second token stalls, 90-second cold-start outages on traffic spikes, and 2–3x wasted GPU spend.

Walk through four concrete events on an 8B-parameter LLM endpoint to see how the platform handles real traffic: 1. Prefix-aware cache hit: Tenant A sends two chat requests sharing a 1,500-token system prompt. The router hashes (tenant_A, prompt_prefix) onto a consistent hash ring (a sorted circle of hashed server positions that keeps matching keys on the same replica even when capacity changes) and lands on replica-2, which already holds those 1,500 tokens in its KV cache (saved Key and Value attention vectors from earlier tokens), cutting Time To First Token (TTFT) from 180 ms to 25 ms. 2. Bounded-load spillover: Ten more Tenant A requests arrive simultaneously, pushing replica-2 past 1.25x the pool's average active token load. Rather than piling onto an overloaded GPU, the router walks clockwise around the ring to replica-3, trading one prefix-cache miss to protect tail latency. 3. Chunked prefill protection: Tenant B submits an 8,000-token document on a shared replica. Instead of stalling all 80 active user streams for 150 ms to read 8,000 tokens at once, the engine slices the prompt into 512-token chunked prefill pieces interleaved with ongoing decode iterations, keeping everyone's Time Per Output Token (TPOT) under 40 ms. 4. Fast scale-up via batch preemption: KV cache occupancy crosses the 70% autoscaling target. The Kubernetes operator evicts a low-priority spot batch worker on a warm node whose local NVMe SSD already caches the 16 GB weights, bringing a new real-time replica online with a fresh replica lease (a short-lived heartbeat registration proving the pod is healthy) in ~25 seconds while existing 30% KV headroom absorbs the burst.

Key trade-offs

  • Batch concurrency: GPU cost efficiency vs. per-token latency (TPOT). Because every decode iteration reads all 16 GB of an 8B model's weights from GPU High-Bandwidth Memory (HBM) (ultra-fast memory stacked on the GPU chip) regardless of batch size, packing 80–120 concurrent streams multiplies output tokens per dollar — until reading their combined KV cache pushes step latency past the 50 ms TPOT budget. Automated benchmarking finds each model's highest safe concurrency before latency degrades.
  • Prefix-affinity routing vs. uniform load spreading. Routing identical system prompts to the same replica reuses cached KV pages and slashes prefill compute, but viral prompts can create a hot GPU. Enforcing a 1.25x bounded-load cap preserves most cache hits while bounding worst-case queues, and salting cache keys with tenant_id gives up cross-tenant cache sharing to prevent timing side channels (inferring another tenant's prompts from fast response times).
  • Burst headroom vs. raw GPU utilization. Because loading multi-gigabyte weights and warming CUDA kernels takes 20–90+ seconds, running real-time GPUs at 95% occupancy guarantees SLO breaches during bursts. Targeting 70% real-time KV occupancy preserves burst headroom, while backfilling spare GPUs with preemptible offline batch shards recovers the otherwise-idle GPU-hours.
  • Shared vs. dedicated vs. isolated multi-tenancy. Mixing tenant requests (and ~27 MB LoRA low-rank fine-tune adapters) inside one shared base-model pool yields the lowest cost per million tokens, whereas dedicated whole GPUs or hardware MIG (Multi-Instance GPU) partitions eliminate noisy neighbors at the price of idle capacity, and microVM sandboxes (lightweight virtual machines with isolated guest kernels) with blocked internet egress safely run untrusted custom containers at higher operational overhead.
  • Decoupled content-addressed artifacts vs. monolithic container images. Keeping runtime images generic and mounting immutable SHA-256 weight digests from a node-local NVMe cache avoids pulling 50+ GB container layers on every update, trading a small node-agent cache service for 5–10x faster rollouts and instant pointer-flip rollbacks.
  • CPU vs. GPU right-sizing. GPUs deliver ~18x lower cost per request at full saturation for small neural networks, yet carry a high hourly price floor ($0.80/h for an L4 vs. $0.20/h for a 4-vCPU pod). Benchmarking each model sets an objective QPS crossover (~80 req/s for 1 replica, ~160 req/s with a 2-replica availability minimum) instead of guessing.

Common mistakes

  • Autoscaling LLMs on raw GPU compute utilization. GPU Streaming Multiprocessor (SM) utilization (the percentage of time GPU compute cores have at least one active warp) jumps near 100% with even a single decode stream because reading weights saturates memory cycles; scale on KV cache occupancy, queue wait time, and active sequence count instead.
  • Using round-robin load balancing for LLM endpoints. Round-robin treats a 50-token query and an 8,000-token document as equal load and destroys prefix-cache locality across replicas.
  • Static batching and contiguous max_tokens reservation. Waiting for the longest answer in a batch to finish leaves GPUs idle, and reserving max_tokens up front wastes 60–80% of KV memory compared to paged KV caching (allocating small fixed-size token blocks on demand).
  • Baking model weights into Docker images or deploying mutable :latest tags. Multi-gigabyte images turn node scale-up into a container-registry bottleneck, and mutable tags make exact canary audits and instant rollbacks impossible.
  • Software time-slicing one GPU across different tenants. Standard OS/CUDA process sharing provides neither GPU memory fault isolation nor tail-latency protection; cross-tenant sharing must happen either inside a platform-governed engine (shared tier) or via hardware-partitioned MIG slices.
  • Comparing canary metrics against yesterday's baseline. Prompt lengths and traffic mix shift hour by hour; always compare canary pods against primary pods serving live traffic in the exact same time window.
  • Transparently retrying a failed stream after tokens already reached the client. Server-side retries mid-stream duplicate text in the caller's output; automatic retries are safe only before the first token is flushed and only when guarded by an idempotency key (a unique client-generated request ID that prevents duplicate execution or double billing).

Follow-up questions

  • How would you serve a frontier model that exceeds a single 8-GPU node, such as a 405B-parameter model? In BF16 (2 bytes per parameter), 405B weights require ~810 GB before KV cache, exceeding one 8 × 80 GB (640 GB) H100 node. First evaluate FP8 quantization (1 byte per weight, ~405 GB), which fits inside a single 8-GPU NVLink node with ~200 GB left for KV cache if offline accuracy gates pass; if full BF16 is required, combine intra-node tensor parallelism (splitting each layer's matrix math across 8 GPUs over NVLink) with inter-node pipeline parallelism (assigning consecutive layer blocks across 2 nodes connected by RDMA — Remote Direct Memory Access networking that transfers GPU memory directly across hosts with minimal CPU overhead). Schedule the 16-GPU unit atomically via gang scheduling (LeaderWorkerSet in Kubernetes, ensuring all 16 GPUs start together or none start) and pre-stage weights on local NVMe SSDs because cold-pulling 810 GB over object storage takes minutes.
  • When and how would you disaggregate prefill and decode onto separate GPU pools? Prefill is compute-bound and bursty, whereas decode is memory-bandwidth-bound and steady; co-locating them means huge prompt bursts still compete with decode steps even with chunked prefill. Disaggregated serving routes new prompts to a compute-tuned prefill pool, transfers the resulting KV cache tensors over RDMA/NVLink to a memory-bandwidth-tuned decode pool, and lets each pool scale independently with its own optimal batch size and tensor-parallel degree. Because shipping hundreds of megabytes of KV cache per request requires fast RDMA fabrics and a stateful session router, start with chunked prefill on unified pools and adopt disaggregation only for high-volume endpoints with long prompts and tight TPOT SLOs.
  • How do you meter and bill tenants fairly across shared, Multi-LoRA, and dedicated deployments? On dedicated and isolated tiers, bill reserved GPU-seconds from replica lease activation to termination regardless of idle time, because the tenant owns that hardware slice. On shared base models and Multi-LoRA pools, meter uncached input tokens, cached-prefix input tokens (discounted because they skip prefill compute), and output tokens (priced higher per token because decode occupies HBM bandwidth on every step) via idempotent InvocationMetered events keyed by request_id, adding a small VRAM-residency fee only if a tenant pins many idle LoRA adapters in memory. Reconcile router token events daily against internal serving-engine counters so every invoice line is auditable.

Follow-up questions

Similar questions

More Lambda interview questions

All 2 Lambda questions →