Slides · ML systems and interviews

ML system design: framing, budgets, two-stage retrieval, serving, rollout and monitoring

ML system design

Framing, budgets, two-stage retrieval, serving, rollout and monitoring.

Concept

Why this is worth 100 minutes

  • Most of an ML product is not the model. Google’s guide says to be unafraid of launching without ML and to keep the first model simple while the infrastructure is right.
  • The system design round is graded on structure, stated trade-offs and failure modes named early (common industry pattern).
  • Mental model: a funnel with a feedback loop. Every choice trades quality, latency, cost and risk.

Five things you will be able to do:

  1. Frame a problem and run the nine-step framework.
  2. Choose an inference mode and do back-of-envelope capacity.
  3. Design a retrieve-rank-re-rank funnel and measure each stage.
  4. Pick serving levers and roll out safely.
  5. Monitor, break feedback loops, and name technical debt.

Diagram

The design loop

Diagram: Goal to data to features to model to serving to online evaluation to monitoring, with logs and drift signals returning to the data step.

logs, drift, feedback

Goal, metric,
constraints

Data and
labels

Features

Model
stages

Serving

Online
evaluation

Monitoring

Diagram summary: Goal to data to features to model to serving to online evaluation to monitoring, with logs and drift signals returning to the data step.

Compare

Is this an ML problem

AskIf the answer is no
Do simple rules fall short?Ship the rule
Is there a label or feedback signal?Collect data first
Is an error affordable?Add human review
Can you use an opaque model?Limit model choices
  • A heuristic is cheap and brittle; a model is accurate and costs maintenance for its whole life.
  • Ship the baseline, log decisions and corrections, and let them become labels.

Source1 Rules of Machine Learning: Best Practices for ML Engineering

Check yourself

Check: the first sentence

An interviewer says “design a spam filter for a chat app”. What do you say before drawing anything?

Answer

Ask for scale, the cost of a false positive against a missed spam message, the latency allowed, and what labels exist (user reports?). State assumptions, name a simple rule baseline, then give the metric and one guardrail, such as the rate of blocked genuine messages.

Worked example

Goal, objective, metric

LayerFood-delivery feed
GoalMore orders without hurting delivery times
ObjectiveProbability the user orders from this restaurant
MetricOffline recall@k, NDCG@k. Online order rate
GuardrailDelivery ETA, cancellations
  • A proxy objective such as clicks can rise while the goal falls.
  • Constraints (scale, latency, freshness, cost, privacy) choose the architecture, so ask first.

Diagram

The nine steps

Diagram: Nine steps from framing to monitoring, with a dotted arrow back to framing.

revisit

1 Frame
goal, scale, constraints

2 Data and labels

3 Baseline

4 Features

5 Model

6 Offline evaluation

7 Serving

8 Online evaluation, rollout

9 Monitoring, risks

Diagram summary: Nine steps from framing to monitoring, with a dotted arrow back to framing. A suggested 35-minute split is 4, 4, 2, 4, 5, 3, 5, 3, 5 minutes.

Compare

Batch, online, streaming

ModeRunsCosts
BatchOn a scheduleStale between runs
OnlinePer requestHard latency budget
StreamingAs events arriveState, ordering, late events
  • Mix them: slow features in batch, fast aggregates by streaming, final scoring online.
  • Pick the slowest mode the product tolerates.

Math

Capacity by hand

L=λWL=\lambda W
  • 5M daily users x 4 sessions = 20,000,000 requests a day = 231.48 per second. Peak x3 = 694.44 (assumed).
  • 694.44 x 0.060 s = 41.7 in flight. At 8 per server and 50% load, each carries 4: 11 servers.
  • $0.40 per server-hour gives $105.60 a day, $5.28 per million requests.
  • Memory: 200,000 x 64 floats = 51.2 MB. 100,000,000 x 128 = 51.2 GB.

Worked example

Latency is a distribution

StatisticSimulated (ms)
Mean45.2
p5040.1
p9591.5
p99126.2
Slowest277.5
  • Serial steps add. Parallel calls cost their maximum.
  • Ten calls each slow 1% of the time: 1 - 0.99^10 = 0.0956 of requests wait on one.
  • Timeout 100 ms plus a 5 ms fallback: 3.20% fall back, slowest served 105.0 ms.

Source2 The Tail at Scale

Check yourself

Check: a request path

A request does a 8 ms lookup, then three feature fetches of 15, 25 and 12 ms, then a 6 ms model call. What is the latency if the fetches run in parallel, and in series?

Answer

Parallel: 8 + max(15, 25, 12) + 6 = 39 ms. In series: 8 + 15 + 25 + 12 + 6 = 66 ms. Parallel calls help the mean, but the page still waits for the slowest fetch, so its tail sets the path’s tail.

Diagram

The funnel

Diagram: A request narrows from millions of items to a short list through candidate generation, a ranker and a re-ranker.

Request

Candidate generation
cheap, high recall
millions to hundreds

Ranker
rich features, accurate
hundreds to tens

Re-ranker
diversity, rules,
fairness, exploration

Result list

Impressions, clicks, orders

Training pipelines

Diagram summary: A request narrows from millions of items to a short list through candidate generation, a ranker and a re-ranker. User actions on the list are logged and train both models.

Embedding retrieval is usually served from an approximate nearest-neighbour index such as HNSW, so retrieval recall is measured, not assumed.

Sources3 Deep Neural Networks for YouTube Recommendations4 Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs

Math

Recall@k and NDCG@k

recall@k=∣top-k∩relevant∣∣relevant∣,NDCG@k=∑i=1kgi/log⁡2(i+1)IDCG@k\mathrm{recall@}k=\frac{|\text{top-}k\cap\text{relevant}|}{|\text{relevant}|},\qquad \mathrm{NDCG@}k=\frac{\sum_{i=1}^{k} g_i/\log_2(i+1)}{\mathrm{IDCG@}k}
  • Recall judges the retriever: a dropped item can never be shown.
  • NDCG judges the ranker: the best items should come first.
  • Gains 1 and 3 in that order: 2.893 / 3.631 = 0.797.

Source5 ndcg_score (scikit-learn API reference)

Worked example

Candidates against quality

CandidatesRecallFinal NDCG@10
500.1650.472
2000.2840.654
5000.3950.772
2,0000.6130.903
20,000 (no retrieval)1.0000.944
  • Quality is capped by retrieval recall. A better ranker does not rescue a weak retriever.
  • Ranker cost grows with the candidate count. The latency budget picks the point.

Check yourself

Check: where to look

A search system retrieves 1,000 candidates and finds 95% of the relevant items among them. NDCG@10 is still poor. Which stage do you investigate first, and why?

Answer

The ranker or its features and labels. Recall of 0.95 at the retriever means few relevant items were lost, so the weakness is in how the candidates are ordered. Check position-bias in the click labels and features missing at ranking time.

Compare

Four designs

DesignEmphasis
RecommenderCold start, position bias, feedback loops
SearchHybrid retrieval, learning to rank, NDCG and MRR
FraudImbalance, delayed and selective labels, cost-based threshold
AdsCalibration: value is pCTR x bid
  • Fraud threshold: act when p > F / (F + L) = 4 / 84 = 0.0476, if scores are calibrated.
  • Keep a random approval holdout so declined transactions do not blind you.

Source6 Unbiased Learning-to-Rank with Biased Feedback

Concept

Training and serving the same

  • One feature definition for both paths. Re-use code. Log the features served and train on them.
  • A feature store has an offline side (training, point-in-time joins) and an online side (low-latency reads), fed from one data source definition.
  • Cost: another system to run and a schema to govern. It pays off when many models share features.
  • See the skew section of the previous module.

Sources1 Rules of Machine Learning: Best Practices for ML Engineering7 Concepts overview (Feast documentation)

Compare

Serving levers

LeverGainCost
CacheSkip repeated work (0.391 hit rate at 1% of keys)Stale answers
BatchingThroughput (batch 16: 1000 items/s at 16 ms)Latency
Quantisation400 MB to 100 MB for 100M parametersSome accuracy
DistillationA smaller, faster studentTrain twice
  • Pull them cheapest first, and re-run offline evaluation after each.

Sources8 Distilling the Knowledge in a Neural Network9 Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference

Worked example

Batching by hand

Assume 8 ms fixed and 0.5 ms per item.

BatchLatency (ms)Items per second
18.5117.6
812.0666.7
1616.01000.0
6440.01600.0
  • Under a 20 ms cap the best batch is 24 (1200.0 items per second).
  • Waiting for a batch to fill adds more latency that this table ignores.

Diagram

Rollout ladder

Diagram: Offline evaluation, shadow, canary, A/B test and ramp, with rollback available from the canary and the A/B stage when a guardrail is...

guardrail breached

guardrail breached

Offline evaluation

Shadow
score, do not act

Canary
small share of traffic

A/B test
randomised, guardrails

Ramp to 100%

Monitor

Rollback

Diagram summary: Offline evaluation, shadow, canary, A/B test and ramp, with rollback available from the canary and the A/B stage when a guardrail is breached.

Source10 Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing

Check yourself

Check: win offline, lose online

A ranker improves NDCG offline and lowers orders in the A/B test. Give three explanations.

Answer

Logged data came from the old system, so offline relevance mixes in position bias and selection. The offline metric may not measure the goal (orders). Serving may differ from training features, or latency rose and hurt conversion. Compare served and training features and check latency percentiles per arm before trusting either result.

Worked example

A toy feedback loop

Ten items; item 7 has a true click rate of 0.15, the rest 0.10.

Policy (100 runs)Item 7 most shownShare of the top item
Always show the best so far140.998
Explore 10% at random550.670
  • The model decides what it learns about. Keep an exploration or random holdout slice and log propensities.

Source11 Hidden Technical Debt in Machine Learning Systems

Concept

Fallbacks and humans

  • Fallback ladder: full model, cheaper model, cached default, rule. Decide the order in advance.
  • Monitor the fallback rate, not only accuracy: requests cut by a timeout leave the accuracy figure.
  • Every remote call has a timeout. Safety checks have an explicit fail-open or fail-closed rule.
  • Human review for the uncertain middle band and costly errors. Reviewer capacity limits the band. In clinical alerts, alert fatigue limits it.

Compare

Technical debt

Risk (from the paper’s abstract)Defence
EntanglementAblations, ownership
Undeclared consumersVersioned outputs, registry
Data dependenciesSchema checks, contracts
Hidden feedback loopsExploration slice, logging
Configuration issuesConfig in version control
  • Every part needs an owner, a test and a monitor.

Source11 Hidden Technical Debt in Machine Learning Systems

Code

Homework: the system design toolkit

Python

def servers_needed(qps, latency_s, concurrency, target_util):
    """Little's law, rounded up."""

def ndcg_at_k(ranked, gains, k):
    """DCG over the ideal DCG."""

def two_stage(retrieved, scores, n_candidates, k):
    """Re-rank only the retriever's candidates."""

def lru_hit_rate(requests, capacity):
    """Hits divided by requests."""
  • Also: percentile, path latency, cost, recall@k, batching, timeout with fallback.

Summary

Recap

  • Ask if ML is needed, separate goal, objective and metric, name a guardrail, and state constraints first.
  • Run the nine steps, say trade-offs aloud, start with a baseline.
  • Budget percentiles, do capacity arithmetic with stated assumptions, and mix inference modes.
  • Retrieve, rank, re-rank. Retrieval recall caps quality. Recall@k for the first stage, NDCG@k for the second.
  • One feature definition, serving levers cheapest first, rollout by shadow, canary and A/B with rollback.
  • Monitor fallbacks and drift, break feedback loops with exploration, and give every part an owner.

References

References & Sources (1 of 3)

  1. Rules of Machine Learning: Best Practices for ML Engineering (opens in a new tab)

    Google for Developers2026Article

    Used for Rule 1 (do not be afraid to launch without ML), rule 4 (keep the first model simple and get the infrastructure right), rule 36 (positional features, same default value at serving), rules 29 and 32 on logging serving-time features and re-using code, and rule 8 on asking how much performance falls if the model is a day old.

  2. The Tail at Scale (opens in a new tab)

    Jeffrey Dean, Luiz Andre Barroso2013Communications of the ACM 56(2), pp. 74-80Paper

    Used for Brief slowdowns that are harmless in small systems can dominate latency at scale, and the idea of latency tail-tolerant design (abstract page).

  3. Deep Neural Networks for YouTube Recommendations (opens in a new tab)

    Paul Covington, Jay Adams, Emre Sargin2016Proceedings of the 10th ACM Conference on Recommender SystemsPaper

    Used for A large production recommender split into a deep candidate generation model and a separate deep ranking model (abstract page).

  4. Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (opens in a new tab)

    Yu. A. Malkov, D. A. Yashunin2016arXiv:1603.09320Paper

    Used for HNSW as a multi-layer proximity-graph method for approximate nearest-neighbour search with reported logarithmic scaling (arXiv abstract).

  5. ndcg_score (scikit-learn API reference) (opens in a new tab)

    scikit-learn2026Documentation

    Used for NDCG with a logarithmic discount, normalised by the ideal score, with tied predictions averaged by default.

References

References & Sources (2 of 3)

  1. Unbiased Learning-to-Rank with Biased Feedback (opens in a new tab)

    Thorsten Joachims, Adith Swaminathan, Tobias Schnabel2016arXiv:1608.04468Paper

    Used for Position bias in click data and propensity-weighted learning to rank (arXiv abstract).

  2. Concepts overview (Feast documentation) (opens in a new tab)

    Feast2026Documentation

    Used for A feature view's data source is used both to generate training datasets and to materialise features into the online store.

  3. Distilling the Knowledge in a Neural Network (opens in a new tab)

    Geoffrey Hinton, Oriol Vinyals, Jeff Dean2015arXiv:1503.02531Paper

    Used for Compressing the knowledge of an ensemble into a single model that is easier to deploy (arXiv abstract).

  4. Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference (opens in a new tab)

    Benoit Jacob, Skirmantas Kligys, Bo Chen, Menglong Zhu, et al.2017arXiv:1712.05877Paper

    Used for A quantisation scheme for integer-arithmetic-only inference, with a co-designed training procedure that preserves end-to-end accuracy after quantisation (arXiv abstract).

  5. Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing (opens in a new tab)

    Ron Kohavi, Diane Tang, Ya Xu2020Book

    Used for The practice of running trustworthy online controlled experiments (A/B tests); publisher description only.

References

References & Sources (3 of 3)

  1. Hidden Technical Debt in Machine Learning Systems (opens in a new tab)

    D. Sculley, Gary Holt, Daniel Golovin, Eugene Davydov, et al.2015NeurIPS 2015 (Advances in Neural Information Processing Systems 28)Paper

    Used for The list of ML-specific risk factors (boundary erosion, entanglement, hidden feedback loops, undeclared consumers, data dependencies, configuration issues, changes in the external world, system-level anti-patterns) from the abstract page.