Everyone builds model serving the same way the first time: wrap the model in a Flask route, load the weights once at startup, and call model.predict(x) for each request as it arrives. It works on a laptop with a small model and one user at a time. Then the interviewer makes it the real problem: the model is a multi-billion-parameter transformer that needs a GPU to run at all, you are getting tens of thousands of inference requests per second, each request must come back inside a strict latency SLA (say p99 < 200ms), the GPUs cost several dollars an hour each so you cannot waste a single one, and you must be able to roll out a new model version - a retrained weights file - without ever dropping a request or taking the service down.

The one-request-at-a-time Flask loop cannot do any of that. A GPU is a throughput machine: it is fast only when you feed it a big batch of work at once, and running it on a single request leaves 95% of its arithmetic units idle. So the central move of a serving platform is dynamic batching - you deliberately hold a request for a few milliseconds, collect every other request that arrives in that window, run them through the GPU as one fused batch, then split the results back apart. That one decision - how long to wait, how big a batch to form, how to do it without blowing any individual request’s latency budget - is the whole game. Get batching right (plus routing across replicas and swapping model versions live) and the platform is efficient, fast, and always up. Get it wrong and you either melt money on idle GPUs, or you breach SLAs by waiting too long, or you drop requests every time you deploy.

Let me do it properly.

Functional Requirements (FR)

In scope:

  • Synchronous prediction. A client sends an inference request (a model name, optionally a version, and the input payload - a prompt, an image tensor, a feature vector) and gets back the model’s output (logits, generated tokens, a classification, an embedding) within a latency SLA. This is the core read-like path.
  • Multi-model hosting. The platform hosts many distinct models at once (a ranking model, an embedding model, a vision classifier, an LLM), each with its own hardware needs and SLAs, sharing one fleet of accelerators. A request names which model it wants.
  • Model versioning. Each model has multiple versions (v3, v4, v5). A request can target a specific version or the “default/production” alias. The platform can promote, roll back, and run several versions side by side.
  • Zero-downtime rollout. Deploying a new version - loading new weights onto GPUs - must happen without dropping requests or exceeding SLAs, with support for canary (route 5% of traffic to the new version), shadow (mirror traffic to the new version but discard its output, for validation), and instant rollback.
  • Dynamic batching. The platform groups concurrently arriving requests for the same model/version into a batch to run efficiently on the GPU, transparently to the client, while respecting each request’s latency budget.
  • Autoscaling. Replicas scale up and down with load, because GPUs are expensive and traffic is spiky.

Explicitly out of scope (say this to control scope):

  • Model training. We serve trained weights handed to us as artifacts (a versioned file in object storage). Training, fine-tuning, and the data pipeline are a separate system; we are the inference platform.
  • Feature computation / feature store. For recommendation-style models, the features arrive in the request (or are fetched by an upstream service). We take the input tensor as the contract; we note where a feature store attaches.
  • Token-level streaming internals of a specific LLM runtime. We cover how batching and KV-cache-aware continuous batching differ for autoregressive models, but we do not reimplement a specific inference engine’s kernels.
  • The business logic / application calling us (a search backend, a chat app). We are the prediction API they depend on.

The one decision that drives everything: a model serving platform is a throughput-vs-latency machine built around the accelerator, where the scarce, expensive resource is GPU time, and the central tension is batching for GPU efficiency against per-request latency SLAs. You pay a deliberate, bounded wait (collect a batch) and a lot of GPU memory (weights + activations resident) to make inference cheap per request. So the design is dominated by the batching scheduler - how it forms batches, bounds the wait, routes to the right replica, and keeps serving while model versions change underneath it.

Non-Functional Requirements (NFR)

  • Scale: host ~200 distinct models across a fleet of ~500 GPUs. Aggregate ~50,000 inference requests/sec at peak across all models, heavily skewed - a few hot models take most of the traffic while a long tail of models get a trickle. Request sizes vary from tiny (a 512-feature vector, sub-millisecond on GPU) to heavy (an LLM generating 500 tokens, hundreds of milliseconds).
  • Latency (the hard target): per-model SLAs, typically p99 < 200ms end to end for a classification/embedding model, including queueing, batch-wait, GPU compute, and network. The whole batching design exists to stay under this while batching. For LLM generation, the relevant SLAs split into time-to-first-token (TTFT) < 500ms and inter-token latency < 50ms.
  • Throughput / efficiency (the other hard target): sustained GPU utilization > 70%. GPUs idle = money burned. Batching is how you convert spare latency budget into throughput, so utilization and latency are two ends of the same dial.
  • Availability: 99.95%+ for the prediction path. Inference backing a user-facing product (search ranking, chat) going down is a visible outage. This forces replication and graceful degradation.
  • Consistency: inference is effectively stateless per request for most models - the same input + same model version = same output, no cross-request state. The one exception is autoregressive generation, which keeps a per-sequence KV cache within a single request’s lifetime. Version routing is eventually consistent: after you promote v5, it is fine if a few in-flight requests still hit v4 for a second.
  • Durability: the platform holds no durable user data; model artifacts (weights) are the durable state and live in object storage / a model registry, versioned and immutable. Losing a serving node loses only in-flight requests on it (retried), not data.
  • Cost (a first-class constraint here): unlike most systems where you optimize latency and treat cost as secondary, here GPU cost is so high that cost-efficiency is a top-tier NFR. Every design choice - batch size, autoscaling aggressiveness, model-to-GPU packing, right-sizing accelerators - is partly a cost decision.

Back-of-the-Envelope Estimation (BoE)

Let me ground the design in numbers before drawing boxes.

Why one-request-at-a-time wastes the GPU:

A modern inference GPU does ~300 TFLOP/s (fp16/bf16).
A medium model forward pass = ~5 GFLOP per request.

Single request: 5 GFLOP / 300 TFLOP/s = ~16 microseconds of math...
  but kernel launch + memory transfer overhead per call is ~1-5 ms.
  So a batch of 1 spends ~95% of wall-clock NOT doing math.
  Effective utilization at batch=1: often < 10%.

Batch of 64 requests: the 5 GFLOP becomes ~320 GFLOP, the GPU
  does it in ~1 ms of actual math, overhead amortized across 64.
  Throughput per GPU jumps ~30-50x for the SAME hardware.
This 30-50x is the entire economic reason dynamic batching exists.

Request load and fleet sizing:

Peak aggregate:            50,000 requests/sec
Skew: top 10 models        ~80% of traffic = 40,000 req/s
      tail 190 models      ~20% = 10,000 req/s

For a hot model at, say, 10,000 req/s, with a GPU that sustains
  ~2,000 req/s per replica WHEN BATCHED well:
    replicas needed = 10,000 / 2,000 = 5 replicas (+1 headroom).
Without batching (200 req/s per replica): 50 replicas for the SAME
  model. Batching cuts the GPU bill ~10x.

Fleet: ~500 GPUs total, packed so hot models get many dedicated
  replicas and tail models share GPUs (multi-tenant packing).

The batch-wait latency budget:

SLA: p99 end-to-end < 200 ms. Budget split:
  network in/out            ~20 ms
  queue + batch-wait window  <= W ms   (the tunable)
  GPU compute (batched)     ~30-80 ms
  deserialization/overhead  ~10 ms

So the batch-wait window W must be small - typically 5-20 ms.
You wait AT MOST W ms to form a batch; if the batch fills before W,
fire immediately. W is the knob that trades a little tail latency
for a lot of GPU efficiency. Setting W too high breaches SLA;
too low starves the batch and wastes the GPU.

GPU memory (the packing constraint):

A 7B-parameter model in fp16 = 7B * 2 bytes = 14 GB of weights.
An 80 GB GPU:
  weights          14 GB
  KV cache / activations for a batch   can be 10s of GB for LLMs
  leaves room for ONE such model + its batch, not many.

A small model (100 MB weights) -> dozens fit on one GPU
  (multi-model packing on shared GPUs for the tail).
So hot/big models get dedicated GPUs; small tail models are packed
many-per-GPU. GPU memory, not CPU, caps how models map to hardware.

Storage / registry:

200 models x (avg 2 GB/version) x ~5 live versions
  = ~2 TB of model artifacts in object storage. Trivial to store;
  the cost is LOADING a version onto a GPU (seconds to minutes for
  big weights), which is why rollouts pre-warm replicas (deep dive).

The takeaway: this is a GPU-bound, latency-SLA-constrained, cost-dominated throughput system. The scarce resource is accelerator time; batching converts spare latency budget into 30-50x throughput; GPU memory caps how models pack onto hardware; and loading weights is slow enough that version rollout must be carefully staged. Every design choice - the batch scheduler, the router, replica autoscaling, version management - exists to keep GPUs busy and requests inside their SLA while weights change underneath.

High-Level Design (HLD)

A serving platform is a path from client to GPU and back, with three pieces of intelligence in the middle: a router (pick which model/version and which replica), a batch scheduler per replica (form batches under the wait budget), and a control plane (manage versions, replicas, and rollouts). Model weights live in a registry/object store; replicas are GPU processes each holding a loaded model version.

                         ┌──────────────┐
   clients ─────────────►│  Inference   │  (REST/gRPC: model, version?, input)
                         │   Gateway    │
                         └──────┬───────┘
                                │
                     ┌──────────▼───────────┐
                     │       ROUTER          │  stateless
                     │ - resolve model+ver   │  (reads routing
                     │   (alias -> version)  │   table from
                     │ - split canary/shadow │   control plane)
                     │ - pick a replica      │
                     │   (load-aware)        │
                     └──────────┬───────────┘
                                │ route to a replica of (model, version)
       ┌────────────────────────┼─────────────────────────┐
       │                        │                          │
┌──────▼───────┐         ┌───────▼──────┐          ┌────────▼──────┐
│  REPLICA A   │         │   REPLICA B   │          │   REPLICA C   │
│ model=rank v5│         │ model=rank v5 │          │ model=rank v6 │ (canary)
│ ┌──────────┐ │         │               │          │               │
│ │ REQUEST  │ │         │               │          │               │
│ │  QUEUE   │ │         │               │          │               │
│ └────┬─────┘ │         │               │          │               │
│ ┌────▼─────┐ │         │               │          │               │
│ │  BATCH   │ │         │               │          │               │
│ │SCHEDULER │ │  (wait <=W or fill B)   │          │               │
│ └────┬─────┘ │         │               │          │               │
│ ┌────▼─────┐ │         │               │          │               │
│ │   GPU    │ │         │   GPU         │          │   GPU         │
│ │ fwd pass │ │         │   fwd pass    │          │   fwd pass    │
│ │ on batch │ │         │               │          │               │
│ └──────────┘ │         │               │          │               │
└──────────────┘         └──────────────┘          └───────────────┘
       │                                                    │
       └─── results split back to per-request responses ────┘

┌──────────────────────────────────────────────────────────────────┐
│ CONTROL PLANE (strongly consistent, e.g. Raft/etcd-backed):        │
│  - model registry (versioned immutable weights -> object store)    │
│  - routing table (model -> {version: weight%}, aliases)            │
│  - replica inventory, health, GPU placement, autoscaler            │
│  - rollout state machine (canary %, shadow, promote, rollback)     │
└──────────────────────────────────────────────────────────────────┘
     ▲                                     │ pulls weights on load
     │ artifacts                           ▼
┌────┴───────────┐                 ┌────────────────┐
│ Model Registry │◄───train jobs   │ Object Storage │ (weights, GBs)
└────────────────┘                 └────────────────┘

Prediction path - one request, end to end:

  1. A request hits the inference gateway (gRPC/REST): {model: "rank", version?: "default", input: tensor}. The gateway authenticates, validates the input shape, and forwards to the router.
  2. The router resolves the target: it maps the model name (and the requested version or the default alias) to a concrete version using the routing table from the control plane. If a canary/shadow split is active, it decides this request’s fate here (e.g. 5% chance to v6, else v5; shadow-mirror a copy to v6 with its response discarded).
  3. The router picks a replica of that (model, version) using load-aware selection - prefer the replica with the shortest queue / lowest in-flight batch, not round-robin, because a replica mid-GPU-pass is busy. It forwards the request there.
  4. The replica drops the request into its in-memory request queue. The batch scheduler running on that replica pulls from the queue: it accumulates requests until either the batch reaches the max size B or the oldest request in the batch has waited W milliseconds - whichever comes first. Then it fires the batch.
  5. The batch is padded/collated into one tensor and run through the GPU forward pass as a single call. The GPU produces one output tensor for the whole batch.
  6. The scheduler splits the batch output back into per-request responses (each request kept its slot index) and returns each to its waiting caller. The router/gateway relays the response to the client.

Rollout path - deploying a new version, end to end:

  1. A new weights artifact (v6) is registered in the model registry (immutable, versioned, in object storage).
  2. The control plane spins up new canary replicas that pull v6 weights from object storage and load them onto GPUs (seconds to minutes). The replicas run a health/warmup check (a few synthetic inferences to JIT-compile kernels and fill caches) before being marked ready.
  3. The control plane updates the routing table: rank -> {v5: 95%, v6: 5%}. The router now sends 5% of live traffic to v6 while v5 keeps serving the rest. Metrics (latency, error rate, output distribution) are watched.
  4. If the canary is healthy, the split is shifted gradually (5% -> 25% -> 50% -> 100%), adding v6 replicas and draining v5 replicas as it goes. When v6 is at 100%, the default alias is repointed to v6 and old v5 replicas are torn down (GPUs freed).
  5. If the canary is unhealthy at any step, the control plane rolls back instantly by resetting the routing table to 100% v5 - which is cheap because v5 replicas were never torn down during canary. No request is dropped because old replicas keep serving throughout.

Failure handling: if a replica dies mid-batch, its in-flight requests fail and are retried by the router against another replica (idempotent - same input, same version = same output). If a GPU node is lost, the autoscaler/control plane replaces it and reloads the model. The control plane itself is Raft-backed so the routing table and rollout state survive node loss.

The architectural insight: the batch scheduler lives at the replica (close to the GPU, where it can see the queue), the router is a stateless load-aware dispatcher, and the control plane owns all slow-changing truth (versions, routing weights, placement) in a strongly consistent store - so that forming batches, choosing replicas, and swapping versions are three decoupled concerns that each scale and fail independently.

Component Deep Dive

Three hard parts: (1) dynamic batching - the core scheduler that trades a bounded wait for GPU throughput without breaching SLAs, (2) routing and autoscaling across replicas under skewed, spiky load, and (3) zero-downtime version rollout - canary, shadow, and rollback while weights load slowly. I walk each from naive to scalable.

1. Dynamic Batching: the core scheduler

Batching is the whole reason the platform exists. The scheduler decides when to stop waiting and what to run.

Approach A: No batching - one request per GPU call (the naive instinct)

Each request runs model.predict(x) on the GPU immediately on arrival.

request arrives -> GPU forward pass on batch of 1 -> respond

Where it breaks - immediately and expensively: a GPU forward pass has large fixed overhead (kernel launches, memory transfer, Python/driver dispatch) that dwarfs the math for a single small request. Utilization sits below 10%; you need ~10x the GPUs to carry the load, at thousands of dollars/GPU/month. It is latency-optimal (zero wait) but economically ruinous and does not scale - you run out of GPUs long before you serve 50K req/s. The GPU is a throughput device starved by one-at-a-time feeding.

Approach B: Static (fixed-size) batching

Wait until exactly B requests have arrived, then run them as one batch.

accumulate requests until count == B (say 32), then fire the batch.
  • Why it is tempting: big batches = great GPU utilization. When traffic is high and steady, 32 requests arrive in a blink and the GPU stays full.
  • Where it breaks: tail latency and starvation. If traffic dips, the 32nd request may never arrive in time - the first request sits waiting for B to fill and blows its SLA while the batch is half-empty. A fixed B has no notion of a deadline. Under bursty, skewed load (which is exactly our profile) static batching either starves (waits forever for a full batch) at low load or is fine at high load - and you cannot have one fixed number that is right for both. It optimizes throughput while ignoring the latency SLA, which is half the spec.

Approach C: Dynamic batching - bounded by size OR a max-wait window

Form a batch that fires when either it reaches max size B or the oldest queued request has waited W milliseconds. This bounds latency and still batches aggressively when traffic is high.

BATCH SCHEDULER LOOP (per replica, one model/version):
  batch = []
  deadline = none
  loop:
    req = queue.poll(timeout = time-until-deadline)
    if req:
        if batch empty: deadline = now + W      # start the clock
        batch.append(req)
        if len(batch) == B: fire(batch); reset    # full -> fire now
    else:  # deadline hit (W elapsed) with a partial batch
        if batch: fire(batch); reset               # fire what we have

fire(batch):
  tensor = collate(batch)        # pad/stack into one input tensor
  out = gpu.forward(tensor)      # ONE GPU call for the whole batch
  for i, req in enumerate(batch):
      req.respond(out[i])        # split results by slot index
  • Why it works: at high load the batch fills to B almost instantly (max throughput, the W timer never fires); at low load the W timer caps how long any request waits (SLA protected, smaller batch accepted). It self-adjusts to traffic without a config change. W and B are the two dials: W is the latency-vs-efficiency trade (how much of the budget you spend forming batches), B is capped by GPU memory (activations for B requests must fit).
  • Where it still needs care: W must be set from the SLA budget (BoE: ~5-20ms), not guessed. And a single huge request mixed with tiny ones can distort the batch. Which leads to the refinements.

Refinements that make dynamic batching production-grade

ADAPTIVE W AND B: tune by observed load. Under high QPS, shrink W
  (batches fill on size anyway) to cut tail latency; under low QPS,
  you are latency-bound not throughput-bound, so a slightly larger W
  is fine. Some schedulers learn B from a GPU latency profile:
  pick the largest B whose forward-pass time still fits the budget.

QUEUE PRIORITY / DEADLINES: stamp each request with its deadline on
  arrival. The scheduler can fire early if the earliest deadline is
  near, and can reorder so a request about to breach SLA is not stuck
  behind a just-arrived one. This decouples fairness from arrival order.

BUCKET BY SHAPE (for variable-length inputs): padding a batch to the
  longest member wastes GPU on the short ones. Group requests of
  similar size/sequence-length into the same batch (length bucketing)
  so padding overhead stays low.

The special case: continuous batching for autoregressive (LLM) generation

Plain dynamic batching assumes every request in the batch finishes in one forward pass. An LLM generating 500 tokens runs ~500 forward passes, and different requests finish at different lengths. Static batching here is terrible: the whole batch is held hostage until the longest generation completes, and a slot whose sequence finished early sits idle.

NAIVE LLM BATCH: run the batch until the LONGEST sequence is done.
  A request generating 10 tokens waits for one generating 500.
  Idle slots waste the GPU; short requests get awful tail latency.

CONTINUOUS (IN-FLIGHT) BATCHING: schedule at the TOKEN step, not the
  request. After each decode step, evict finished sequences from the
  batch and admit newly-arrived requests INTO the running batch's
  free slots. The batch composition changes every step. This keeps
  the GPU full of active sequences and lets short requests leave
  early - the standard for LLM serving. The per-sequence KV cache is
  the state that must be managed (paged, to avoid fragmentation).

So batching is not one algorithm: dynamic size-or-wait batching for single-pass models, continuous token-level batching for autoregressive generation - both serving the same goal of keeping the GPU saturated without any request waiting past its deadline.

2. Routing and Autoscaling Across Replicas

One replica cannot serve a hot model’s traffic, and load is skewed and spiky. The router spreads requests across replicas; the autoscaler adjusts replica count. Both are harder than they look because a GPU replica’s “busyness” is not a simple CPU number.

Routing - Approach A: round-robin (naive)

Send request 1 to replica 1, request 2 to replica 2, cycling.

Where it breaks: a GPU replica mid-forward-pass is fully occupied for the duration of that batch; a replica with an empty queue is idle. Round-robin ignores this and will cheerfully queue a request behind a replica that just started a big batch while another replica sits free. With variable batch times, round-robin produces lumpy queues and bad tail latency. It assumes uniform, instant service - false for batched GPU work.

Routing - Approach B: load-aware least-outstanding-requests

The router tracks, per replica, the number of in-flight requests (queued + in the current batch), and sends each new request to the least-loaded replica.

for each (model, version), router keeps a live count of
  outstanding requests per healthy replica.
route(req) -> replica with min(outstanding), ties broken randomly.
Replicas report queue depth / in-flight via fast health pings or
  piggybacked on responses, so the router's view is near-real-time.
  • This naturally routes around a replica busy with a long batch and fills idle replicas first. Combined with the replica-side scheduler, it keeps batches healthy without a central coordinator. A power-of-two-choices variant (pick 2 replicas at random, send to the less loaded) gets most of the benefit with far less global state - good when there are many replicas.
  • The router stays stateless with respect to durable data: its only state is this soft, refreshable load view. If a router dies, another takes over with no data loss.

Autoscaling - the GPU-specific problem

The naive autoscaling signal is CPU utilization. On a GPU box that is meaningless - the CPU is often idle while the GPU is pegged. The right signals are GPU utilization, batch queue depth, and latency headroom.

SCALE-OUT when (per model):
  p99 latency approaches the SLA, OR
  average batch queue depth stays high (requests waiting), OR
  GPU utilization is pegged AND requests are still queueing.

SCALE-IN when:
  GPU utilization and queue depth are low for a sustained window,
  AND removing a replica would not push p99 past the SLA.

The hard constraints that make GPU autoscaling different from stateless web autoscaling:

  • Cold start is slow and expensive. A new replica must pull multi-GB weights from object storage, load them onto the GPU, and warm up (JIT kernels). That is seconds to minutes - far too slow to react to a traffic spike reactively. Fixes: keep a warm pool of pre-loaded standby replicas for hot models, pre-warm on predicted load (schedules, known spikes), and scale ahead of demand using a predictive signal, not purely reactive.
  • Scale-to-zero for the tail. The 190 cold models cannot each hold a dedicated GPU idle. Tail models are packed many-per-GPU (small weights share a device) or scaled to zero and loaded on demand, accepting a cold-start latency hit for the first request (a documented trade-off: the tail gets worse first-request latency in exchange for not burning GPUs on idle models).
  • GPU is indivisible-ish. You scale in whole replicas (whole GPUs, or GPU partitions via MIG/time-slicing for small models). You cannot add “10% of a GPU” like a CPU. So autoscaling is coarser-grained and packing (which models share which GPU) becomes a bin-packing scheduling problem the control plane solves.

So routing and scaling together: load-aware (least-outstanding or power-of-two) routing fills GPUs evenly, and autoscaling driven by GPU-util + queue depth + latency headroom - with warm pools to hide slow cold starts and many-per-GPU packing for the cold tail - keeps the fleet busy without burning idle accelerators.

3. Zero-Downtime Version Rollout

A new weights file must go live without dropping a request or breaching SLA, and must roll back instantly if it misbehaves. The naive deploy fails because loading weights is slow and models can regress silently.

Approach A: In-place swap (naive)

Take each replica, load the new weights over the old, resume.

Where it breaks: loading multi-GB weights onto a GPU takes seconds to minutes, during which that replica serves nothing - requests queue up and breach SLA or get dropped. Do it to all replicas at once and the service is down; do it one at a time and you still have a rolling outage window per replica plus reduced capacity throughout. Worse, if v6 is bad (higher latency, degraded accuracy, a crash on some input), you have already discarded v5 on the swapped replicas and rollback means another slow reload. In-place swap conflates “deploy” with “be down,” and gives no safe validation step.

Approach B: Blue-green with the routing table (no in-place swap)

Never mutate a running replica’s weights. Stand up new replicas for v6 alongside the live v5 replicas, and flip traffic via the routing table.

state:  rank -> { v5: 100% }        # v5 replicas serving
step 1: spin up v6 replicas, load weights, WARM UP, mark ready.
        (v5 untouched, still at 100% - no capacity lost)
step 2: rank -> { v5: 100%, v6: shadow }   # optional shadow first
step 3: rank -> { v5: 95%, v6: 5% }        # canary
step 4: ramp -> 25% -> 50% -> 100% while adding v6 / draining v5
step 5: default alias -> v6; tear down v5 replicas (free GPUs)
rollback at ANY step: rank -> { v5: 100% } instantly (v5 still alive)
  • Zero downtime because old replicas keep serving at full capacity until new ones are proven and ramped. The only cost is temporarily running both versions (extra GPUs during the rollout) - a deliberate cost-for-safety trade.
  • Rollback is a routing-table edit, not a redeploy - instant and cheap, because v5 was never torn down during canary. This is the single most important property.

The two validation tools: canary and shadow

CANARY: route a small % of REAL traffic to v6 and serve its real
  responses to those users. Watch error rate, p99 latency, and
  business/quality metrics on the canary slice vs v5. Ramp only if
  healthy. Risk: real users see v6 output, so a bad canary affects
  that small %. Good for catching latency/crash regressions live.

SHADOW (mirror): send a COPY of real traffic to v6 but DISCARD its
  output - users only ever see v5's response. Compare v6's outputs
  and latency against v5 offline. Risk: ZERO user impact (output
  thrown away), so you can validate correctness/parity before any
  real user is exposed. Cost: you pay GPU for shadow inferences that
  serve no user. Good for validating output parity and load behavior
  BEFORE a canary exposes anyone.

The standard pipeline is shadow first (validate parity, zero user risk), then canary (validate live, small user risk), then ramp, then promote - with automated rollback triggers (if canary p99 or error rate crosses a threshold, auto-reset the routing table to the old version).

Weight loading and warmup - the detail that makes it safe

A replica marked “ready” before it is actually warm will blow the first requests’ latency (cold kernels, unfilled caches). So a v6 replica is only added to the routable pool after it has loaded weights and run a handful of synthetic warmup inferences to JIT-compile GPU kernels and fill allocator/caches. The control plane gates the routing-table change on this readiness signal.

So version rollout is blue-green by routing table, never in-place: stand up warmed new replicas, validate with shadow then canary, ramp via traffic weights, and keep old replicas alive so rollback is one atomic routing edit - trading some extra GPU during the overlap for zero-downtime, instantly-reversible deploys.

API Design & Data Schema

A serving platform exposes a prediction API, a model-management API, and a rollout/admin API. Internally the durable state is small (a registry + routing table); the heavy state is GPU-resident model weights.

Prediction API

POST /v1/models/{model}/predict            # synchronous inference
  Headers: Authorization, X-Request-Id (for idempotent retry)
  {
    "version": "default",                  # or explicit e.g. "5"
    "inputs": { "features": [0.1, ...] }   # or "prompt", "image", etc.
    "parameters": { "max_tokens": 256 }    # model-specific (LLM, etc.)
  }
  -> {
       "model": "rank", "version": "5",    # which version actually served
       "outputs": { "scores": [...] },
       "latency_ms": 41
     }

POST /v1/models/{model}/predict:stream     # token streaming (LLM)
  -> server-sent events, one chunk per token/step (TTFT + inter-token)

POST /v1/models/{model}/predict:batch      # client-side pre-batched inputs
  { "instances": [ {...}, {...}, ... ] }   # offline/bulk scoring path

Model management & registry API

POST /v1/registry/models/{model}/versions  # register a new version
  { "artifact_uri": "s3://models/rank/v6/",  # immutable weights
    "runtime": "triton|vllm|custom",
    "hardware": { "gpu": "h100", "count": 1 },
    "max_batch_size": 32, "max_batch_delay_ms": 10 }
  -> { "version": "6", "status": "registered" }

GET  /v1/registry/models/{model}/versions   # list versions + status
GET  /v1/models/{model}/metadata             # input/output schema, SLAs

Rollout / admin API

POST /v1/rollouts/{model}                    # drive a rollout
  { "target_version": "6",
    "strategy": "canary",
    "steps": [ {"traffic": 5}, {"traffic": 25}, {"traffic": 50},
               {"traffic": 100} ],
    "shadow_first": true,
    "auto_rollback": { "max_p99_ms": 200, "max_error_rate": 0.01 } }

PUT  /v1/routing/{model}                     # set traffic split directly
  { "split": { "5": 95, "6": 5 }, "default": "5" }

POST /v1/rollouts/{model}/rollback           # instant: route 100% to prev
GET  /v1/fleet/health                        # replicas, GPU util, queues

Data model - a small consistent control store + GPU-resident weights

SQL vs NoSQL is the wrong framing for the hot path, but it matters for the control plane. The control-plane state is small, relational-ish, and must be strongly consistent (the routing table is read on every request and must not diverge across routers), so it lives in a strongly consistent store (Raft/etcd-style or a small SQL DB with a consistent cache), not an eventually-consistent NoSQL store - a split-brain routing table would send traffic to a torn-down version. The model artifacts are large immutable blobs in object storage (NoSQL-of-blobs), referenced by URI. The hot inference state (loaded weights, KV caches) is GPU memory, not a database at all.

1. Model registry (durable, in control store + object storage):

model_version
  model_name     STRING        # "rank"
  version        INT           # 6  (monotonic, immutable once registered)
  artifact_uri   STRING        # s3://models/rank/v6/  (immutable weights)
  runtime        ENUM          # triton | vllm | custom
  hardware_spec  JSON          # gpu type, count, memory need
  batch_params   JSON          # max_batch_size B, max_batch_delay W
  status         ENUM          # registered | loading | ready | retired
  created_at     TIMESTAMP
  PRIMARY KEY (model_name, version)
  - immutable artifact; a new weights file is always a NEW version,
    never an overwrite -> clean rollback and reproducibility.

2. Routing table (strongly consistent, read on every request):

routing
  model_name   STRING   PRIMARY KEY
  split        JSON      # { "5": 95, "6": 5 }  traffic % per version
  shadow       JSON      # { "6": true }        mirror-and-discard
  default_ver  INT       # version the "default" alias resolves to
  version      INT64     # optimistic-lock / generation for safe updates
  - cached at every router with a short TTL + change notification
    (watch), so routing changes propagate in ~sub-second but reads
    are local and fast. Strong consistency on WRITE prevents split brain.

3. Replica inventory (control plane, soft/live state):

replica
  replica_id   STRING
  model_name   STRING
  version      INT
  node_id      STRING        # which GPU node
  gpu_index    INT           # which device (for packing)
  state        ENUM          # loading | warming | ready | draining
  in_flight    INT           # live load signal for the router
  gpu_util     FLOAT         # autoscaler signal
  last_heartbeat TIMESTAMP
  INDEX (model_name, version, state)   # router queries ready replicas
  - ephemeral: rebuilt from heartbeats; not the source of truth for
    anything durable. Lost on restart and re-reported.

4. Request queue (per replica, in-memory only):

queue entry (RAM, never persisted)
  request_id   STRING
  arrival_ts   MONOTONIC     # for the W deadline
  deadline_ts  MONOTONIC     # arrival + SLA budget, for priority
  input_tensor BYTES         # collated into a batch
  respond_to   CHANNEL       # where to send the split result
  - pure in-memory; a replica crash loses its queue and those requests
    are retried by the router elsewhere (idempotent).

Why these choices: the routing table is the one thing that must be strongly consistent and globally agreed (it decides which version every request hits during a rollout), so it sits in a Raft-backed store and is cached at routers with watches - strong on write, fast on read. Model versions are immutable rows pointing at immutable blobs, which is what makes rollback a pointer change rather than a data migration. Replica inventory is deliberately soft (heartbeat-rebuilt) because it changes constantly and losing it is harmless. The request queue is never persisted because a dropped in-flight request is simply retried - durability belongs to the weights, not to transient inference work.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each:

1. Single-request GPU calls (breaks before anything else). Batch-of-1 forward passes leave the GPU >90% idle; you run out of GPUs at a fraction of target load. Fix: dynamic batching - group concurrently arriving requests and run one fused forward pass, firing on max batch size B OR max wait W, whichever comes first. 30-50x throughput per GPU for the same hardware. W is set from the SLA budget; B is capped by GPU memory. This is the foundational fix.

2. Batch scheduler vs latency SLA. A fixed batch size starves at low load (first request waits forever for the batch to fill) and ignores deadlines. Fix: the size-or-wait rule plus per-request deadlines and adaptive W/B - at high load batches fill on size and W never fires; at low load W caps the wait so no request breaches SLA. For LLMs, continuous (in-flight) batching at the token step so short generations leave early and the GPU stays full.

3. Uneven replica load / tail latency. Round-robin queues requests behind replicas mid-batch while others idle. Fix: load-aware routing (least-outstanding-requests or power-of-two-choices) using a near-real-time in-flight count per replica, so new requests fill the least-busy GPU. Retry failed in-flight requests on another replica (idempotent).

4. Cold start on scale-up. A new replica needs seconds-to-minutes to pull multi-GB weights, load them to GPU, and warm kernels - far too slow to react to a spike. Fix: warm standby pools for hot models, predictive / scheduled pre-warming ahead of known spikes, and readiness gating (a replica joins the routable pool only after weights load + synthetic warmup inferences). Autoscale on GPU-util + queue depth + latency headroom, not CPU.

5. The cold-model tail burning GPUs. 190 low-traffic models cannot each hold a dedicated idle GPU. Fix: multi-model packing (many small models share a GPU via memory packing / MIG partitions / time-slicing) and scale-to-zero for the coldest, accepting a first-request cold-start hit. Hot models get dedicated, densely-batched replicas; the control plane solves model-to-GPU placement as bin-packing.

6. Deploy = downtime (version rollout). In-place weight swap takes a replica offline during the slow load and discards the old version, making rollback another slow reload. Fix: blue-green by routing table - stand up warmed new-version replicas alongside the old, shift traffic via the routing split, keep old replicas alive. Rollback is one atomic routing edit. Validate with shadow (mirror + discard, zero user risk) then canary (small live %), with auto-rollback on latency/error thresholds.

7. Routing table split-brain. If routers disagree on the traffic split during a rollout, traffic can hit torn-down or wrong versions. Fix: the routing table lives in a strongly consistent (Raft) store, written atomically with an optimistic-lock generation, and cached at routers with watch-based invalidation - strong on write, fast local read, sub-second propagation. Tear down old replicas only after the split has fully propagated.

8. Hot model exceeding one replica / head-of-line from heavy requests. A giant request (long sequence) in a batch slows every co-batched request; one hot model saturates its replicas. Fix: length/shape bucketing so heavy and light requests do not share a padded batch; scale replicas horizontally for the hot model (routing spreads across them); separate queues/replica pools for heavy vs light request classes of the same model so a 500-token generation never sits in the same batch as a 10-token one.

9. GPU node failure. A lost node takes its loaded weights and in-flight batch with it. Fix: N+1 replica redundancy per hot model across nodes/zones so losing one does not drop capacity below SLA; in-flight requests on the dead node are retried elsewhere (idempotent); the control plane reschedules a replacement replica and reloads weights from the registry. The control plane is Raft-backed so routing/rollout state survives.

10. Cost blowout. GPUs are the dominant cost; over-provisioning for peak wastes thousands/month, shadow traffic doubles inference cost during validation. Fix: batch aggressively (the cheapest lever - more throughput per GPU), right-size accelerators (do not put a tiny model on an H100), pack the tail, scale in promptly when queue depth and GPU-util drop, and time-box shadow to the validation window rather than running it forever. Cost is a monitored, first-class metric, not an afterthought.

Wrap-Up

The trade-offs that define this design:

  • Deliberately wait to go faster overall. The counterintuitive core move is adding latency (hold each request up to W ms) to gain 30-50x throughput by batching - because a GPU idle on batch-of-1 wastes 90% of itself. We make the wait a bounded dial (W from the SLA budget, B from GPU memory, fire on whichever hits first) so we spend only spare latency budget, never the SLA.
  • Batching is two algorithms, not one. Single-pass models use size-or-wait dynamic batching; autoregressive generation uses continuous (in-flight, token-level) batching so short requests leave early and the GPU stays saturated - same goal, different mechanics, because an LLM is 500 forward passes with per-sequence KV state.
  • Route by real GPU load, scale on GPU signals. Round-robin and CPU-based autoscaling both lie about a batched GPU’s busyness, so we route by least-outstanding-requests and scale on GPU-util + queue depth + latency headroom - and we hide slow multi-GB cold starts behind warm pools and predictive pre-warming rather than reacting to spikes.
  • Pack the tail, dedicate the head. Hot models get dedicated, densely-batched replicas; the long tail of cold models shares GPUs or scales to zero, trading first-request latency for not burning accelerators on idle models - because cost is a first-class NFR here, not a footnote.
  • Deploy by routing table, never in place. New versions come up as warmed replicas beside the old ones; shadow then canary validate with zero-then-small user risk; traffic ramps via a strongly-consistent routing split; and because old replicas stay alive, rollback is one atomic edit. We pay extra GPU during the overlap to buy zero-downtime, instantly-reversible deploys.
  • Durability lives in the weights, not the work. Model artifacts are immutable versioned blobs and the routing table is Raft-consistent; the request queue and replica inventory are transient and rebuildable, so a lost replica costs only retried in-flight requests, never data or a wrong-version routing decision.

One-line summary: a GPU-bound serving platform where a per-replica dynamic batch scheduler (size-or-wait, continuous batching for LLMs) converts spare latency budget into 30-50x throughput, load-aware routing and GPU-signal autoscaling with warm pools keep the fleet busy under skewed spiky traffic, and blue-green rollouts driven by a strongly-consistent routing table with shadow, canary, and one-edit rollback let model versions change live - trading a few milliseconds of deliberate batch-wait and some overlap GPU for cheap, high-throughput, always-up, instantly-reversible inference.