Slides · ML systems and interviews
ML system design: framing, budgets, two-stage retrieval, serving, rollout and monitoring
1 / 29
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:
- Frame a problem and run the nine-step framework.
- Choose an inference mode and do back-of-envelope capacity.
- Design a retrieve-rank-re-rank funnel and measure each stage.
- Pick serving levers and roll out safely.
- Monitor, break feedback loops, and name technical debt.
Diagram
The design loop
Compare
Is this an ML problem
| Ask | If 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.
Source[1] 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
| Layer | Food-delivery feed |
|---|---|
| Goal | More orders without hurting delivery times |
| Objective | Probability the user orders from this restaurant |
| Metric | Offline recall@k, NDCG@k. Online order rate |
| Guardrail | Delivery 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
Compare
Batch, online, streaming
| Mode | Runs | Costs |
|---|---|---|
| Batch | On a schedule | Stale between runs |
| Online | Per request | Hard latency budget |
| Streaming | As events arrive | State, 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=λ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
| Statistic | Simulated (ms) |
|---|---|
| Mean | 45.2 |
| p50 | 40.1 |
| p95 | 91.5 |
| p99 | 126.2 |
| Slowest | 277.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.
Source[2] 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
Embedding retrieval is usually served from an approximate nearest-neighbour index such as HNSW, so retrieval recall is measured, not assumed.
Sources[3] Deep Neural Networks for YouTube Recommendations[4] Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs
Math
Recall@k and NDCG@k
recall@k=∣relevant∣∣top-k∩relevant∣,NDCG@k=IDCG@k∑i=1kgi/log2(i+1)- 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.
Worked example
Candidates against quality
| Candidates | Recall | Final NDCG@10 |
|---|---|---|
| 50 | 0.165 | 0.472 |
| 200 | 0.284 | 0.654 |
| 500 | 0.395 | 0.772 |
| 2,000 | 0.613 | 0.903 |
| 20,000 (no retrieval) | 1.000 | 0.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
| Design | Emphasis |
|---|---|
| Recommender | Cold start, position bias, feedback loops |
| Search | Hybrid retrieval, learning to rank, NDCG and MRR |
| Fraud | Imbalance, delayed and selective labels, cost-based threshold |
| Ads | Calibration: 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.
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.
Sources[1] Rules of Machine Learning: Best Practices for ML Engineering[7] Concepts overview (Feast documentation)
Compare
Serving levers
| Lever | Gain | Cost |
|---|---|---|
| Cache | Skip repeated work (0.391 hit rate at 1% of keys) | Stale answers |
| Batching | Throughput (batch 16: 1000 items/s at 16 ms) | Latency |
| Quantisation | 400 MB to 100 MB for 100M parameters | Some accuracy |
| Distillation | A smaller, faster student | Train twice |
- Pull them cheapest first, and re-run offline evaluation after each.
Sources[8] Distilling the Knowledge in a Neural Network[9] 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.
| Batch | Latency (ms) | Items per second |
|---|---|---|
| 1 | 8.5 | 117.6 |
| 8 | 12.0 | 666.7 |
| 16 | 16.0 | 1000.0 |
| 64 | 40.0 | 1600.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
Source[10] 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 shown | Share of the top item |
|---|---|---|
| Always show the best so far | 14 | 0.998 |
| Explore 10% at random | 55 | 0.670 |
- The model decides what it learns about. Keep an exploration or random holdout slice and log propensities.
Source[11] 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 |
|---|---|
| Entanglement | Ablations, ownership |
| Undeclared consumers | Versioned outputs, registry |
| Data dependencies | Schema checks, contracts |
| Hidden feedback loops | Exploration slice, logging |
| Configuration issues | Config in version control |
- Every part needs an owner, a test and a monitor.
Source[11] 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)
Rules of Machine Learning: Best Practices for ML Engineering (opens in a new tab)
Google for Developers2026Article
https://developers.google.com/machine-learning/guides/rules-of-ml
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.
The Tail at Scale (opens in a new tab)
Jeffrey Dean, Luiz Andre Barroso2013Communications of the ACM 56(2), pp. 74-80Paper
https://research.google/pubs/the-tail-at-scale/
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).
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
https://research.google/pubs/deep-neural-networks-for-youtube-recommendations/
Used for A large production recommender split into a deep candidate generation model and a separate deep ranking model (abstract page).
Yu. A. Malkov, D. A. Yashunin2016arXiv:1603.09320Paper
https://arxiv.org/abs/1603.09320
Used for HNSW as a multi-layer proximity-graph method for approximate nearest-neighbour search with reported logarithmic scaling (arXiv abstract).
ndcg_score (scikit-learn API reference) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.ndcg_score.html
Used for NDCG with a logarithmic discount, normalised by the ideal score, with tied predictions averaged by default.
References
References & Sources (2 of 3)
Unbiased Learning-to-Rank with Biased Feedback (opens in a new tab)
Thorsten Joachims, Adith Swaminathan, Tobias Schnabel2016arXiv:1608.04468Paper
https://arxiv.org/abs/1608.04468
Used for Position bias in click data and propensity-weighted learning to rank (arXiv abstract).
Concepts overview (Feast documentation) (opens in a new tab)
Feast2026Documentation
https://docs.feast.dev/getting-started/concepts/overview
Used for A feature view's data source is used both to generate training datasets and to materialise features into the online store.
Distilling the Knowledge in a Neural Network (opens in a new tab)
Geoffrey Hinton, Oriol Vinyals, Jeff Dean2015arXiv:1503.02531Paper
https://arxiv.org/abs/1503.02531
Used for Compressing the knowledge of an ensemble into a single model that is easier to deploy (arXiv abstract).
Benoit Jacob, Skirmantas Kligys, Bo Chen, Menglong Zhu, et al.2017arXiv:1712.05877Paper
https://arxiv.org/abs/1712.05877
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).
Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing (opens in a new tab)
Ron Kohavi, Diane Tang, Ya Xu2020Book
https://www.cambridge.org/core/books/trustworthy-online-controlled-experiments/D97B26382EB0EB2DC2019A7A7B518F59
Used for The practice of running trustworthy online controlled experiments (A/B tests); publisher description only.
References
References & Sources (3 of 3)
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
https://papers.nips.cc/paper_files/paper/2015/hash/86df7dcfd896fcaf2674f757a2463eba-Abstract.html
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.
Keys: ← → move, Home End first and last, F full screen.