Design: LLM inference platform

In one sentence

A gateway enforces per-tenant token quotas and tiers; a router sends each request to the replica holding its cached prefix and LoRA adapter; engine pools autoscale on queue depth and KV usage, from warm pools.

Quotas and tiers apply before any GPU work; the router uses live engine signals for cache and adapter locality; pools grow from warm replicas, not from zero.

How it works

  • Targets: ~15 base models, hundreds of LoRA fine-tunes, p95 TTFT under 1 s, p95 TPOT under 50 ms.
  • Quota tokens, not requests: reserve prompt + max_tokens at admission and refund unused output at completion.
  • Prefix affinity must yield to load: in llm-d's benchmark, prefix-only routing completed ~55% of requests at high load.
  • The worst failure is a correlated collapse at peak: keep N+1 replicas and a ~10% retry budget.
  • Utilization is the biggest cost lever: ~$0.46 per M output tokens at 100% busy, ~$1.16 at 40%.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your LLM serving fleet autoscales when GPU utilization exceeds 80%. Overnight, at a fraction of peak traffic, every replica still reads ~95% and the fleet never scales down. At peak, p95 TTFT blows through the SLO. Which signal should drive scaling?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: an OpenAI-compatible API serving ~15 open-weight base models (8B to 400B+) plus hundreds of tenant LoRA fine-tunes, with streaming, an interactive and a batch tier, per-tenant token quotas and usage-based billing. Non-functional: interactive p95 TTFT under 1 s for prompts up to 8k tokens and p95 TPOT under 50 ms; 99.9% availability; a GPU bill that follows traffic, not peak.

Questions I'd ask:

  1. Which models and sizes, and how many fine-tunes are LoRA adapters versus full weights?
  2. Traffic shape: tokens per day, input:output ratio, prompt lengths, peak-to-average, batch share?
  3. Which SLOs per tier, promised per request or per tenant?
  4. Which GPUs: owned or cloud, reserved or elastic, in how many regions?
  5. May tenants share GPUs and KV cache, or do some need dedicated capacity?

The highest-cost failure is a correlated collapse at peak: a node dies or one tenant bursts, KV caches fill, preemptions and client retries amplify the load, and every tenant's TTFT blows up at once. The quiet runner-up is a fleet of reserved GPUs sitting idle.

High-level design

Admission: an LLM gateway maps the API key to a tenant and tier, counts prompt tokens with the model's tokenizer and reserves prompt + max_tokens from the tenant's token bucket (Rate limiting). Requests wait in per-tier queues; batch work only fills spare capacity (Batch inference).

Router: picks a replica of the right base model from a placement registry plus live signals each engine publishes: queue depth, KV-cache usage, cached prefix blocks and loaded LoRA adapters. Prefix locality turns a shared system prompt into skipped prefill (Prompt caching).

Engine pools: one pool per base model and GPU type. vLLM by default, SGLang for prefix-heavy agent traffic, TensorRT-LLM where peak efficiency pays for the extra operations (Self-hosted serving stack). Tensor parallelism inside one NVLink node, Continuous batching, PagedAttention & vLLM, prefix caching, multi-LoRA (LoRA & QLoRA) and FP8 weights. The largest models split into prefill and decode pools (Prefill vs decode).

Control plane: an autoscaler on queue depth and KV usage, warm replicas with weights pre-staged, a model registry, and health checks with draining. Metering: each response's usage (input, cached and output tokens) goes to a durable stream, then to billing and quota reconciliation (Token economics & cost estimation).

Code Router core: score replicas by cached prefix, adapter and load
pythonRouter core: score replicas by cached prefix, adapter and load
import hashlib
from dataclasses import dataclass, field

BLOCK = 16  # tokens per KV block; must match the engine's block size

@dataclass
class Replica:
    model: str                                       # base model it serves
    loras: set[str] = field(default_factory=set)     # adapters resident on GPU
    cached: set[bytes] = field(default_factory=set)  # prefix-block hashes, from KV events
    waiting: int = 0                                 # requests queued for a batch slot
    kv_util: float = 0.0                             # share of KV blocks in use
    draining: bool = False

def block_hashes(tokens: list[int], salt: str) -> list[bytes]:
    # Chained like the engine's: block i's hash covers every token before it.
    # The salt (tenant + adapter) keeps cache hits from crossing tenants.
    h, out = salt.encode(), []
    for i in range(0, len(tokens) - BLOCK + 1, BLOCK):
        h = hashlib.sha256(h + str(tokens[i:i + BLOCK]).encode()).digest()
        out.append(h)
    return out

def pick(replicas, model, lora, tokens, tenant):
    blocks = block_hashes(tokens, salt=f"{tenant}:{lora}")
    pool = [r for r in replicas if r.model == model and not r.draining and r.kv_util < 0.9]
    if not pool:
        raise Saturated(model)  # gateway queues interactive, returns 429 to batch

    def score(r: Replica) -> float:
        hit = next((i for i, b in enumerate(blocks) if b not in r.cached), len(blocks))
        return (2.0 * hit / max(len(blocks), 1)          # share of prefill skipped
                + (0.5 if lora is None or lora in r.loras else 0.0)
                - 1.0 * r.kv_util - 0.05 * r.waiting)    # weights: tune on replayed traffic
    return max(pool, key=score)
Real example

Acme's support bot (interactive tier) sends a 3,000-token prompt to llama-70b:acme-support-v3, a LoRA adapter, with max_tokens 500. The gateway resolves the key, counts tokens and reserves 3,500 from Acme's 2M tokens/minute bucket (~3 ms in Redis). The router scores the 30 replicas of the 70B pool: r7 has the adapter loaded and holds Acme's 2,400-token system prompt and tool schemas (150 blocks) at 60% KV usage, so it wins. r7 prefills only 600 new tokens instead of 3,000; the first token streams at ~300 ms against a 1 s p95 SLO. Decode emits 320 tokens at ~35 ms each, ~11 s of streaming. The usage event records 600 uncached and 2,400 cached input tokens plus 320 output; the unused 180 return to Acme's bucket.

Trade-offs +4 · −4

+ You gain

  • Prefix- and adapter-aware routing turns shared system prompts into skipped prefill, a large compute saving on chat and agent traffic.
  • Multi-LoRA serves hundreds of fine-tunes from one copy of each base model instead of one GPU set per fine-tune.
  • Token quotas and priority tiers keep one tenant's burst or a batch job from breaking interactive SLOs.
  • Scaling on queue depth and KV usage tracks real saturation, so capacity follows load instead of a misleading GPU util%.

− You pay

  • Stateful routing: cache affinity fights load balance, and hot tenants can pile onto a few replicas.
  • Warm replicas and N+1 headroom mean paying for idle GPUs: ~25% of the fleet in this design.
  • Disaggregated prefill and decode add KV transfer over RDMA, a ratio to retune and a new failure surface.
  • Each extra engine (SGLang, TensorRT-LLM) multiplies builds, benchmarks and on-call knowledge.

Use it when

You self-host open-weight or fine-tuned models for many teams or customers at sustained volume (tens of GPUs or more), with per-tenant SLOs, quotas and billing.

Avoid it when

Low or spiky volume, where a provider API is cheaper (API vs self-hosting), or one model for one team, where a single vLLM deployment behind a gateway is enough.

Numbers to know 5
  • Assumed peak for the 70B flagship: 60k output + 600k input tokens/s (~3× average). Decode: 60k ÷ ~1,500 tokens/s per H100 (assumed goodput at p95 TPOT ≤ 50 ms, FP8) = 40 GPUs.
  • Prefill: 600k × 50% cache misses × 140 GFLOP/token (2 × 70B) ≈ 42 PFLOP/s ÷ ~800 TFLOPS effective per H100 (~40% of 1,979 FP8 dense) ≈ 53 GPUs.
  • Fleet: 93 GPUs + ~25% headroom for N+1 and bursts ≈ 120 H100s (30 TP=4 replicas, 15 nodes) ≈ $220k/month at an assumed $2.50 per GPU-hour (Nov 2026).
  • Unit cost: 1,500 tokens/s × 3,600 s = 5.4M output tokens per GPU-hour → ~$0.46 per M at 100% busy, ~$1.16 at 40%: utilization is the biggest cost lever.
  • LoRA: rank 16 on every linear layer of Llama-3-70B ≈ 207M params ≈ 0.4 GB in BF16, ~0.3% of the base; hundreds fit in host RAM.
Common pitfalls 4
  • Scaling on GPU utilization: it reads ~100% even at batch 1. Scale on waiting requests and KV-cache usage, and alert on p95 TTFT burn.
  • Round-robin or least-connections balancing: it scatters a tenant's shared prefix across replicas, the hit rate collapses and every request pays full prefill.
  • One prefix cache shared by all tenants: a faster TTFT tells a prober that someone else sent that prefix. Salt cache keys per tenant (vLLM cache_salt).
  • Request-count quotas and unlimited client retries: after a node loss the survivors' queues grow and retries finish them off. Use token quotas, retry budgets, 429 with Retry-After, and shed batch first.
Interview questions 3

Answer out loud first, then reveal.

How many GPUs does this platform need?Show answer

I'd derive it per model from tokens, not requests. Peak output tokens/s divided by measured per-GPU decode goodput at the TPOT SLO gives decode GPUs; peak uncached input tokens/s times 2 × parameters in FLOPs, divided by realistic effective FLOPS, gives prefill GPUs. For the 70B flagship at 60k output and 600k input tokens/s with 50% cache hits, that's ~40 + ~53, about 120 H100s with N+1 and burst headroom. The goodput figure must come from a benchmark on our real prompt-length mix, because it moves a lot with context length, and I'd re-run it on every engine upgrade.

A node with 8 GPUs dies at peak. Walk me through it.Show answer

Two TP=4 replicas vanish, about 7% of a 30-replica pool. Health checks eject them within seconds; requests that hadn't started streaming retry elsewhere, and cut streams resume by re-prefilling prompt plus emitted tokens on another replica. N+1 headroom absorbs the dip, the autoscaler promotes warm replicas, and the batch tier is shed first so interactive SLOs hold. What actually kills platforms here is the retry storm, so the gateway enforces a retry budget and returns 429 with Retry-After to batch tenants. Then the bad GPU is cordoned and the node drained for repair.

Finance wants the GPU bill down 30% without breaking SLOs. Where do you look?Show answer

Utilization first, because idle GPUs are the biggest line: fill troughs with batch and eval jobs, and fold low-traffic full fine-tunes into LoRA adapters on shared bases. Then cost per token: FP8 weights and KV cache use half the memory of BF16, which buys bigger batches; prefix-aware routing raises cache hits, so less prefill; Speculative decoding where TPOT is the limit. Then the mix: send easy traffic to a smaller model if evals hold (Model routing & cascades). I'd ship each lever behind the same SLO dashboards, since most cost wins trade latency, and gate quantization on task evals, not just perplexity.

Deep dive 5

Routing: cache, adapters and load

Round-robin is wrong for LLMs: requests differ 100× in cost, and replicas differ in what they hold in cache. Each engine publishes KV events (blocks stored or evicted), queue depth and KV usage; the router scores replicas on longest cached prefix, adapter already loaded, and load. NVIDIA Dynamo's KV router and llm-d's scheduler weigh prefix overlap against load; the Gateway API Inference Extension adds LoRA affinity. Affinity must yield to load: in llm-d's benchmark, a prefix-only scorer completed ~55% of requests at high load, prefix plus load 100%. Salt prefix hashes per tenant (vLLM cache_salt) so cache hits can't leak across tenants through timing. Placement is a slower loop: every few minutes the registry decides which models run on which pools, and how many replicas each gets.

Engine pools and parallelism

One pool per base model and GPU type keeps replicas interchangeable. Size a replica by memory: a 70B in FP8 is ~70 GB of weights, so TP=4 on H100s leaves ~200 GB for KV cache, ~1.2M tokens with FP8 KV; tensor parallelism stays inside one NVLink node (GPU memory math). Chunked prefill stops a 100k-token prompt from stalling everyone's decode. Fine-tunes ride as LoRA adapters on the shared base: vLLM keeps a few on GPU and more in a host-RAM LRU, swapping in milliseconds instead of loading another 140 GB model. Disaggregate prefill and decode only for large models with long prompts and tight TPOT: you get independent scaling, but pay for KV transfer over RDMA (NIXL in Dynamo) and a prefill:decode ratio to retune as traffic shifts.

Autoscaling and cold starts

Scale on saturation, not GPU util%: waiting requests (vllm:num_requests_waiting) and KV-cache usage, with p95 TTFT burn as the alarm. Scale up fast (e.g., more than ~2 waiting per replica for 30 s) and down slowly (~15 min of low load) to avoid flapping. Cold start is the real constraint: provision a GPU node, pull a ~10 GB image, read 70 GB of weights (~70 s at ~1 GB/s from object storage), capture CUDA graphs: minutes. So keep warm capacity: a few loaded replicas per hot model, or engines in vLLM sleep mode with weights parked in host RAM, plus nodes with weights pre-staged on local NVMe. Long-tail models scale to zero under an explicit cold-start SLA, or become LoRA adapters. Batch work and preemptible GPUs fill the troughs and are evicted first.

Tenancy: quotas, tiers and metering

Quota tokens, not requests: one 100k-token prompt costs as much prefill as 50 prompts of 2k. At admission, reserve prompt + max_tokens from the tenant's tokens-per-minute bucket and refund unused output at completion; also cap concurrent streams per tenant, because long streams hold KV memory. Tiers map to engine priority (vLLM --scheduling-policy priority) and first claim on capacity; batch is admitted only below a utilization threshold and preempted first. Large customers buy reserved capacity: dedicated replicas behind the same router (Multi-tenant isolation in AI apps). Metering reads each response's usage block (input, cached input, output), writes an event keyed by request ID to a durable stream and bills idempotently; a cancelled stream bills the tokens actually generated. Reconcile metered usage against quota counters hourly.

Failures, draining and deploys

The failure unit is the replica: one bad GPU (an Xid error, an NVLink fault) takes down its whole TP group. Health checks run a tiny generation every ~10 s, not just a TCP probe, and the router ejects a replica on first failure. Requests that haven't started streaming retry elsewhere; a stream cut mid-way resumes by sending prompt plus tokens already emitted as a fresh prefill on another replica, so the client sees a pause, not an error. Keep N+1 replicas per pool and a gateway retry budget (~10% of traffic), or one lost node becomes a retry storm. Deploys drain: stop new requests, let streams finish (bounded by max_tokens × TPOT: 4k × 50 ms = 200 s), then stop. New engine versions canary on one replica, compared on TTFT, TPOT and errors.