Interview Prep · ML System Design

The ML System Design Field Guide

A working-knowledge reference for the "design a recommendation system / fraud pipeline / feature store / real-time ranking system at scale" interview — the framework, the vocabulary that separates ML systems from general backend design, four fully worked examples, and the questions you're actually likely to be asked.

16 sections · 24 interview Q&A · updated 2026
Section 01

Overview & Mental Model

What this interview is actually testing, and why 15 years of shipping models doesn't automatically transfer.

ML system design is the interview format that asks you to design something like "Instagram's Explore feed," "a fraud-detection pipeline for a payments company," or "a feature store for a mid-size ML org" — in 35-45 minutes, on a whiteboard, with an interviewer who will interrupt you. It's distinct from two adjacent formats you may already be strong in: ML coding (implement k-means, backprop a small net) and general system design (design a URL shortener, a rate limiter). ML system design borrows the structure of the latter but the hard parts are ML-specific: what's the label, where does it come from, how stale can a feature be, and what happens when the world (or the fraudsters) drift out from under your model.

What interviewers are grading

  • Structure. Do you have a repeatable process, or are you free-associating architecture components?
  • Judgment under ambiguity. The prompt is deliberately underspecified — clarifying questions and stated assumptions matter more than any single "correct" answer.
  • Production instincts. Can you talk about staleness, retraining, rollback and monitoring, not just model accuracy?
  • Communication. Can you narrate trade-offs out loud as you go, not just arrive at an answer.

Why your background is an asset here

Fifteen years of shipping models means you already have real opinions on retraining cadence, feature staleness and rollback pain — most candidates are reciting a blog post, you're describing an incident. The gap to close is usually the reverse: staying at the right altitude (architecture and trade-offs) instead of diving into model internals, and being fluent in the specific vocabulary — feature stores, shadow deployment, training/serving skew — that this interview format expects you to use precisely.

Why this matters for interviews

Senior/staff-level ML system design interviews weight trade-off reasoning and failure-mode awareness far more than junior ones do. "I'd use a two-tower model for candidate generation" is a mid-level answer. "I'd use a two-tower model for candidate generation because it lets me pre-compute item embeddings offline and only run a cheap dot-product at serving time — the cost is that the interaction between user and item features is limited to what the dot product can express, which is why I'd follow it with a heavier ranking stage" is a senior answer.

Section 02

The Interview Framework

A six-step structure that scales from a 35-minute phone screen to a 60-minute onsite. Say the step names out loud — it costs nothing and signals structure immediately.

StepTime budgetWhat you're doing
1. Clarify & scope~10%Pin down the business objective, the ML task it maps to, scale, latency constraints, and what's explicitly out of scope.
2. Back-of-envelope estimation~10%QPS, data volume, storage, and a latency budget you'll defend later. Cheap to do, and it silently sets the architecture's scale.
3. High-level architecture~25%Data collection & labeling → feature pipeline → training → serving → feedback loop. Draw it before you defend any one box.
4. Deep dive (1-2 components)~35%The interviewer usually steers this. Go deep on the model/features for one box, or the infra for one box — not both shallowly.
5. Scaling & failure modes~10%What breaks at 10x traffic? What happens when the feature store is down, when labels are delayed, when the model degrades silently?
6. Trade-offs & wrap-up~10%Name what you'd do differently with more time/budget, and the trade-offs you made explicitly rather than by omission.

Step 1, in more detail: the questions worth asking

Business & ML task

  • What's the business metric this optimizes (engagement, GMV, fraud loss avoided)?
  • Is this really one ML task, or several (retrieval + ranking, detection + triage)?
  • Binary decision, ranked list, or a score consumed downstream?

Scale & constraints

  • Roughly how many users/items/events, and requests per second at peak?
  • What's the latency budget — p50 and p99 — for a response?
  • Real-time inference, or is batch/offline scoring acceptable?
  • Any regulatory/fairness/explainability constraints (common in fraud, credit, hiring)?
Interview trap

Don't skip straight to "I'd use a transformer." Interviewers deliberately underspecify the prompt to see whether you ask before designing. Spending 90 seconds clarifying scope, then stating your assumptions explicitly ("I'll assume 50M DAU and a 200ms p99 budget unless told otherwise") is worth more than guessing right by luck.

A one-line summary you can reuse

"I'll clarify the objective and scale, size the system with rough math, sketch the offline-training / online-serving split end to end, then go deep wherever you'd like — model, features, or infra — and close with how it scales, fails, and what I'd trade off."

Section 03

How ML Systems Differ From Backend Systems

A URL shortener has one hard problem: scale. An ML system has that problem plus a second system that decays the moment you stop watching it. This is the vocabulary that signals you know the difference.

Training/serving skew

Concept. The single most-tested failure mode: a feature computed one way offline (batch SQL, pandas) and a subtly different way online (a live service call) produces different values for the "same" feature — the model silently degrades because production features don't match what it was trained on. The fix is a shared feature-computation path, which is the entire reason feature stores exist.

Online vs. offline features

Concept. Offline features are computed in batch over historical data for training (cheap, can look arbitrarily far back). Online features are computed or looked up at request time, under a hard latency budget (must be a key-value read, not a Spark job). The two must agree in value — that's point-in-time correctness, covered in Section 6.

Data & label latency

Concept. A backend system's "data" is available the instant it's written. An ML system's label often isn't: did the user actually like the recommendation (minutes), did the loan default (months), was the transaction actually fraud (days, pending a chargeback). This delay bounds how fast you can detect model decay and how fresh your training data can be.

Model staleness & retraining cadence

Concept. A backend service doesn't get worse just by sitting still; a model does, as the world drifts from its training distribution. Retraining cadence (hourly, daily, weekly) is a deliberate trade-off between staleness risk, compute cost, and pipeline complexity — not a default you inherit from a tutorial.

Non-deterministic quality, not just correctness

Concept. A backend bug is usually binary — it works or it 500s. A model can be "up" (200 OK, low latency) while its predictions quietly get worse. This is why ML monitoring needs a second axis beyond system health: prediction-quality health (Section 12).

Safe rollout is a spectrum, not a flag

Concept. A backend feature flag is usually on/off. ML rollouts graduate through shadow deployment (score in parallel, log only, serve nothing), canary (serve a small traffic slice), and A/B test (serve a controlled slice long enough to measure a business metric, not just latency) — because the thing you're validating is prediction quality, which you can't unit-test.

Rollout stages, precisely

StageTraffic servedWhat it validatesTypical duration
Offline evaluationNone — historical/held-out dataModel quality vs. the current champion, on metrics you trustHours
Shadow deploymentNone — scores computed but discarded/loggedLatency, infra correctness, prediction distribution vs. production, with zero user riskDays
Canary release1–5% of trafficReal-world serving behavior at small blast radius before wider exposureHours–days
A/B testA meaningful, randomized slice (often 50/50 against control)The actual business metric moves in the intended direction, with statistical power1–4 weeks
Full rollout100%— old model kept as instant rollback targetOngoing
Why this matters for interviews

When an interviewer asks "how would you deploy this safely," the strongest answer names the specific stages above in order and says what each one is for — not just "I'd A/B test it." Mentioning that shadow mode catches infra bugs for free (no statistical test needed, you're just diffing distributions) is a senior-level detail most candidates miss.

Section 04

Estimation & Capacity Planning

Rough numbers, defended with simple arithmetic, done in under two minutes. The exact figures matter far less than showing you know which figures matter.

The four numbers you almost always need

QPS (queries per second)

Formula. DAU × requests/user/day ÷ 86,400, then multiply by a peak factor (2–5×) since traffic isn't uniform across the day. 100M DAU × 20 feed refreshes/day ÷ 86,400 ≈ 23K QPS average, ≈ 70–100K QPS at peak.

Storage

Formula. events/day × bytes/event × retention days. 500M events/day × 500 bytes × 400 days retention ≈ 100 TB raw — before compression, which typically buys back 3–10× on columnar formats.

Latency budget

Approach. Start from the end-to-end SLA (e.g. 200ms p99) and subtract network/gateway overhead, feature lookups, and model inference, leaving a remainder for anything else in the path. Every hop you add (a second model, a retrieval call) has to fit inside what's left.

Training data volume & refresh

Approach. How many labeled examples accumulate per retraining window, and is that enough given class imbalance (fraud is often <1% positive)? This number tells you whether daily retraining is even statistically meaningful, or whether you need a longer window.

A worked example: feed ranking latency budget

StageBudgetNote
Client → edge / API gateway~15msNetwork + auth + routing
Candidate generation (retrieval)~40msANN lookup over millions of items, narrowed to hundreds
Feature fetch (online store)~15msParallel key-value reads, batched per candidate
Ranking model inference~60msScoring hundreds of candidates, batched on GPU/CPU
Business rules / re-ranking / diversity~10msDedup, guardrails, promoted content injection
Response serialization & return trip~10ms—
Total~150msLeaves headroom under a 200ms p99 SLA for tail variance
Interview trap

Don't let estimation become a rabbit hole. State assumptions, do the arithmetic on the whiteboard in under two minutes, round aggressively (10M, not 9.7M), and move on. The interviewer is checking that you instinctively reach for math before designing, not grading you on precision.

Section 05

Reference Architecture

The shape almost every ML system converges to: a fast online path for serving, and a slower offline path that keeps it trained and fed. Nearly every worked example later in this guide is a specialization of this diagram.

Fig. 1 — The online path (top) must clear a strict latency budget on every request; the offline path (bottom) trades latency for throughput and correctness, and the two are bridged by materialization (feature pipeline → online store) and deployment (model registry → model serving).

Reading the diagram in an interview

Draw a version of this first, even in a worked example that's "just" about one component — it gives the interviewer a map of where your deep dive sits, and it signals immediately that you know the online/offline split is the organizing idea of ML systems, not an afterthought. Narrate it as: "requests come in here, get scored using features that were pre-computed over here, and the model itself was produced by this separate pipeline that never touches the request path directly."

What's usually correct to omit

A single system rarely needs every box drawn with equal weight. If the interviewer's focus is the ranking model, the feature-pipeline internals can be one box labeled "assume this exists." Depth where it's asked for, a placeholder everywhere else.

Where the deep dive usually goes

In practice, interviewers steer toward one of: the ranking/scoring model itself, the feature store and its consistency guarantees, or the retraining/monitoring loop. Have a two-minute answer ready for each before you walk in.

Section 06

Feature Stores & Pipelines

The component that exists specifically to prevent training/serving skew. Expect at least one question that assumes you know what one actually does.

A feature store is a system that computes, stores, and serves features for both training and inference from a single definition, so the value of "user's 7-day click rate" is guaranteed to mean the same thing whether it's read by a training job over historical data or by a live request at 2am. It has two storage halves that mirror the offline/online split from Section 5: an offline store (large, cheap, batch-queryable — for training) and an online store (small, fast, key-value — for serving), fed by the same feature-computation pipeline.

Point-in-time correctness

The subtlest and most-tested idea in this section: when you build a training set from historical logs, a feature value for "was this user shown a promo in the last 24h" must reflect what was true at the time of that historical event — not what's true today. Naively joining "current" feature values onto historical labels leaks future information into training (label leakage) and produces a model that looks great offline and fails in production. Feature stores solve this with point-in-time (as-of) joins: for every training row, pull the feature value as it stood at that row's timestamp.

Interview trap

If you're asked "how would you build the training set for this ranking model," and your answer doesn't mention point-in-time correctness, that's the single most common senior-level gap. Say it explicitly: "I'd do an as-of join against the feature store so I'm not leaking future feature values into historical training rows."

The 2026 feature-store landscape

The space has consolidated around a handful of clear categories rather than one obvious winner — know the shape of the market, not just one product.

Feast

Open source, self-hosted. The default "generic" answer in an interview: a Python-defined feature registry over pluggable offline (BigQuery, Snowflake, S3) and online (Redis, DynamoDB) backends. No managed compute of its own — you still own the pipelines that populate it.

Tecton

Commercial, managed. Built by the team behind Uber's Michelangelo platform; handles feature engineering, pipelines, and serving end-to-end rather than just the store layer, with declarative feature transformations and built-in streaming.

Databricks Feature Store

Commercial, managed. Tightly integrated with the Lakehouse (Delta Lake + Spark) — the natural default if training already runs on Databricks, since feature lineage ties directly to Delta tables.

SageMaker / Vertex AI Feature Store

Commercial, managed, cloud-native. AWS and GCP's respective offerings — S3/BigQuery-backed offline stores with managed online serving and streaming ingestion (Kinesis / Pub-Sub). Strong default if you're already committed to that cloud.

Hopsworks

Open source + commercial. Positions itself as a full feature-and-training platform rather than a thin store, with a strong emphasis on Python-native feature pipelines and its own managed offering.

"Build your own"

DIY. Common at smaller shops: an offline warehouse table plus a Redis cache populated by a cron/streaming job, with no unifying framework. Perfectly valid to propose in an interview — just be explicit about what you're giving up (shared definitions, drift monitoring, lineage) versus a purpose-built store.

Batch vs. streaming feature computation

Batch features

Freshness: hours. Computed on a schedule (nightly Spark/Airflow job) — "total purchases in the last 30 days," "average order value." Cheap, simple, fine for anything that doesn't change fast.

Streaming features

Freshness: seconds. Computed continuously off an event stream (Flink/Kafka Streams) — "transactions in the last 5 minutes," "clicks in this session." Necessary wherever staleness of minutes would defeat the purpose (fraud, real-time personalization).

feature_repo/transaction_features.pyPython · Feast-style
from feast import FeatureView, Field, FileSource
from feast.types import Float32, Int64

# One definition, read identically by training (offline) and serving (online)
txn_velocity_source = FileSource(
    path="s3://features/txn_velocity/",
    timestamp_field="event_timestamp",
)

txn_velocity_fv = FeatureView(
    name="txn_velocity",
    entities=["card_id"],
    ttl=timedelta(hours=6),
    schema=[
        Field(name="txn_count_5min", dtype=Int64),
        Field(name="txn_amount_sum_1hr", dtype=Float32),
    ],
    source=txn_velocity_source,
)
Why this matters for interviews

A strong answer to "would this feature be batch or streaming" ties the choice back to the label's own latency: a fraud feature needs streaming because fraud happens in seconds; a "user's favorite genre" feature is fine as a nightly batch job because taste doesn't shift minute to minute. Don't default to streaming everywhere — it's the more expensive, more operationally fragile choice, and naming that trade-off explicitly is what separates "knows the buzzwords" from "has run one of these."

Section 07

Serving & Deployment Patterns

How a trained model actually turns into an endpoint — the patterns, the current serving frameworks, and the rollout mechanics from Section 3 in more depth.

Three serving patterns

Online / real-time

Pattern. A request triggers inference synchronously, under a strict latency budget (tens to low-hundreds of ms). Required whenever the prediction gates a user-facing response — fraud approval, a ranked feed, a chat reply.

Batch / offline

Pattern. Predictions are computed on a schedule for a large set of entities at once and written to a store for later lookup — e.g. nightly churn scores for every user. Cheapest per-prediction, but predictions are only as fresh as the last batch run.

Streaming / near-real-time

Pattern. Inference triggered by each event on a stream, with results available within seconds rather than synchronously in the request path — e.g. scoring a transaction the instant it lands in Kafka, ahead of a downstream decision step.

The 2026 serving-framework landscape

What "model serving infrastructure" means has shifted: for classical ML it's still fairly stable, but LLM/GenAI serving has its own fast-moving stack worth naming correctly.

FrameworkBest forNotable trait
vLLMLLM inference, general production defaultPagedAttention for KV-cache efficiency + continuous batching; broad hardware support (NVIDIA/AMD/TPU)
SGLangMulti-turn / agentic LLM workloadsRadixAttention gives very high KV-cache reuse across shared prefixes — strong for chat/agent traffic patterns
NVIDIA TritonMulti-model, multi-framework serving & ensemblesGeneral-purpose inference server (any framework via backends), heavier setup than a single-model LLM server needs
KServeKubernetes-native model serving at the platform levelStandardizes serving behind a common K8s CRD — autoscaling (incl. scale-to-zero), canary rollout support built in
TorchServe / cloud-native (SageMaker, Vertex endpoints)Classical ML & simpler deep modelsStraightforward single-model REST/gRPC serving; cloud-managed variants trade flexibility for zero ops
Text Generation Inference (TGI)Legacy Hugging Face deploymentsEntered maintenance mode in late 2025 — Hugging Face itself now points new projects at vLLM or SGLang
Interview trap

If a prompt involves an LLM component, naming continuous batching and KV-cache management (what vLLM/SGLang are actually solving) is a strong signal you understand LLM-serving economics, not just that you can call an API. Generic "I'd deploy it behind a REST endpoint" answers under-differentiate for a senior GenAI-leaning role.

Safe rollout, revisited: canary + shadow together

In practice these aren't either/or: shadow mode runs first to validate infra correctness and latency at zero risk, then a canary exposes a small live slice to catch anything shadow mode couldn't (real user behavior, feedback loops), then an A/B test measures the actual business metric before full rollout. Champion/challenger is the standing version of this: the current production model (champion) keeps serving while a challenger is evaluated against it on live or shadow traffic before any promotion decision.

rollout sketchpseudocode
# Simplified rollout state machine a model version moves through
stages = [
    "offline_eval",   # beats champion on held-out metrics
    "shadow",        # scores live traffic, predictions discarded/logged
    "canary_5pct",   # serves a small live slice
    "ab_test",       # randomized slice, measured against business metric
    "full_rollout",  # 100% traffic, old model kept warm for rollback
]

def promote(model_version, stage_results):
    if stage_results.regressed:
        return "rollback"   # instant — route back to champion
    return "advance"
Section 08

Worked Example: Recommendation System

"Design Netflix/YouTube/Spotify's home-page recommendations." The classic two-stage funnel — and why nobody scores every item against every user.

1. Clarify & scope

Assume: 100M+ items, 100M+ users, personalized ranked list of ~20 items per home-page load, p99 latency budget ~200ms, implicit feedback (clicks/watches) is the primary signal.

2. Why a two-stage funnel

Scoring every item for every user with a rich model is computationally impossible at this scale (100M items × a model with meaningful per-user/item interaction terms, per request). The standard solution is a funnel: a cheap, high-recall candidate generation stage narrows millions of items to hundreds, then a more expensive, high-precision ranking stage scores just those hundreds with a much richer model.

Fig. 2 — Candidate generation trades precision for speed at massive scale (millions → hundreds); ranking trades speed for precision on a small, already-relevant set (hundreds → twenty).

3. Deep dive: the two-tower retrieval model

A two-tower model encodes users and items into the same embedding space with two separate neural networks (towers) trained so that a user's embedding is close (high dot product / cosine similarity) to embeddings of items they engaged with. The critical serving-time property: item embeddings can be pre-computed offline and indexed once in an approximate-nearest-neighbor (ANN) index; at request time you only compute the user embedding once and do a fast ANN lookup — you never re-run a full neural network per item at serving time.

What the two-tower design buys you

Sub-linear retrieval over hundreds of millions of items via ANN (HNSW, IVF), and item embeddings that can be refreshed on a batch cadence independent of the request path.

What it costs you

User–item interaction is limited to a single dot product — no rich cross-features (e.g. "this exact item, watched at this exact time of day"). That expressiveness gap is exactly what the downstream ranking stage exists to close.

4. Scaling & failure modes

  • Cold start (new user). No interaction history to build a user embedding from — fall back to popularity/trending candidates and demographic priors until enough signal accumulates.
  • Cold start (new item). No embedding history — seed from content features (title, category, image embedding) rather than purely collaborative signal, and inject into candidate pools explicitly so it isn't starved of exposure.
  • Feedback loops. Showing an item more makes it get clicked more, which reinforces showing it more — left unchecked this collapses diversity. Mitigate with exploration (small randomized traffic, bandit-style) and explicit diversity terms in re-ranking.
  • Retrieval index staleness. If item embeddings are refreshed daily but catalog changes hourly, brand-new items are invisible to retrieval until the next refresh — the trending/popular candidate source exists partly to patch this gap.
Section 09

Worked Example: Search, Feed & Ads Ranking

"Design search relevance," "design the Instagram feed," "design ad click-through-rate prediction" — architecturally these three are close enough relatives to study together. Know what actually differs.

All three share the retrieval-then-rank shape from Section 8. What differs is the objective, the label, and how directly money is on the line.

Search rankingFeed rankingAd click prediction
ObjectiveRelevance to an explicit queryEngagement / time well spentExpected revenue = P(click) × bid
LabelClick, dwell time, human relevance judgmentsLike, comment, share, watch time, negative feedback (hide/report)Click, and downstream conversion
Candidate sourceInverted index / lexical match + dense retrievalFollow graph + two-tower retrieval + trendingAdvertiser targeting rules + relevance retrieval
Ranking lossOften pairwise/listwise (LambdaMART-style, or a learned cross-encoder)Multi-task: predict several engagement types, combine into one scorePointwise calibrated probability — calibration matters enormously (it's multiplied by a bid)
Distinct hard problemQuery understanding, synonymy, freshness of the indexBalancing many competing objectives without over-optimizing any oneExtreme class imbalance + calibration + auction dynamics

Deep dive: multi-stage ranking with a cascade

At the largest scale, a single ranking model over hundreds of candidates is itself often split further into a cascade: a lightweight model (logistic regression or a small GBDT) scores hundreds down to tens cheaply, then a heavier model (deep cross-network, or a transformer-based re-ranker) scores just the survivors with full feature richness. Each stage narrows the funnel and can afford progressively more expensive computation per item, the same principle as retrieval → ranking, applied again inside ranking itself.

Deep dive: calibration for ad click prediction

In an ads auction, the predicted click probability is multiplied directly by the advertiser's bid to rank ads and set price — a systematically over- or under-confident model doesn't just rank badly, it directly costs or loses revenue. This is why ad-ranking systems obsess over calibration (does a predicted 5% click rate actually convert at ~5% in aggregate) in addition to raw discrimination (AUC), and why post-hoc calibration steps (Platt scaling, isotonic regression) are a standard part of the pipeline, not an afterthought.

Why this matters for interviews

If asked to design ad click prediction and you only talk about AUC, you've missed the domain's actual hard problem. Naming calibration unprompted is a strong senior signal — it shows you understand the score is consumed by a downstream decision (an auction), not just ranked in isolation.

Multi-objective ranking, briefly

Feed ranking rarely optimizes one label. A common pattern: predict several engagement probabilities separately (P(like), P(comment), P(share), P(hide)) with a shared multi-task model, then combine them into one score with hand-tuned or learned weights — explicitly penalizing negative signals like "hide" or "report" rather than only rewarding positive ones. This is a deliberate design choice worth naming: pure engagement-maximization without negative-feedback terms reliably degrades into clickbait and outrage content.

Section 10

Worked Example: Fraud & Anomaly Detection

"Design a real-time fraud-detection system for card transactions." The domain where label latency, extreme imbalance, and hard real-time constraints all collide at once.

1. Clarify & scope

Assume: card-not-present e-commerce transactions, a decision (approve/decline/review) must be returned within ~100-300ms as part of the checkout flow, fraud rate <1% of transactions, and false declines carry real cost (angry legitimate customers) alongside fraud losses.

2. The defining constraint: label latency

The single hardest thing about this domain: you often don't know a transaction was fraud for days to months (a chargeback has to be filed and processed). This means "ground truth" for a given day's training data isn't fully known for a long time — you're always training on a necessarily incomplete, backward-looking label set, and any drift in fraud patterns takes real time to even become measurable in labels, let alone retrain against.

Fig. 3 — The request path (rules + model, top) must resolve in well under 300ms; the label path (bottom) resolves in days-to-months and only ever informs the next model version, never the current decision.

3. Deep dive: rules + model, not model alone

Production fraud systems almost never rely on a model in isolation. A deterministic rules engine (hard blocks on known-bad IPs/BINs, velocity thresholds, sanctioned countries) runs alongside the model for three reasons: rules are instantly auditable and explainable (often a regulatory requirement), rules can react to a newly-discovered fraud pattern within minutes rather than waiting for a retrain, and rules provide a guardrail that catches obvious cases even if the model is temporarily degraded or unavailable.

4. Handling extreme class imbalance

  • Resampling. Oversample the minority (fraud) class or undersample the majority during training so the model isn't overwhelmed by negatives — common baseline, easy to overdo.
  • Class weighting / focal loss. Weight the loss function to penalize missed fraud more heavily than a false positive, tuned to the actual cost asymmetry between the two error types.
  • Anomaly-detection framing. For very rare or novel fraud patterns, unsupervised/semi-supervised approaches (isolation forests, autoencoder reconstruction error) can flag "doesn't look like anything we've seen," complementing a supervised classifier that only knows patterns it's already been labeled on.
  • Threshold, don't just train, around business cost. The approve/decline threshold is a business decision balancing fraud loss against false-decline friction — it's normal for this to be tuned independently of model training, and to differ by transaction segment.
Interview trap

Don't propose retraining "in real time" as if that solves the label-latency problem — it can't, because you don't have real-time labels. The correct framing is: the features can and should update in real time (streaming velocity checks), but the model retrains on a cadence bounded by how fast reliable labels actually arrive, with rules and monitoring covering the gap in between.

Section 11

Worked Example: RAG-Based System

"Design a customer-support assistant grounded in our documentation." The 2026-topical worked example — at the system-design altitude, not the chunking/embedding-model altitude (that depth lives in a companion RAG-focused guide).

1. Clarify & scope

Assume: a chat-style assistant answering questions grounded in a corpus of internal docs (hundreds of thousands of pages, updated continuously), must avoid hallucinating unsupported answers, p95 end-to-end latency budget of a few seconds is acceptable (this is chat, not a ranked list).

2. Why this is a system-design problem, not just a prompting problem

What makes RAG an ML system design question rather than a prompt-engineering one is everything around the LLM call: how documents get ingested, chunked and re-indexed as they change; how retrieval is served at low latency over a large, growing index; how you evaluate quality without a fixed label set; and how you keep the corpus's freshness from silently lagging behind the source of truth — the same offline/online split as every other system in this guide, just with a vector index and an LLM call in the online path.

Offline path (ingestion)

Document source → chunking → embedding model → write to vector index, triggered on a schedule or on document-change events. This is where corpus freshness is won or lost — a doc updated in the source system is only as fresh as the next ingestion run.

Online path (query)

User query → (optional) query rewrite → embed → vector search (+ often a keyword/BM25 pass, combined as hybrid search) → optional re-ranking of retrieved chunks → LLM generation grounded in the retrieved context → response.

3. Deep dive: vector database choice at the system level

The 2026 landscape has enough viable options that the interview-relevant skill is picking dimensions, not memorizing a leaderboard: managed vs. self-hosted operational burden, whether you need it as a bolt-on to a database you already run (pgvector inside Postgres) versus a purpose-built engine (Pinecone, Weaviate, Qdrant, Milvus) at very large scale, and whether hybrid (dense + lexical) search is a first-class feature or something you have to bolt on yourself.

pgvector (Postgres extension)

Bolt-on. Lowest operational overhead if you already run Postgres — one fewer system to operate, transactional consistency with your other data. Scales less gracefully than purpose-built engines at very large (100M+ vector) scale.

Pinecone

Managed, commercial. Fully-managed, serverless-style vector search — the "don't want to operate this" default, at a per-usage cost.

Weaviate / Qdrant / Milvus

Open source (+ managed options). Purpose-built vector engines with native hybrid search and filtering; self-hostable for data-sovereignty needs, or consumed as a managed service from the same vendors.

4. Deep dive: grounding, evaluation, and hallucination

Without a fixed label set, RAG quality is evaluated on several axes rather than one accuracy number: faithfulness (is the answer actually supported by the retrieved context, or did the model add unsupported claims), relevance (did retrieval actually surface the right documents), and answer quality (often via an LLM-as-judge scorer against a curated golden set of Q&A pairs). In production, tracing every step (retrieved chunks, prompt, generated answer) is what makes a bad answer debuggable after the fact — without it, "the answer was wrong" is a dead end, not a root cause.

Why this matters for interviews

Anchor a RAG system-design answer on the same skeleton as everything else in this guide: an offline pipeline that keeps a store fresh, an online path under a latency budget, and a monitoring layer that catches degradation. That framing reads as "I understand this is an ML system with an LLM component," not "I read about RAG once" — the distinction interviewers are actually listening for in 2026.

Section 12

Monitoring & Observability

The system doesn't announce that it's gotten worse. This is the layer that tells you before your business metrics do.

Two axes of health

System health

Axis. Is the service up, is latency within budget, is the error rate normal — standard backend observability (metrics, logs, traces). Necessary but not sufficient: a model can be perfectly healthy on this axis while its predictions quietly degrade.

Prediction-quality health

Axis. Is the model still right. Directly measuring this requires labels, which (per Section 10) are often delayed — so this axis leans heavily on proxy signals that don't require waiting for ground truth.

Drift: the proxy signals that don't need labels

Data drift

Signal. The distribution of input features at serving time has shifted from what the model was trained on — measurable immediately, no labels required. Common metric: Population Stability Index (PSI) or KL-divergence between the training and current feature distributions, monitored per-feature.

Concept drift

Signal. The relationship between features and the label has changed — the same input now implies a different outcome (fraudsters adapt, tastes change). Harder to detect directly without labels; often inferred from a sustained shift in the model's output-score distribution even when inputs look stable.

Prediction drift

Signal. The distribution of the model's outputs has shifted — a cheap, label-free proxy that often moves before you can confirm data or concept drift directly, making it a good first alarm.

Data quality checks

Signal. Null-rate spikes, schema changes, out-of-range values, a feature pipeline silently failing upstream. Not "drift" in the statistical sense, but the single most common real-world cause of a production model going bad overnight — check for it first.

drift_check.pyPython
def population_stability_index(expected, actual, bins=10):
    # Buckets both distributions the same way, then sums the divergence per bucket
    e_pct, a_pct = bucketize(expected, bins), bucketize(actual, bins)
    return sum(
        (a - e) * math.log(a / e)
        for e, a in zip(e_pct, a_pct) if e > 0 and a > 0
    )

# Rule of thumb thresholds used widely in practice:
#   PSI < 0.1  -> no significant shift
#   PSI 0.1-0.25 -> moderate shift, worth investigating
#   PSI > 0.25 -> major shift, page on-call / consider rollback

The monitoring tool landscape

ToolCategoryNotable trait
EvidentlyOpen sourcePopular for drift/data-quality reports and dashboards; easy to self-host and embed in a pipeline
WhyLabsCommercial (+ open-core whylogs)Lightweight statistical profiling library paired with a managed monitoring platform
Arize AICommercialStrong on root-cause analysis (which feature/segment is driving a drift alert) and, increasingly, LLM/agent tracing
Fiddler AICommercialPairs monitoring with model explainability — useful where regulatory/fairness explainability is required
Home-grownDIYFeature-store-adjacent statistics jobs + dashboards (Grafana) over logged predictions — common and valid to propose when asked how you'd build this from scratch
Interview trap

"I'd monitor for drift" is an incomplete answer on its own. State what you'd actually alert on (PSI above a threshold per key feature, a sustained shift in output-score distribution), what the alert triggers (a paged on-call, an automatic rollback, a retraining job), and how you'd distinguish a real problem from a benign seasonal shift — that operational specificity is what's actually being graded.

Section 13

Trade-offs & Failure Modes

A cheat sheet of the tensions this interview format keeps re-testing in different costumes. Recognize the shape, and you'll recognize the question.

TensionPush one way……and you pay
Freshness vs. costStreaming features, frequent retrainingMore infra complexity, more compute spend, more that can break
Latency vs. model complexityA bigger, richer modelSlower inference — may blow the latency budget or force a cheaper funnel stage upstream
Recall vs. precision in retrievalWider candidate generationMore load on the (expensive) ranking stage downstream
Personalization vs. cold startHeavier reliance on user historyNew users/items get poor recommendations until enough signal accumulates
Exploration vs. exploitationMore randomized exploration trafficShort-term engagement/revenue cost for better long-term signal and diversity
Model complexity vs. explainabilityA deep, high-capacity modelHarder to satisfy regulatory/fairness explainability requirements (common in fraud, credit, hiring)
Centralized feature store vs. team autonomyOne shared, governed feature storeCoordination overhead; teams move slower than with their own ad-hoc pipelines
Build vs. buy (feature store, monitoring, serving)A managed platformVendor cost and lock-in, versus the ongoing ops burden of self-hosting

Failure modes worth naming unprompted

  • Silent feature-pipeline failure. A feature quietly starts returning nulls or stale values; the model keeps serving without erroring, and only a data-quality check catches it.
  • Feedback loop collapse. A recommender reinforces its own past decisions until diversity collapses — needs explicit exploration/diversity terms, not just "more data."
  • Retraining on a label distribution that no longer reflects the population being scored (e.g. only retraining on flagged-and-confirmed fraud, not the full transaction population) — a subtle form of sample-selection bias.
  • Cascading staleness. An upstream batch job's delay silently propagates — the online feature store keeps serving yesterday's materialized values with no error, because "stale" isn't "broken."
  • A/B test contamination. Users switching devices/sessions land in both control and treatment, or network effects (a marketplace, a social feed) leak treatment effects into the control group, invalidating the read.
Section 14

Interview Questions

Grouped by depth. Answer out loud, in your own words, before reading the model answer.

Framework & process

frameworkWalk me through how you'd approach an ML system design question you've never seen before.

Clarify the business objective, ML task, and scale/latency constraints; do quick back-of-envelope estimation; sketch the end-to-end architecture (data → features → training → serving → feedback loop); go deep wherever the interviewer steers, usually the model/features for one component or the surrounding infra; then cover scaling and failure modes and close with explicit trade-offs. Say the steps out loud as you move through them.

frameworkHow is ML system design different from general backend system design?

General system design's hard problem is almost entirely scale and availability. ML system design has that, plus a second dimension: prediction quality decays over time even when the system is "up," labels often lag far behind data, and safe rollout has to validate quality, not just correctness — hence shadow deployment, canaries, and A/B tests as a graduated sequence rather than a binary feature flag.

frameworkWhat do you do if you genuinely don't know the answer to a deep-dive question?

State your reasoning process out loud rather than guessing silently: name the trade-off space, propose the most defensible default, and flag it explicitly as an assumption you'd validate ("I'd default to a GBDT here for interpretability and iteration speed, but I'd want to confirm that against your actual latency and team-skills constraints"). Interviewers are grading judgment under uncertainty, not encyclopedic recall.

Estimation

estimationHow would you estimate QPS and storage for a feed-ranking system with 200M daily active users?

QPS: DAU × requests/user/day ÷ 86,400, then apply a peak multiplier (2–5×) since traffic isn't uniform. Storage: events/day × bytes/event × retention period, then discount for compression (columnar formats typically buy back 3–10×). State the assumptions explicitly, round aggressively, and move on — the arithmetic should take under two minutes.

estimationGiven a 200ms end-to-end latency SLA, how do you allocate it across a retrieval + ranking pipeline?

Start from the total and subtract fixed overhead (network, auth, gateway) first, then divide what's left across retrieval, feature lookup, and model inference based on which is the bottleneck — ranking a large candidate set is usually the biggest single line item. Always leave headroom below the p99 target for tail variance rather than budgeting to exactly 200ms.

Architecture & feature stores

architectureWhat is training/serving skew, and how do you prevent it?

It's when a feature is computed differently offline (training) than online (serving), so the model sees a different distribution of feature values in production than it was trained on, degrading quality without any visible error. The standard prevention is a feature store: define each feature's computation once and serve it identically to both training and inference paths, rather than maintaining separate offline and online implementations.

feature-storeWhat is point-in-time correctness, and why does it matter?

When building a training set from historical data, each row's feature values must reflect what was true at that historical moment, not current values — otherwise you leak future information into training (label leakage), which inflates offline metrics and fails silently in production. Feature stores implement this via as-of joins keyed on each row's timestamp.

feature-storeWhen would a feature be computed as a streaming feature versus a batch feature?

Tie it to how fast the underlying signal actually changes and how much staleness the use case can tolerate: a fraud velocity feature needs streaming because fraud happens in seconds; a user's long-run purchase-category preference is fine as a nightly batch job because taste doesn't shift minute to minute. Streaming is more operationally expensive, so it should be a deliberate choice, not a default.

architectureWhy is retrieval/candidate-generation typically a separate stage from ranking, rather than one model?

Scoring every item for every user with a rich model is computationally infeasible at scale (millions of items × per-request). A cheap, high-recall retrieval stage narrows the space to hundreds of candidates first; a more expensive, high-precision ranking model then scores only those. It's a deliberate precision/compute trade-off applied twice, at two different price points.

architectureExplain a two-tower model and why it enables fast retrieval.

Two separate networks encode users and items into a shared embedding space, trained so engaged user-item pairs have high similarity. Because the towers are independent, item embeddings can be pre-computed offline and indexed once (ANN index); at serving time you only compute the user embedding and do a fast approximate nearest-neighbor lookup, never re-running a full network per item.

Serving & deployment

servingWalk through the stages of safely rolling out a new model version.

Offline evaluation against the current champion, then shadow deployment (scores live traffic, predictions discarded — validates latency and infra correctness with zero user risk), then a small-percentage canary (validates real-world serving behavior at limited blast radius), then a randomized A/B test measured against the actual business metric, then full rollout with the prior model kept warm for instant rollback.

servingWhat's the difference between shadow deployment and a canary release?

Shadow deployment scores live traffic in parallel but never serves the result to a user — it validates latency and correctness with zero risk, purely by diffing against the current production model's behavior. A canary release actually serves the new model to a small real traffic slice, which is what's needed to observe real user response, not just infra health.

servingWhat's the difference between vLLM and a general-purpose server like Triton, and when would you choose each?

vLLM is purpose-built for LLM inference — PagedAttention plus continuous batching give it strong throughput specifically for autoregressive generation. Triton is a general multi-framework, multi-model server, better suited to serving several different model types or an ensemble pipeline behind one endpoint, at the cost of more setup overhead than a single-model LLM deployment needs. Pick vLLM (or SGLang for heavy multi-turn/agentic reuse) for a pure LLM-serving workload; reach for Triton when you're serving a heterogeneous fleet of models.

Scenario-based & worked examples

scenarioDesign a real-time fraud-detection system for card transactions. What's the hardest constraint?

Label latency: confirmed fraud (chargebacks) can take days to months to resolve, so training data is always incomplete and backward-looking, and model drift takes real time to even become measurable. Production systems compensate with a deterministic rules engine alongside the model (instant reaction to newly-discovered patterns, auditable, resilient if the model degrades), streaming features for real-time signal, and a retraining cadence bounded by how fast reliable labels actually arrive — not by wishful "real-time retraining."

scenarioHow would you handle extreme class imbalance in a fraud or anomaly-detection model?

Resampling (oversample the minority class or undersample the majority) or class-weighted/focal loss during training; anomaly-detection framing (isolation forests, autoencoder reconstruction error) to catch novel patterns a supervised model has never seen labeled; and tune the approve/decline decision threshold separately as a business-cost trade-off between fraud loss and false-decline friction, rather than baking one fixed threshold into training.

scenarioDesign ad click-through-rate prediction. Why does calibration matter more here than in most ML problems?

The predicted click probability is multiplied directly by the advertiser's bid to rank and price ads in the auction — a systematically over- or under-confident model doesn't just rank worse, it directly misprices revenue. This is why CTR pipelines add explicit post-hoc calibration (Platt scaling, isotonic regression) and monitor calibration continuously, not just discrimination metrics like AUC.

scenarioHow would you prevent a recommendation system's feedback loop from collapsing content diversity?

Add explicit exploration — a small slice of randomized or bandit-driven traffic that surfaces items outside the model's current confidence, purely to keep collecting unbiased signal — plus explicit diversity terms in the re-ranking stage rather than relying on the ranking model's raw score alone, which will otherwise keep reinforcing whatever it already favors.

scenarioDesign a RAG-based support assistant grounded in internal documentation. What makes this an ML system design question rather than a prompting question?

Everything around the LLM call: an offline ingestion pipeline that chunks, embeds, and re-indexes documents as they change (and how corpus freshness lags the source of truth), an online path under a latency budget doing retrieval (often hybrid dense + lexical) and optional re-ranking before generation, and an evaluation/monitoring layer (faithfulness, retrieval relevance, LLM-as-judge against a golden set) since there's no fixed label set to fall back on.

scenarioA ranking model's offline metrics improved after a retrain, but the following week's A/B test showed a regression. What would you investigate?

First, training/serving skew introduced by the retrain (a feature computed differently than before, or a bug in the new pipeline) — check the online feature distribution against what the model was trained on. Second, a mismatch between the offline metric and the actual business metric being optimized (offline AUC improving while a downstream real-world effect, like reduced diversity or a feedback loop, gets worse). Third, A/B test validity itself — contamination, insufficient sample size, or a novelty effect that will fade.

Monitoring & production

monitoringHow do you detect model degradation when true labels are delayed by weeks?

Lean on label-free proxies: data drift (has the input feature distribution shifted from training, measured via PSI or KL-divergence per feature), and prediction drift (has the output-score distribution shifted). Neither proves the model is wrong, but a sustained shift in either is the earliest available signal, and it's cheap to compute continuously without waiting for ground truth.

monitoringWhat's the difference between data drift and concept drift?

Data drift is a shift in the input feature distribution itself (users are now, say, transacting at different amounts) — detectable immediately, no labels needed. Concept drift is a shift in the relationship between features and the label (the same input now implies a different outcome, e.g. fraudsters adapting their tactics) — harder to detect directly without labels, often inferred indirectly from a sustained output-drift signal.

monitoringWhat would you actually alert on for a production ranking model, beyond "accuracy dropped"?

Data-quality checks first (null-rate spikes, schema changes, an upstream pipeline silently failing — the most common real-world cause), then per-feature PSI against the training distribution, then output-score distribution shift, then, once labels do arrive, the actual business metric against a rolling baseline. Each should map to a defined action — page on-call, trigger a rollback, or kick off a retraining job — not just a dashboard nobody watches.

Trade-offs

tradeoffWhen would you choose a simpler model (logistic regression, GBDT) over a deep neural network for a production system?

When training data is limited, when inference latency is tightly budgeted and a simpler model clears it more reliably, when explainability/regulatory requirements matter (fraud, credit, hiring), or when the team's ability to iterate and debug quickly outweighs a marginal accuracy gain from added complexity — "start with the simplest model that meets the requirements" is the right default framing to open with, then justify complexity where it's earned.

tradeoffHow do you decide retraining cadence — hourly, daily, or weekly?

Balance three things: how fast the underlying distribution actually drifts (a fast-moving fraud landscape needs more frequent retraining than slow-moving user taste), how quickly reliable labels accumulate (no point retraining daily if labels resolve over weeks), and the cost/complexity of the retraining pipeline itself. State the reasoning, not just a cadence — "daily" said without justification is a weaker answer than "daily, because our label latency is ~48h and daily is the fastest cadence that reliably captures fresh signal without retraining on mostly-repeated data."

Section 15

Glossary

Every term used in this guide, in one place.

A/B Test
A randomized controlled rollout comparing a new model against the current one on a live business metric, with statistical power to detect a real difference.
ANN (Approximate Nearest Neighbor)
An index (HNSW, IVF) that finds vectors close to a query vector in sub-linear time, trading a small amount of recall for large speed gains — what makes retrieval over hundreds of millions of items feasible.
Backfill
Recomputing historical feature or label values, typically needed when a feature definition changes and existing training data must be regenerated consistently.
Calibration
Whether a model's predicted probabilities match real-world outcome frequencies (a predicted 5% click rate should convert at ~5%) — distinct from discrimination (AUC), and critical wherever a score is used directly in downstream math (e.g. an ad auction).
Candidate Generation
The first stage of a retrieval-then-rank funnel: a cheap, high-recall model that narrows a huge item pool to a few hundred plausible candidates.
Canary Release
Serving a new model to a small percentage of live traffic to validate real-world behavior at limited blast radius, before a full A/B test or rollout.
Champion/Challenger
The standing pattern where a current production model (champion) keeps serving while a candidate replacement (challenger) is evaluated against it before any promotion decision.
Concept Drift
A shift in the relationship between features and the label over time — the same input now implies a different true outcome.
Data Drift
A shift in the distribution of input features at serving time relative to training — detectable without labels.
Feature Freshness
How recently a feature's value was computed relative to now; the acceptable staleness depends entirely on how fast the underlying signal changes.
Feature Store
A system that computes, stores, and serves features for both training and inference from a single shared definition, to prevent training/serving skew.
Hybrid Search
Combining dense (embedding/vector) retrieval with sparse lexical (keyword/BM25) retrieval, typically merged via a fused ranking, to catch both semantic and exact-term matches.
KV Cache
The cached key/value attention state an LLM reuses across generation steps; efficient management of it (PagedAttention, RadixAttention) is the main lever behind modern LLM-serving throughput.
Label Latency
The delay between an event occurring and its true outcome (label) becoming known — minutes for a click, months for a loan default or a chargeback.
Materialization
The process of copying/syncing computed feature values from the offline feature store into the low-latency online store so they're available for real-time serving.
Model Registry
A versioned, governed store tracking a model's lineage from training run through approval to production deployment.
Model Staleness
The degradation in a model's real-world accuracy as the live data distribution drifts away from what it was trained on, purely as a function of time since training.
Multi-Task Ranking
Predicting several related engagement signals (like, comment, share, hide) with one shared model and combining them into a single ranking score, rather than optimizing one label in isolation.
Offline Feature Store
The batch-queryable half of a feature store (data warehouse / lake) used to build training sets, typically via point-in-time joins.
Online Feature Store
The low-latency key-value half of a feature store (Redis, DynamoDB) used to fetch precomputed features at inference time under a strict latency budget.
p99 Latency
The 99th-percentile response latency — the value below which 99% of requests fall; the metric a latency SLA is usually actually defended against, since averages hide tail behavior.
Point-in-Time Correctness
The guarantee that a feature value used in a historical training row reflects what was true as of that row's timestamp, not the current value — prevents label leakage.
Population Stability Index (PSI)
A statistic quantifying how much a feature's distribution has shifted between two periods (e.g. training vs. current production) — a common threshold-based drift alarm.
Prediction Drift
A shift in the distribution of a model's output scores over time — a cheap, label-free early-warning proxy for degradation.
QPS
Queries per second — the primary throughput unit used in capacity planning for a serving system.
RAG (Retrieval-Augmented Generation)
An architecture where an LLM's response is grounded by retrieving relevant documents/context at query time, rather than relying solely on its trained-in knowledge.
Ranking
The second stage of a retrieval-then-rank funnel: a more expensive, high-precision model that scores a small candidate set with richer features.
Re-ranking
A final adjustment pass applied after the main ranking model — business rules, diversity constraints, or a heavier cross-encoder model applied to a now-small candidate list.
Retraining Cadence
How often a model is retrained on fresh data — a deliberate trade-off between staleness risk, label availability, and compute/pipeline cost.
Shadow Deployment
Running a new model on live traffic in parallel with production, logging its predictions without ever serving them to a user — validates latency and infra correctness at zero user risk.
Skew (Training/Serving)
A discrepancy between how a feature is computed during training versus at serving time, causing the model to see different feature values in production than it learned from.
Streaming Feature
A feature computed continuously from an event stream (Flink/Kafka) with freshness measured in seconds, used where staleness of minutes would defeat the feature's purpose.
Two-Tower Model
A retrieval architecture with two independent encoder networks (user and item), trained so engaged pairs are close in a shared embedding space — enables offline-precomputed item embeddings and fast ANN lookup at serving time.
Vector Database
A datastore purpose-built to index and query high-dimensional embedding vectors by similarity, typically via an ANN index — the retrieval backbone of a RAG system.
Section 16

Sources