Multi-Tenant Real-Time ML Inference Platform

Medium · ML System Design · Machine Learning Engineer · Onsite

Prompt

Architect a shared online ML inference platform that internal teams use to host trained models and that user-facing services invoke synchronously inside live request paths. Your design should cover end-to-end model deployment, autoscaling across heterogeneous workloads, and operational plus quality monitoring.

Key scale and workload parameters are intentionally left open—state explicit assumptions up front:

  • Tenant and hardware diversity: How many teams and models share the platform, and how architectures span fast CPU-bound tabular models (such as gradient-boosted trees) through GPU-accelerated deep neural networks, including multi-model cascades or ensembles.
  • Traffic profile and tail latency: Caller latency budgets on synchronous RPCs, diurnal demand swings, sudden promotional traffic spikes, and long-tail endpoints that receive fewer than one call per second.
  • Inputs and release governance: Whether feature inputs arrive inline from callers, require low-latency online feature-store lookups, or combine both, plus target rollback times and human versus automated promotion gates.

Scope & Expectations

  • Immutable model packaging and progressive rollouts: Specify what artifacts and schemas constitute a deployable model version beyond raw weights, how releases progress safely from zero traffic to full production, and how bad rollouts revert within seconds.
  • Capacity-driven scaling and batching: Define per-pool autoscaling signals, GPU dynamic batching with bounded queueing latency, cold-start mitigation, and cost-effective hosting for rarely called models.
  • Fast feature assembly and fault isolation: Keep online feature lookups within tight millisecond sub-deadlines and degrade gracefully when upstream stores or peer replicas falter.
  • Multi-layer observability: Monitor infrastructure, tail latency, input feature health, and live prediction distributions so silent model degradation is caught long before delayed ground-truth labels arrive.

Step-by-step walkthrough

  1. Clarify requirements, problem framing, and assumptions

    Because the prompt leaves scale, hardware, and latency open, we spend the first few minutes stating concrete assumptions out loud so every later choice (batching windows, GPU headroom, canary gates, and logging sampling) is grounded in real numbers.

    Assumed platform context

    • Teams and model mix: 40 product teams running 300 deployed models. Roughly 90% (270 models) are lightweight CPU models—gradient-boosted decision trees (GBDTs like LightGBM/XGBoost), logistic regressions, or small neural nets taking tens of microseconds per row (artifacts of 5–100 MB). Roughly 10% (30 models) are deep neural networks (search rerankers, multimodal embeddings) needing GPUs and multi-gigabyte weight files.
    • Heavy-tailed, spiky traffic: 20 tier-1 models carry > 95% of total requests (search ranking, home feed recommendations, checkout fraud). Around 200 long-tail models receive < 1 request/s (internal tools, niche classifiers, regional experiments). Daily traffic swings 3× between night and peak, with 10× flash spikes inside 2 minutes when marketing campaigns or flash sales launch.
    • Synchronous latency budget: Applications call the platform synchronously on the user's live request path with a typical end-to-end p99 ≤ 50 ms (meaning 99% of calls finish within 50 ms). Platform routing and serialization may consume ≤ 5 ms; the remaining 45 ms splits between feature lookups and model execution.
    • Model inputs: Callers pass live context in the request (search query text, cart total) plus entity IDs (retailer_id, product_id); the platform fetches precomputed entity features from an online feature store (a low-latency key-value database).
    • Rollout safety and rollback speed: Removing a bad version from live traffic must take < 1 minute end-to-end—and < 10 seconds when the prior version is still warm in memory. Early rollout stages advance via automated gates; promoting tier-1 models to 100% requires sign-off from the owning team after experiment review.
    • Multi-model graphs: Endpoints can chain a small declarative DAG (directed acyclic graph, such as a cascade where a cheap CPU model scores 1,000 candidates and a GPU reranker re-scores the top 100, or an ensemble averaging two models).

    ML platform problem framing (predictions and delayed labels)

    Unlike designing a single recommender, an inference platform serves dozens of different tasks. Its core contract is the immutable prediction record: every call returns a unique prediction_id and model_version while logging the inputs and outputs asynchronously. Ground-truth labels belong to product teams and arrive late (5 seconds for a search click, 7 days for a wholesale order, 60 days for a fraud chargeback). By joining late outcomes back to prediction_id, the platform computes delayed online accuracy metrics (AUC, NDCG, calibration) automatically per model version.

  2. Back-of-the-envelope numbers

    Let's size four representative workloads, cold-start latency, logging bandwidth, and A/B test statistics.

    1. Compute sizing across 4 workloads
       A) Search Ranker (GBDT on CPU — high fan-out)
          3,000 req/s x 400 candidate items/req = 1,200,000 rows/s at peak
          1 CPU core @ ~10 us/row = 100,000 rows/s -> 4-vCPU replica saturates at 400,000 rows/s
          At 50% target utilization (200,000 rows/s per replica): 1.2M / 200K = 6 replicas
          Add +2 for 3-zone N+2 redundancy -> 8 CPU replicas (32 vCPUs total)
          Feature reads: 3,000 req/s x (1 retailer + 400 products) = ~1.20M entity key reads/s!
    
       B) Checkout Fraud Scorer (GBDT on CPU — 1 row/req, high availability)
          500 req/s x 1 row = 500 rows/s (< 0.01 CPU cores) -> 3 small replicas across 3 zones
    
       C) Neural Reranker (Transformer on GPU — bursty)
          100 rows/req; baseline 200 req/s (20,000 rows/s), spikes 10x to 2,000 req/s (200,000 rows/s)
          1 GPU executes a batch of 300 rows (3 requests) in 12 ms -> 25,000 rows/s max saturation
          At 60% target utilization (15,000 rows/s per GPU):
          - Baseline: ceil(20,000 / 15,000) = 2 GPUs (if 1 fails, survivor runs at 80% < 100%!)
          - 10x spike: ceil(200,000 / 15,000) = 14 GPUs
    
       D) Long Tail (~200 models at < 1 req/s)
          1 dedicated pod per model = 200+ idle pods -> pack into a shared multi-model pool instead!
    
    2. Cold-start timeline (why headroom and warm pools matter)
       Start container on warm node: ~5 s  |  Pull 2 GB weights (S3: ~10 s; node NVMe cache: ~2 s)
       GPU weight load + warmup batches: ~15 s  => ~22-30 s on warm node, vs. 2-5 min for a new cloud GPU VM!
    
    3. Prediction logging throughput (50,000 req/s, 2M rows/s platform-wide at peak)
       100% full feature vectors (2M rows/s x 100 floats x 4 B): 800 MB/s (~69 TB/day at peak rate!)
       100% compact request records (50,000 req/s x ~1 KB):       50 MB/s
       + 5% sampled full feature vectors:                         40 MB/s  => ~90 MB/s total to Kafka!
    
    4. A/B test sample size (detecting a 2% relative conversion drop: 5.0% -> 4.9%, delta = 0.001)
       Two-sided alpha = 0.05 (z = 1.96), 80% statistical power (z = 0.84):
       n_per_arm = 2 x (1.96 + 0.84)^2 x 0.05 x 0.95 / (0.001)^2
                 = 2 x 7.84 x 0.0475 / 0.000001 = ~745,000 independent units per arm (~1.49M total!)
    

    Notice what Equation 4 proves: confirming a subtle 2% conversion drop requires ~1.49 million independent sessions/units (or days to weeks even with CUPED—Controlled-experiment Using Pre-Experiment Data, which subtracts each user's pre-test baseline to shrink variance by 30–50%). Therefore, fast 30-minute rollout gates cannot wait on purchase conversion; they must watch errors, latency, feature defaults, output drift, and high-frequency proxy clicks!

  3. Data-plane and control-plane APIs

    We separate the ultra-fast data plane (called thousands of times per second by live apps) from the control plane (used by ML engineers and CI pipelines to register and roll out models).

    # Data plane (gRPC protobufs on hot path; HTTP/JSON mirror for internal tools)
    POST /v1/endpoints/{endpoint}:predict
      headers: x-request-id, x-caller-id (from mTLS cert), x-deadline-ms: 45
      body: {
        "experiment_unit": "r_509",                       # hashed for sticky canary / A/B routing
        "shared_entities": {"retailer_id": "r_509"},      # looked up once per request!
        "instances": [                                    # batch up to 1,000 candidate rows
          {"product_id": "p_1", "query_len": 3},
          {"product_id": "p_2", "query_len": 3}
        ]
      }
      response: {
        "prediction_id": "pred_3a7e12",
        "model_version": "feed-rank:v18",
        "predictions":   [0.091, 0.024],
        "degraded":      false     # true if feature store timed out (defaults used) or fallback ran
      }
    
    # Control plane (model lifecycle, progressive rollout, scaling)
    POST /v1/models/{model}/versions              body: {bundle_uri} -> starts offline validation
    GET  /v1/models/{model}/versions/{version}    -> status, golden-set diff, load-test capacity
    POST /v1/endpoints/{endpoint}/rollouts
         body: {
           "candidate_version": "v18",
           "shadow_duration": "60m",
           "canary_steps_pct": [1, 5, 25, 50],
           "step_hold": "30m",
           "auto_gates": {"max_error_delta_pp": 0.1, "max_p99_ms": 45, "max_output_psi": 0.20},
           "require_human_promote_at_50": true
         }
    POST /v1/endpoints/{endpoint}/rollouts/{id}:rollback   # instant <10s pointer revert
    

    Three API details pay huge dividends in production:

    • shared_entities + batched instances: Sending 1 retailer_id and 400 product_ids in a single RPC avoids 399 redundant retailer feature lookups and 399 network round trips.
    • Explicit x-deadline-ms propagation: Every hop subtracts elapsed milliseconds from the remaining budget; if a request expires in queue, the server drops it immediately rather than burning GPU cycles on a timed-out caller.
    • model_version + prediction_id in every response: Downstream checkout events log prediction_id, making experiment attribution and delayed label joins exact.
  4. Data model: immutable model bundles and versioned routing state

    What must an ML team register besides raw model weights? If a team uploads only model.pkl, serving inevitably breaks due to mismatched library versions, missing preprocessing, or differing null defaults. Instead, the deployable unit is an immutable, content-hashed model bundle:

    model: feed-rank
    version: v18                                       # immutable content hash of manifest + artifacts
    weights_uri: s3://ml-artifacts/feed-rank/v18/model.lgb     (sha256: 4d8a...)
    runtime_image: registry.internal/lgbm-server@sha256:ab12... # pinned image digest, NEVER :latest!
    signature:
      shared_inputs:
        - {name: ret_orders_30d, dtype: int32, source: feature_store,
           feature_ref: retailer_v4.orders_30d, default: 0, range: [0, 100000]}
      row_inputs:
        - {name: price_usd, dtype: float32, source: feature_store,
           feature_ref: product_v3.price_usd, default: 25.0, range: [0.01, 50000.0]}
        - {name: query_len, dtype: int32, source: request, range: [1, 64]}
      outputs:
        - {name: p_purchase, dtype: float32, range: [0.0, 1.0]}
    resources:
      cpu: 4
      memory: 8Gi
      gpu: 0
      max_batch_rows: 1024
      batch_wait_ms: 0                                 # 0 ms for CPU trees; e.g. 5 ms for GPU models
      max_queued_batches: 2                            # bounds worst-case queueing latency!
    measured_capacity:
      saturation_rows_per_s: 400000                    # measured automatically during Stage 1 load test
    slo: {p99_ms: 25}
    validation_assets:
      golden_set_uri: s3://ml-artifacts/feed-rank/v18/golden_1000.parquet    # inputs + training outputs
      training_histograms_uri: s3://.../baseline_histograms.json             # for live PSI drift checks
      offline_eval: {window: "2026-08-01..07", ndcg_10: 0.614, incumbent_ndcg_10: 0.608}
    owner: team-discovery-ml
    fallback: {strategy: previous_version}             # or static_score / stage1_only
    

    Control-plane state (PostgreSQL) and Prediction Log (Kafka -> Columnar Warehouse):

    Control Plane (PostgreSQL — low write rate, pushed to routers via watch stream):
      models      (model_name PK, owner_team, tier, oncall_channel)
      versions    (model_name, version, manifest_uri, validation_status, load_test_rows_s)
      endpoints   (endpoint_name PK, active_route_version BIGINT)
      routes      (endpoint_name, route_version BIGINT, rules_json, created_by, created_at)
                  -- e.g. [{ver: "v17", weight: 95, mode: "SERVE"},
                           {ver: "v18", weight:  5, mode: "SERVE"},
                           {ver: "v19", weight: 10, mode: "SHADOW"}]
      rollouts    (rollout_id PK, endpoint_name, candidate_ver, stage, started_at, status)
    
    Prediction Log (Kafka -> Iceberg/ClickHouse, partitioned by date + endpoint_name):
      (prediction_id, req_ts, endpoint_name, model_version, experiment_arm, entity_keys,
       predictions, latency_ms, degraded_flags, sampled_features_map, sampled_feature_ages)
    

    Because routes is append-only and endpoints.active_route_version is a single integer pointer, rolling back never rebuilds containers—it flips active_route_version from 108 back to 107!

  5. High-level architecture

                   Caller Microservices (Search, Feed, Checkout, Risk)
                                    |  gRPC predict(endpoint, instances, deadline)
                                    v
      +-------------------------------------------------------------------------------+
      | Stateless Prediction Router Fleet (deployed in every Availability Zone)       |
      |  1. Auth & per-caller rate limit    3. Parallel sharded feature MGET + cache  |
      |  2. Sticky route pick (routes push) 4. Deadline check & async shadow mirror   |
      +----------+-----------------------+-----------------------+--------------------+
                 |                       |                       |                 \
                 v                       v                       v                  \ async
      +--------------------+  +--------------------+  +-----------------------+  +----------------+
      | Online Feature     |  | Dedicated CPU Pool |  | Dedicated GPU Pool    |  | Kafka:         |
      | Store (Redis /     |  | (1 deployment per  |  | (Dynamic batching +   |  | prediction-log |
      | DynamoDB replicas) |  | hot GBDT/MLP ver;  |  | compiled TensorRT/    |  +-------+--------+
      +--------------------+  | scale on rows/s)   |  | ONNX; warm GPU pool)  |          |
                              +--------------------+  +-----------------------+          v
                              | Shared Multi-Model Pool (~200 <1 req/s models;|  Stream Metrics,
                              | on-demand load + LRU eviction in shared pods) |  PSI Drift Jobs &
                              +-----------------------------------------------+  Delayed Label Join
                                                     ^                                   |
                                                     | deploy pods, scale, push routes   v
      +-------------------------------------------------------------------------------+--+
      | Control Plane: Bundle Registry | Offline Validator & Load Tester |               |
      | Progressive Rollout Controller (Shadow -> Canary -> A/B -> Auto-Rollback)        |
      +----------------------------------------------------------------------------------+
    

    The Prediction Router keeps model servers clean and uniform: routers handle auth, sticky canary / A/B traffic splitting, feature-store batching, local caching, shadow mirroring, and non-blocking Kafka logging, while Model Servers focus purely on fast numerical inference in C++/Rust/CUDA runtimes (Triton, ONNX Runtime, LightGBM).

  6. Deep dive 1: Progressive rollout without an all-at-once switch

    No model jumps straight from registration to 100% live traffic. Every candidate passes through four progressive gates, each catching bugs the earlier stage could not see:

     [Register v18]
           |
           v
     1. OFFLINE GATE (0% live) -----> Schema check + 1,000-row Golden Set replay (|diff| < 1e-5)
           |                          + Slice metrics vs v17 + Saturation load test
           v
     2. SHADOW MODE (10% mirrored) -> Router returns v17 to user, copies request async to v18 (60m).
           |                          Catches crashes, p99 tail spikes, NaN outputs, huge PSI shifts!
           v
     3. CANARY (1% -> 5% -> 25% -> 50% live, sticky by hash(endpoint_salt + retailer_id))
           |                          Compares v18 vs LIVE v17 AT THE EXACT SAME TIMESTAMP:
           |                          - Error rate > v17 + 0.1 pp or p99 > SLO -> AUTO-ROLLBACK (<10s)
           |                          - Output PSI > 0.20 or click CTR drop    -> PAUSE & PAGE OWNER
           v
     4. POWERED A/B TEST (50% / 50%, 7-14 days for tier-1 models)
           |                          Accumulates ~745K units/arm (with CUPED variance reduction)
           v                          -> Owner reviews report & approves 100% promotion
     5. 100% LIVE + 24h WARM BAKE --> Keep v17 warm replicas running for 24h so rollback stays <10s!
    

    Three subtle details separate production-grade rollouts from fragile ones:

    • Golden-set parity check (|serving_pred - training_pred| < 1e-5): Replaying 1,000 saved training feature vectors through the actual serving container catches silent serialization bugs (wrong feature column order, library version mismatch, float truncation) before a single user request touches v18.
    • Same-time canary vs. control comparison: Traffic mix at 09:00 differs sharply from 21:00. Comparing v18 (1% canary) against v17 (99% control) over the exact same 5-minute window cancels out time-of-day and promotional swings.
    • Warm previous version for instant rollback: Control-plane route pushes reach all routers over persistent gRPC streams within ~2 seconds. Keeping v17's replicas warm for a 24-hour bake period after v18 hits 100% guarantees an emergency rollback finishes in < 10 seconds instead of stalling behind a 3-minute GPU cold start.
  7. Deep dive 2: Autoscaling on true capacity, dynamic batching, and cold starts

    Notice that CPU tree ensembles and GPU neural networks saturate completely differently:

    • Why raw "GPU utilization %" is a trap: Nvidia's GPU-Util metric reports the fraction of milliseconds in which at least one GPU kernel ran. A GPU running tiny 1-row batches back-to-back reports 99% GPU utilization even when 95% of its tensor cores sit idle—and conversely can handle 10× more rows/s simply by forming bigger batches!
    • One unified scaling signal (load vs. load-tested capacity): Because Stage 1 load-tested every bundle to find saturation_rows_per_s while meeting its latency SLO, the autoscaler uses the exact same formula for CPU and GPU pools:
    desired_replicas = ceil( live_rows_per_s / (saturation_rows_per_s x target_utilization) )
    
    Example (Workload C GPU spike to 200,000 rows/s, saturation = 25,000 rows/s, target = 0.60):
    desired_replicas = ceil( 200,000 / (25,000 x 0.60) ) = ceil( 13.33 ) = 14 GPU replicas
    

    We scale up aggressively (15-second evaluation window, zero cooldown) and down conservatively (10-minute stabilization window) so bursty traffic never triggers thrashing scale-down/scale-up loops.

    Dynamic batching with bounded queue depth on GPUs

    On GPU servers, a dynamic batcher groups incoming requests across callers until either max_batch_rows (300) fills or the oldest waiting request hits batch_wait_ms (5 ms). Critically, we cap max_queued_batches = 1 (at most 1 batch running on the GPU + 1 batch forming in RAM) so latency stays mathematically bounded during spikes:

    Worst-case GPU server time when request R arrives just as Batch 1 starts on GPU:
      |<-- wait up to 5 ms to fill Batch 2 -->|
      |<----- Batch 1 finishes on GPU (12 ms) ----->|<----- Batch 2 runs on GPU (12 ms) ----->|
      0 ms                                         12 ms                                     24-29 ms!
    
    Worst case = batch_wait_ms (5 ms) + 1 running batch (12 ms) + own batch (12 ms) = 29 ms (fits 45 ms!)
    

    Here is the core batch-formation loop enforcing both batch_wait_ms and max_batch_rows:

    import time
    from typing import List
    
    
    def collect_next_gpu_batch(
        request_queue,
        max_batch_rows: int = 300,
        batch_wait_ms: float = 5.0,
    ) -> List:
        """Group queued requests into one GPU batch without exceeding batch_wait_ms."""
        # 1. Block until the first non-expired request arrives
        first_req = request_queue.pop_blocking()
        batch = [first_req]
        total_rows = first_req.num_rows
    
        # 2. Deadline for closing this batch is batch_wait_ms from the oldest item's arrival
        flush_deadline = time.monotonic() + (batch_wait_ms / 1000.0)
    
        while total_rows < max_batch_rows:
            remaining_s = flush_deadline - time.monotonic()
            if remaining_s <= 0:
                break
    
            next_req = request_queue.peek_with_timeout(remaining_s)
            if next_req is None:
                break
    
            # Drop requests whose caller deadline already expired while waiting!
            if next_req.caller_deadline_monotonic <= time.monotonic():
                request_queue.pop_nonblocking()
                next_req.fail_deadline_exceeded()
                continue
    
            # Stop if adding next_req would overflow max_batch_rows (leave it for next batch)
            if total_rows + next_req.num_rows > max_batch_rows:
                break
    
            batch.append(request_queue.pop_nonblocking())
            total_rows += next_req.num_rows
    
        return batch
    

    Surviving cold starts: A newly started pod stays NotReady (receiving zero live traffic) until it verifies the weights SHA-256, passes the 1,000-row golden check, and executes warmup batches (forcing JIT/CUDA graph allocation before real users arrive). The 40–50% utilization headroom absorbs sudden surges for ~30 seconds while warm-node pods initialize, backed by a small shared warm GPU node pool (with base container images and pre-compiled TensorRT engines cached on local NVMe SSDs) so we rarely wait 4 minutes for cloud VM provisioning.

  8. Deep dive 3: Fast feature fetching and catching silent prediction degradation

    Keeping 401 feature lookups under 10 ms

    1. Deduplicated, sharded MGETs in parallel: For 1 retailer + 400 candidate products, the router groups keys by Redis/DynamoDB shard and fires one parallel multi-get per shard (~2–4 ms).
    2. Short-TTL router cache for batch features: Daily batch features (product_v3.avg_rating_90d) change once every 24 hours. A 60-second in-memory LRU cache (Least Recently Used cache) inside each router pod serves popular catalog items in nanoseconds and slashes feature-store read load by 60–80%. (Minute-level streaming features bypass this cache.)
    3. Strict fetch sub-deadline (10 ms) + training-matched defaults: If 1 slow feature shard misses the 10 ms sub-deadline, the router fills missing values with the exact default declared in the model bundle, sets degraded: true, increments feature_default_fill_total, and still runs the model on time.

    Six-layer monitoring stack—catching silent quality drops before labels arrive

    A model server can return HTTP 200 in 8 ms while emitting garbage because an upstream feature stream stalled and fed 100% default zeros. We monitor six distinct layers, routing infrastructure issues to platform on-call and data/prediction issues to the model owner:

    Layer          Key signals watched                                          Alert target
    1. Infra       OOM kills, GPU ECC errors, pod restarts, warm-pool headroom  Platform on-call
    2. Service     RPS, 5xx rate, p50/p99 latency per endpoint & version,       Platform on-call
                   queue drops, retry rate, router overhead (> 5 ms)
    3. Inputs      Per-feature default-fill %, null/range violations,           Model owner
                   feature staleness (now - feature_ts), feature PSI vs train
    4. Predictions Output mean/quantiles, PSI vs training & last week same hr,  Model owner
                   % constant/NaN scores, intra-query score spread (rankers)
    5. Outcomes    Fast proxy metrics (5s click CTR) + delayed ground-truth     Model owner
                   AUC / log-loss / calibration (reported WITH label maturity!)
    6. Business    Per-version conversion, GMV, fraud loss from A/B joins       Owner + Product
    

    Notice the four early-warning signals that fire days before 7-day purchase or 60-day fraud labels mature:

    • Default-fill rate spike (e.g., price_usd jumping from 0.1% default to 45% default—instantly pinpoints broken feature plumbing).
    • Feature freshness regression (now - served_feature_ts crossing the feature's SLA).
    • Input and prediction PSI (Population Stability Index, measuring histogram divergence against the bundle's training_histograms.json; < 0.10 normal, 0.10–0.25 warn, > 0.25 alert).
    • Fast proxy labels & calibration tracking: Search clicks arrive within seconds; and once delayed labels mature, we track calibration (mean(predicted_prob) / observed_event_rate per slice) strictly over cohorts whose label window has fully closed (never mixing yesterday's immature fraud window with 60-day-old mature labels).
  9. Scaling, long-tail serving, failure handling, and trade-off summary

    Serving 200 long-tail models cheaply + multi-tenant isolation

    • Multi-model server pool for the < 1 req/s tail: Instead of burning 200 always-on pods, 6–10 shared CPU pods host lightweight models on demand. Routers use consistent hashing by model_name so requests for niche-model-7 hit the 2 pods holding it in RAM; when pod RAM fills, the least recently used model unloads cleanly (reloading a 20 MB LightGBM file from local NVMe cache takes < 150 ms on the next rare call).
    • Blast-radius isolation and retry budgets: Tier-1 endpoints run on dedicated node pools with per-caller token-bucket rate limits and per-endpoint concurrency caps in the router, so one runaway caller cannot starve checkout or search. Routers retry a failed/slow replica at most once on a peer replica only if remaining_deadline_ms > p95_model_ms, capped by a 10% retry budget so overload never spirals into a retry storm.

    Failure handling across the platform

    Failure scenario Detection Automated platform response
    Single replica crashes or OOMs Health probe / gRPC reset Router retries peer replica within budget; orchestrator replaces pod
    Entire Availability Zone fails Zone health check Surviving 2 zones rise from ~50% to ~75% utilization (staying inside SLO!) while autoscaler adds pods
    Sudden 20× unscheduled overload Queue depth + deadline drops Shed lowest-priority requests early; cascades skip expensive GPU stage 2 and return CPU stage 1 (degraded=true)
    Online feature store partial outage 10 ms fetch timeout Fill bundle's training defaults, mark degraded=true, page if default share > threshold
    Control plane or Kafka log outage Internal health alerts Static stability: routers keep serving last cached routes table in memory; full Kafka buffers drop logs rather than blocking live predictions!

    Summary of core trade-offs

    • Strict immutable model bundles vs. raw user containers: Requires upfront schema, golden-set, and load-test packaging from ML teams, buying automated skew gates, uniform autoscaling, and zero-code drift monitoring across 300 models.
    • Progressive rollout + 24h warm incumbent vs. instant cutover: Temporarily doubles replica cost during the 24-hour bake window and takes days for powered A/B tests, buying < 10-second rollback and protection against silent business regressions.
    • 50–60% utilization headroom + dynamic batching vs. running hot at 85%: Pays for 40% spare compute and up to 5 ms batching delay, buying 3–5× higher GPU throughput and survival during 30-second cold starts.
    • Default fallback on feature timeouts vs. failing hard: Keeps availability at 99.95% at the cost of slightly degraded predictions—made safe only because degraded and default-fill rates are first-class alerts.

Intuition & how it works

Think of a real-time model inference platform like an international airport's air-traffic control and gate system for 300 different aircraft (trained ML models). Product teams do not just hand over a bare engine (raw model weights); they hand over a sealed, safety-inspected aircraft manifest (immutable model bundle containing weights, pinned runtime container, input/output schemas, training-matched null defaults, a 1,000-row golden test set, and load-tested passenger capacity). When live shopper requests arrive with a strict 50 ms clock, a central prediction router fetches needed passenger luggage in one parallel batch (online feature store lookup), directs jumbo jets onto wide multi-passenger shuttle buses (GPU dynamic batching) while keeping frequent commuter planes in dedicated fast lanes (CPU pools) and parking rare private planes in a shared hangar (multi-model long-tail pool), and keeps yesterday's proven plane fueled at the gate so traffic can switch back in under 10 seconds if turbulence hits.

A naive setup—wrapping a model.pkl inside a basic web server, switching 100% of traffic at once, scaling GPUs on raw "GPU % busy", and paging only on HTTP 500 errors—fails constantly in production. Switching traffic all at once exposes every shopper to subtle preprocessing bugs or conversion drops that offline holdout metrics cannot see (and confirming a 2% conversion drop statistically takes days, not minutes). Scaling GPUs on raw % utilization misreads tiny 1-row batches as "100% full," while monitoring only HTTP status codes stays completely blind when a broken upstream pipeline feeds all-zero default features and the model happily returns fast, confident, wrong predictions.

Concrete 4-step walkthrough (deploying and serving feed-rank:v18)

  1. Offline bundle gate (0% traffic): An ML engineer registers feed-rank:v18. The platform automatically verifies that every declared feature exists online, replays 1,000 saved training rows (golden set) to confirm serving scores match training scores within 1e-5, and load-tests one 4-vCPU replica to measure 400,000 rows/s saturation capacity.
  2. Shadow -> Canary -> Rollback readiness: Router pods mirror 10% of live feed requests asynchronously to v18 (shadow mode, zero user impact) to verify latency and output distribution, then shift 1% -> 5% -> 25% -> 50% of retailers (hashed stickily by retailer_id), comparing v18 against live v17 at the exact same minute on errors, latency, default-fill rate, and click-through rate before a powered A/B test approves 100% rollout (keeping v17 warm for 24 hours).
  3. Serving one 400-item ranking request (p99 <= 50 ms): Discovery calls predict with x-deadline-ms: 45, retailer_id="r_509", and 400 product_ids. The router checks its 60-second local LRU cache (Least Recently Used memory cache) for daily product features, fetches uncached keys in parallel sharded MGETs within 10 ms, sends the assembled 400-row matrix to v18 (~4 ms CPU inference), returns scores + prediction_id, and logs a compact record asynchronously to Kafka.
  4. Catching a silent bug before labels arrive: Two days later, an upstream stream lags and product_views_1h starts missing keys, falling back to default = 0. HTTP error rate stays 0.00%, but the platform's Layer-3 monitor catches default_fill_rate jumping from 0.2% to 38% and PSI (Population Stability Index, a histogram shift metric) crossing 0.25, paging team-discovery-ml immediately—days before 7-day order labels would have noticed.

Key trade-offs

  • Opinionated model bundle vs. "bring any Docker container": Requiring teams to declare feature schemas, defaults, a 1,000-row golden set, and baseline histograms adds packaging work upfront, in exchange for letting the platform automate feature fetching, training-serving parity checks, capacity-based autoscaling, and feature/output drift alerts uniformly across 300 models.
  • Progressive shadow -> canary -> A/B rollout vs. instant deployment: Full rollouts take hours (for low-risk retrains with automated gates) to 1–2 weeks (for new model architectures needing ~745,000 units/arm to detect a 2% relative conversion shift), trading raw deployment speed to catch runtime crashes in shadow, severe regressions at 1% canary, and subtle revenue drops in A/B tests.
  • Keeping the previous version warm for 24 hours vs. immediate teardown: Retaining warm replicas of v17 after v18 hits 100% doubles compute cost for one day on changed endpoints, buying < 10-second pointer rollback instead of risking a 30-second to 4-minute cold-start outage during an incident.
  • 50–60% utilization target + dynamic batching vs. running at 85%+ utilization: Leaving 40–50% spare capacity and waiting up to batch_wait_ms (5 ms) on GPUs costs idle compute and a few milliseconds of tail latency, but boosts GPU throughput 3–5× under bursts and keeps p99 inside budget during the ~30 seconds new pods need to load weights and run warmup batches.
  • Shared multi-model pool vs. one pod per model for the long tail: Packing ~200 < 1 req/s models into a small shared pool with on-demand loading and LRU eviction saves hundreds of idle containers, trading slight noisy-neighbor risk and a sub-second reload delay on rare cache misses.
  • Substituting training defaults on feature timeouts vs. failing the call: Returning predictions using declared training defaults (degraded: true) preserves 99.95% endpoint uptime when a feature shard hiccups, trading a small temporary accuracy dip that must be guarded by strict alerts on default_fill_rate.
  • 100% output logging + 5% feature-vector sampling vs. 100% full logging: Sampling full feature vectors at 5% cuts Kafka and warehouse ingestion from ~850 MB/s to ~90 MB/s while still preserving 100% of prediction_ids for experiment/label joins (allowing opt-in 100% feature logging only for models that retrain directly on served logs).

Common mistakes

  • Treating raw model weights as the deployable artifact: Deploying model.pt without pinning the container digest, preprocessing code, feature versions, and null defaults causes silent training-serving skew (serving computing different inputs than training saw).
  • Cutting 100% of live traffic over at once or comparing canary against last week's baseline: All-at-once switches maximize blast radius, and comparing today's canary against yesterday's metrics confuses normal time-of-day traffic swings with model regressions.
  • Expecting purchase conversion to validate a 15-minute canary: Detecting a 2% relative drop on a 5% conversion rate requires ~745,000 independent units per arm; minute-scale canary gates must watch error rates, latency, default-fill rates, score PSI, and fast click proxies.
  • Autoscaling GPUs on GPU-Util % or allowing unbounded server queues: Tiny 1-row GPU kernels report ~100% busy at 1/10th true row capacity, and unbounded batch queues let waiting batches stack up past the caller's 50 ms deadline; scale on live_rows_per_s / tested_capacity and cap max_queued_batches.
  • Marking new pods Ready before weights load and warmup batches finish: Routing live traffic to an un-warmed pod triggers JIT/CUDA compilation stalls that blow p99 latency into seconds.
  • Issuing one network call per candidate row to the feature store: Fetching 400 product features sequentially instead of parallel sharded MGETs + a short router cache guarantees latency timeouts.
  • Monitoring only CPU, memory, and HTTP 200s—or comparing immature delayed labels: Servers look green when broken features feed defaults, and comparing yesterday's fraud predictions (where 60-day chargebacks have not arrived yet) against last quarter's mature labels creates fake accuracy drops.
  • Allowing unbounded retries across routers and callers: Retrying overloaded model pods without checking remaining deadline or enforcing a 10% retry budget amplifies a brief slowdown into a cascading outage.

Follow-up questions

  • Suppose a candidate model beats the incumbent on offline holdout metrics, yet conversion falls once deployed live. Which rollout safeguards catch this discrepancy, and how fast can traffic revert to the prior version? Offline holdout sets cannot observe live training-serving feature skew, latency-induced timeouts, or closed-loop user behavior (such as ranking clickbait higher that shoppers later abandon at checkout). The platform catches sharp issues in the canary stages by comparing candidate and control simultaneously on default-fill rates, score PSI, and fast proxy signals (click-through and add-to-cart rates), and catches subtler conversion drops by holding tier-1 rollouts at a 50/50 A/B test (using CUPED pre-experiment variance reduction) until sufficient statistical power accumulates before human sign-off. If a regression slips past to 100%, flipping endpoints.active_route_version back to the prior route pushes over open gRPC streams to all routers and completes rollback in < 10 seconds during the 24-hour warm bake window (or ~25–45 seconds if old pods already scaled down and must cold-start from node cache). Post-incident, engineers join the 5% logged feature vectors against offline recomputation to isolate skew and add the missed leading metric as an automated gate.
  • A deep-learning reranker requires GPU accelerators and experiences sudden 10x traffic surges. How do you satisfy strict tail-latency SLOs without overprovisioning idle GPUs around the clock? Run a small baseline (e.g., 2 GPUs at ~60% load) using dynamic batching (max_batch_rows = 300, batch_wait_ms = 5 ms, max_queued_batches = 1) so sudden request bursts naturally pack larger batches and raise per-GPU throughput up to 25,000 rows/s while bounding worst-case GPU latency to 5 + 12 + 12 = 29 ms, scaling up immediately on rows_per_s / tested_capacity and scaling down slowly over 10 minutes. Because cloud providers take 2–5 minutes to boot raw GPU VMs, bridge the 2-minute spike gap three ways: maintain a small shared warm GPU node pool across all 30 GPU models (cutting pod readiness to ~25 s via NVMe-cached weights and pre-compiled FP16/INT8 TensorRT engines, which also double per-GPU throughput), trigger scheduled pre-scaling before planned marketing blasts, and overflow excess burst requests above max_queued_batches to a cheap distilled CPU model or cascade stage-1 score marked degraded = true. During off-peak hours, low-QPS GPU models can share physical GPUs via hardware partitioning (such as NVIDIA MIG).
  • Platform tenants register hundreds of low-volume models that each receive fewer than one call per second. How do you keep them available on demand without dedicating an always-on container to every model? Route the ~200 < 1 req/s models to a shared multi-model server pool of 6–10 CPU pods where each process holds dozens of small models in memory simultaneously, loading artifacts on first request from a fast node-local NVMe cache and evicting the least recently used (LRU) model when RAM fills. The prediction router uses consistent hashing (mapping each model_name deterministically to 2 preferred home pods) so warm hits require zero loading and memory is never duplicated across all 10 pods. Because a 20 MB LightGBM or ONNX model loads in ~50–150 ms from local disk, occasional cold misses easily fit relaxed internal SLOs; models needing strict sub-30 ms latency on every single call simply pin min_loaded_copies = 2 in memory inside the shared pool for megabytes instead of a dedicated pod, while models untouched for weeks scale cleanly to zero RAM.
  • Profiling reveals that fetching online features consumes most of the end-to-end prediction latency budget. Which architectural optimizations reduce feature retrieval overhead? Attack feature latency in four layers ordered by impact: (1) Deduplicate, batch, and parallelize—fetch retailer_id once per request (not 400 times) and group all 400 product_ids into parallel per-shard MGET pipelines; (2) Cache slowly changing features inside the router—a 60-second local RAM LRU cache for daily batch product features absorbs 60–80% of reads on popular items in nanoseconds; (3) Enforce a strict sub-deadline (e.g., 10 ms) with training-matched defaults—cut off straggling tail shards rather than letting one slow Redis node stall the entire 50 ms prediction, marking degraded = true and monitoring default rates; and (4) Optimize data layout and locality—co-locate feature-store read replicas in every availability zone, pack a model's features per entity into a single compact binary blob (1 key read instead of 20 column reads), and let callers pass fresh request-local context directly in instances to skip round-tripping values they already hold in memory.

Follow-up questions

Similar questions

More Faire interview questions

All 10 Faire questions →