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

  • Production
  • 1 h 40 min
  • Lesson 1 of 3 in ML systems and interviews
  • Last verified

Open slides(29 slides)

Before you start

You will be able to

  • Decide whether a problem needs ML, turn a business goal into an objective, a metric and constraints, and run the nine-step design framework out loud with trade-offs.
  • Choose batch, online or streaming inference, and do back-of-envelope capacity, latency-budget and cost estimates with stated assumptions, using percentiles and not means.
  • Explain why large systems retrieve, rank and re-rank, measure each stage with recall@k and NDCG@k, and sketch recommender, search, fraud and ads designs at overview level.
  • Name the serving levers (batching, caching, quantisation, distillation), keep training and serving features consistent, and roll a model out by shadow, canary and A/B.
  • Monitor a live ML system, spot feedback loops, design fallbacks and human review, and name the main sources of ML technical debt.

Concept

The previous module ended with a model that is honestly evaluated, fed clean point-in-time features and watched for drift. This lesson zooms out one more level. An ML system is a model plus everything that feeds it, serves it, tests it and keeps it healthy. In an interview, “design a recommender” or “design a fraud detector” asks whether you can think about that whole system under constraints, out loud, in about 35 minutes.

QuestionTool in this lesson
Should this be ML at all, and what are we optimising?Heuristic baseline, objective against metric, constraints
What do I say, and in what order?The nine-step framework
When is the prediction computed?Batch, online and streaming inference
Will it fit the latency and the budget?Latency budgets, percentiles, Little’s law, back-of-envelope capacity
How do I score millions of items per request?Candidate generation, ranking, re-ranking
How do I keep training and serving the same?One feature definition, feature stores, logging
How do I make serving fast and cheap?Batching, caching, quantisation, distillation
How do I ship it safely?Shadow, canary, A/B, rollback
What breaks after launch?Drift, feedback loops, fallbacks, human review, technical debt

Why It Matters

Most of the work in a production ML system is not the model. Google’s guide to ML engineering says so bluntly: its first rule is not to be afraid to launch a product without machine learning, and its fourth is to keep the first model simple and get the infrastructure right (Rules of ML). The hidden technical debt paper lists the system-level risks specific to ML: boundary erosion, entanglement, hidden feedback loops, undeclared consumers, data dependencies, configuration issues and changes in the external world (Sculley et al., 2015).

For an interview this round is the senior differentiator (common industry pattern). It is graded on structure, trade-offs said aloud and failure modes named before you are asked, more than on any one clever model (common industry pattern).

Mental Model

Think of the design as a funnel with a feedback loop. Requests and candidates go in at the top. Each stage is more expensive per item and sees fewer items. Logs from the bottom come back to train the top. Every design decision is a trade among four things: quality, latency, cost and risk.

Diagram: A design runs from goal to data to features to model to serving to online evaluation to monitoring, and monitoring returns logs and drift...

logs, drift, feedback

Goal, metric,
constraints

Data and
labels

Features

Model
stages

Serving

Online
evaluation

Monitoring

Diagram summary: A design runs from goal to data to features to model to serving to online evaluation to monitoring, and monitoring returns logs and drift signals to the data step. Treat the loop, not the model, as the unit of design.

Is this an ML problem

Start with the question most candidates skip. ML pays off when you have a decision that is hard to write as rules, you have (or can collect) data that records the right answer, a wrong answer has a tolerable cost, and the pattern is stable enough to learn. Ask four things.

  1. Do simple rules solve it well enough? A heuristic baseline ships quickly, is easy to explain and sets the bar a model must beat. The Rules of ML make the same point: if ML is not absolutely required, do not use it until you have data (Rules of ML).
  2. Is there a label or a feedback signal? Without one you can only do unsupervised work or collect data first.
  3. What does an error cost? If a wrong answer is unacceptable without human review, design the review into the system rather than hoping for accuracy.
  4. Is explainability required? A regulated decision may need a model you can justify, which limits the choices.

The trade-off: a heuristic is cheap and brittle, a model is more accurate and costs data, infrastructure and maintenance for the life of the product. Say that, then say what you would do first: ship the rule baseline and collect labels while it runs (common practice).

Objective, metric and constraints

A business goal (“more orders”, “fewer fraud losses”) is not yet something a model can optimise. Three layers need to be separated.

LayerExample for a food-delivery feedWhy it matters
Business goalMore orders per session without hurting delivery timesWhy the system exists
Training objectivePredict the probability that this user orders from this restaurantWhat the model optimises (a loss)
MetricsOffline: recall@k and NDCG@k. Online: order rate with guardrails on delivery ETA and cancellationsHow you decide it worked

The gap between layers is where designs fail. A model that optimises clicks can raise clicks and lower orders. A model that optimises today’s order can starve new restaurants, and the loss shows up months later. Name one guardrail metric for every primary metric: a number you will not allow to get worse, such as latency, cancellation rate or complaints.

Then state constraints before architecture, because they pick the architecture: users and scale, latency budget, freshness of data, cost per request, privacy, and what happens when the system is down. A good opening is to ask for these, then write your assumptions on the board.

The design framework

The same nine steps fit almost every prompt. The times below are a suggested split for a 35-minute round (a convention from interview preparation, not a rule).

StepMinutesWhat to say
1. Clarify and frame4Users, goal, scale, latency, constraints. Business metric to ML metric. Is ML needed?
2. Data and labels4Sources, volume, label definition, delay and noise, privacy, bias
3. Baseline2A rule or logistic regression, to set the bar
4. Features4User, item, context, aggregates; batch against real-time; freshness
5. Model5Candidates, justified by latency, data size and interpretability
6. Offline evaluation3Metrics, time or group split, error analysis, calibration
7. Serving5Batch or online, latency budget, caching, fallbacks, cost
8. Online evaluation and rollout3A/B, guardrails, shadow and canary
9. Monitoring and risks5Drift, feedback loops, retraining, fairness, abuse
Diagram: Nine steps in order, from framing to monitoring, with a dotted arrow back to framing because monitoring findings change the goal or the...

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 in order, from framing to monitoring, with a dotted arrow back to framing because monitoring findings change the goal or the data. Spend the most time where the prompt is hardest, not equally on every step.

Three habits make the framework land. Say the trade-off (“the cost of this is…”). Start with a baseline before a complicated model. Name the failure mode before the interviewer does (“the risk here is label delay”). Structure beats cleverness: jumping straight to a transformer is the most common way to lose this round (common industry pattern).

Inference modes

The first serving question is when the prediction is computed. It decides your latency budget, your infrastructure and your cost.

ModeWhen it runsGood forCosts
BatchOn a schedule (nightly) for every entityEmail recommendations, churn lists, scores that change slowlyStale between runs; wasted work for entities nobody asks about
OnlineAt request time, one request at a timeSearch, feeds, fraud checks at paymentA hard latency budget; the whole feature path must be fast
StreamingContinuously, as events arriveRolling aggregates, near-real-time alertsThe most moving parts: state, ordering, late events
Diagram: Batch precomputes scores and serves them from a table.

Streaming

Event stream

Update aggregates

Online store

Online model reads fresh features

Online

Request

Fetch features

Model

Response

Batch

Nightly job scores everyone

Score table

Request reads a stored score

Diagram summary: Batch precomputes scores and serves them from a table. Online computes at request time. Streaming keeps features fresh by updating aggregates as events arrive, and an online model then reads them.

Most real systems mix modes: embeddings and slow user profiles computed in batch, fast aggregates (a card’s transactions in the last hour) kept fresh by streaming, and the final scoring online. Choose the slowest mode the product can tolerate, because every step toward real time adds cost and failure modes (common practice). Freshness is a requirement to ask about: the Rules of ML suggest asking how much performance drops if the model is a day old (Rules of ML).

Budgets and capacity

A design without numbers is a drawing. Back-of-envelope capacity means a few lines of arithmetic with assumptions you state, so the interviewer can see the order of magnitude and correct you. All figures in this section come from the script in the Code section and are assumptions, not data about any real company.

Worked example: a feed for 5 million daily users. Assume 4 sessions per user per day and one feed request per session. That is 20,000,000 requests a day, or 231.48 requests per second on average. Traffic is bursty, so assume the peak is three times the average: 694.44 requests per second.

To size servers, use Little’s law, a standard queueing result (common practice): the number of requests in flight equals the arrival rate times the time each spends in the system. The sizing below assumes little queueing at this load, which is why it also keeps servers well below full utilisation.

L=λWL=\lambda W

SymbolMeaning
LLAverage number of requests in flight
λ\lambdaArrival rate, requests per second
WWAverage time one request spends in the system, in seconds

At 694.44 requests per second and an assumed 0.060 s of service time, about 41.7 requests are in flight. If one server handles 8 at a time and you keep it at 50% of that for headroom, each server carries 4, so you need ⌈41.7/4⌉=11\lceil 41.7/4\rceil = 11 servers. At an assumed price of $0.40 per server-hour, that is $105.60 a day, or $5.28 per million requests.

Each assumption is a lever. Halving the service time halves the servers, a lower target utilisation buys headroom for bursts and slow requests at a price, and the peak factor is the number most worth asking about. Memory is the other budget: 200,000 restaurants as 64-dimension float32 embeddings take 51.2 MB, but 100,000,000 items with 128 dimensions take 51.2 GB, which no longer fits in one machine’s fast memory and changes the design.

Latency is a distribution

A latency budget is the time the whole request path may take, split across its steps. Two rules make it honest.

Add serial steps, take the maximum of parallel ones. A path of a 5 ms lookup, then a 10 ms and a 40 ms feature fetch costs 55 ms in series and 45 ms if the two fetches run in parallel.

Budget percentiles, not means. In the script, 20,000 simulated requests with a median of 40.1 ms have a mean of 45.2 ms, a p95 of 91.5 ms, a p99 of 126.2 ms and a slowest request of 277.5 ms. The p99 is the value 99% of requests beat. This lesson computes it with the nearest-rank rule: sort the nn values and take the one at rank ⌈p n/100⌉\lceil p\,n/100\rceil (other definitions interpolate and differ slightly). Percentiles do not average: take one server whose 100 requests include 99 at 10 ms and one at 100 ms (p99 10 ms), and another whose 100 include 90 at 10 ms and 10 at 200 ms (p99 200 ms). The mean of the two p99s is 105 ms, but the 200 pooled requests have 189 at 10 ms, one at 100 ms and ten at 200 ms, so the nearest-rank p99 (rank 198) is 200 ms (derived here, two tiny servers by hand). That is a different problem from the sampling noise described below: even one server’s p99 is a noisy estimate if the window is small, so compute it from all requests pooled over one large window and never from an average of per-server figures (derived here).

Tails matter more as systems grow. A request that calls many services waits for the slowest. The paper “The Tail at Scale” argues that brief slowdowns harmless in a small system can dominate performance at scale, and that the whole should be built to tolerate them (Dean and Barroso, 2013). If each call is slower than its p99 one time in a hundred, a request that fans out to 10 independent calls hits at least one such call with probability 1−0.9910=0.09561-0.99^{10}=0.0956 (derived here). The simulation gave 0.1030, which is more than sampling noise explains. The reason is that the p99 used as the threshold (126.2 ms) was estimated from 20,000 draws and is really the true 98.92nd percentile of the simulated distribution, so each call exceeds it with probability 0.01077 and 1−0.9892310=0.10271-0.98923^{10}=0.1027 (script, section 2). Estimating a tail percentile from a sample is itself noisy, which is one more reason to measure p99 over a large window.

The standard defence is a timeout with a fallback: stop waiting at a threshold and return a cheaper answer. With a 100 ms timeout and a 5 ms fallback in the script, 3.20% of requests fall back and the slowest served request is 105.0 ms, instead of 277.5 ms. The price is quality on those requests, which is why the fallback rate is itself a metric to watch.

Two-stage retrieval and ranking

Why not score every item with your best model? Because the best model is expensive and the catalogue is large. With 20,000 items and a ranker that costs a little per item, scoring everything for every request is wasteful. With 100 million items it is impossible inside a latency budget. The answer is a funnel: a cheap stage keeps a few hundred candidates out of millions, and an expensive stage orders only those. The YouTube recommendation paper describes its system as the classic two-stage split of a deep candidate generation model and a separate deep ranking model (Covington et al., 2016).

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

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 passes through candidate generation, a ranker and a re-ranker, shrinking from millions of items to a short list. What users do with the list is logged and used to train both models.
StageJobTypical tools (common practice)Optimise for
Candidate generationFind items that might be goodTwo-tower embeddings with an approximate nearest-neighbour index, popular and recent items, keyword search (BM25)Recall: do not lose the good items
RankerOrder the candidates by predicted valueGradient-boosted trees or a deep model with rich user, item and context featuresPrecision at the top
Re-rankerApply what the score cannotDiversity, business rules, fairness for new items, exploration slotsWhole-list quality and policy

Approximate nearest-neighbour search is what makes embedding retrieval fast. One widely used method, HNSW, builds layers of proximity graphs and searches from sparse layers down, and its authors report logarithmic scaling (Malkov and Yashunin, 2016). The trade-off is approximation: the index may miss a true neighbour, so retrieval recall is measured, not assumed.

Measuring each stage

Each stage has its own metric because it has its own job.

Recall@k asks how many of the relevant items the first kk results contain. It is the right metric for candidate generation, because an item the retriever drops can never be shown.

recall@k=∣top-k∩relevant∣∣relevant∣\mathrm{recall@}k=\frac{|\text{top-}k\cap\text{relevant}|}{|\text{relevant}|}

NDCG@k is the right metric for the ranker because it rewards putting the most relevant items first. With gain gig_i at rank ii:

DCG@k=∑i=1kgilog⁡2(i+1),NDCG@k=DCG@kIDCG@k\mathrm{DCG@}k=\sum_{i=1}^{k}\frac{g_i}{\log_2(i+1)},\qquad \mathrm{NDCG@}k=\frac{\mathrm{DCG@}k}{\mathrm{IDCG@}k}

SymbolMeaning
gig_iGraded relevance (gain) of the item at rank ii
log⁡2(i+1)\log_2(i+1)The discount: lower ranks count for less
IDCG@k\mathrm{IDCG@}kDCG of the best possible ordering, so a perfect list scores 1

By hand, with gains 1 for item A and 3 for item B, the order (A, B) gives DCG=1+3/log⁡23=2.893\mathrm{DCG}=1+3/\log_2 3=2.893 and the ideal order (B, A) gives 3+1/log⁡23=3.6313+1/\log_2 3=3.631, so NDCG=0.797\mathrm{NDCG}=0.797. scikit-learn’s ndcg_score applies a logarithmic discount, divides by the ideal score, and by default averages tied predictions; the homework version uses the formula above and does not handle ties specially (scikit-learn, ndcg_score).

The two stages trade off. The script builds a synthetic catalogue of 20,000 items per user with 20 relevant items, a cheap noisy retriever score and a more accurate ranker score (both assumed for the exercise). The retriever alone reaches NDCG@10 of 0.214.

Candidates passed onRetriever recall at that sizeFinal NDCG@10Ranker calls per request
500.1650.47250
2000.2840.654200
5000.3950.772500
2,0000.6130.9032,000
All 20,000 (no retrieval)1.0000.94420,000

Read it as a cost curve. The final quality is capped by retrieval recall, because the ranker cannot promote an item it never sees, so a better ranker does not rescue a weak retriever. Passing more candidates raises quality and raises ranker cost and latency in proportion. The design question is where on this curve the latency budget lets you sit.

Four designs

Use the same skeleton for every prompt and change the emphasis. These are overview-level sketches. The latency figures are assumptions you would state, not facts about any product.

Recommender feed

Funnel as above. Candidate sources: two-tower retrieval, popular nearby, recent and reorder history; filter by availability first. The ranker predicts the probability of the target action, often with several heads (click, order). Three issues to raise unprompted.

  • Cold start. New users get popularity, location and onboarding answers; new items get content features and exploration slots (common practice).
  • Position bias. Top slots get clicks regardless of quality, so raw click logs mislead. Position bias in click data strongly influences how many clicks a result gets, and the Joachims et al. paper corrects for it by weighting examples with estimated propensities (Joachims et al., 2016). Rule 36 of the Rules of ML recommends adding positional features so the model learns the effect of position, and giving every candidate the same default value (or omitting the feature) at serving time (Rules of ML).
  • Feedback loops. What you show decides what you learn. The monitoring section returns to this.

Query understanding (spelling, intent, rewriting), then hybrid retrieval (keyword and embedding), a light ranker and a heavier learning-to-rank model on the survivors (common practice). Metrics: NDCG@k and MRR offline, click-based online metrics with the same position-bias caution (common practice).

Fraud

Diagram: A transaction gets features, then a rules layer and a model score feed one decision with three outcomes: approve, step-up or review,...

low risk

middle

high risk

Transaction

Feature service
velocity, device, history

Rules layer

Model score

Decision

Approve

Step-up check or review queue

Decline

Labels arrive later

Diagram summary: A transaction gets features, then a rules layer and a model score feed one decision with three outcomes: approve, step-up or review, decline. Confirmed outcomes come back much later.

Fraud adds three problems. Extreme imbalance (see the evaluation lesson). Delayed and selective labels: a chargeback arrives weeks later, and a declined transaction produces no outcome at all, so keep a small random holdout of approvals that bypasses the model to measure what you would otherwise never see (common practice). Adversaries who adapt, which is concept drift by design. The decision uses costs: if a missed fraud loses $80 and a wrongly declined customer costs $4 in friction, then with a calibrated probability pp you act when the expected loss of approving exceeds the expected cost of declining.

p⋅L>(1−p)⋅F  ⇒  p>FF+L=484=0.0476p\cdot L>(1-p)\cdot F\;\Rightarrow\;p>\frac{F}{F+L}=\frac{4}{84}=0.0476

Here LL is the loss from a missed fraud and FF the friction cost of a false alarm (derived here, with these assumed costs). The threshold only works when scores are calibrated, which is one reason to check calibration before launch (the calibration section). A fail-open or fail-closed policy for outages must be an explicit decision, because “the model is down” is a normal event (common practice).

Ads click prediction

Features: user, ad, context and crosses. Model: gradient boosting or a deep network. The predicted click probability feeds an auction, so calibration matters as much as ranking quality (common practice): expected value per impression is pCTR×bid\mathrm{pCTR}\times\mathrm{bid}. At a pCTR of 0.02 and a bid of $1.50 that is $0.03; a model that overstates pCTR by 2x makes it $0.06 and the system overbids by that factor (assumed numbers). Conversions are delayed and new ads need exploration (common practice).

Features and consistency

The previous module’s training-serving skew section explained the failure: two code paths compute the same feature differently. Here is the system-level cure.

  • One feature definition used by both training and serving. Google’s rule is to re-use code between training and serving whenever possible, and to save the features used at serving time (Rules of ML).
  • A feature store gives that definition a home. In Feast, a feature view must have a data source, which is used both to generate training datasets and to materialise feature values into the online store (Feast). Training reads the offline side with point-in-time joins; serving reads the online side with low latency.
  • Log what you served. Training on the logged serving-time features is the most direct way to train like you serve.

The trade-off: a feature store adds a system to run and a schema to govern. For one model with a few features, a shared library and logged features may be enough (common practice). It earns its keep when many models share features and freshness matters.

Serving levers

When the model is too slow or too costly, pull these levers in roughly this order: cheapest and least risky first (common practice).

Cache

Many requests repeat. A cache returns a stored answer for a repeated key. With skewed (Zipf-like) traffic over 10,000 keys, an LRU cache holding only 1% of the keys (100) served 0.391 of 200,000 requests, and holding 10% served 0.675 (script, section 5). The trade-offs: cached answers go stale, personalised results cache poorly, and hit rate depends entirely on how skewed your traffic is, which you must measure rather than assume.

Batching

Accelerators and vectorised code have a fixed cost per call, so grouping requests raises throughput and adds latency. With an assumed 8 ms fixed cost and 0.5 ms per item, a batch of 1 takes 8.5 ms (117.6 items per second), a batch of 16 takes 16.0 ms (1000.0 per second) and a batch of 64 takes 40.0 ms (1600.0 per second). Under a 20 ms latency cap the best batch is 24, at 1200.0 items per second. The script ignores the time a request waits for a batch to fill, which is a real extra latency in practice.

Quantisation

Quantisation stores numbers in fewer bits (common practice). Moving 100 million parameters from 32-bit floats to 8-bit integers cuts memory from 400 MB to 100 MB (arithmetic in the script). The integer-arithmetic paper proposes a quantisation scheme for inference that uses integer-only arithmetic, together with a training procedure that keeps end-to-end accuracy close to the original model (Jacob et al., 2017). The cost is some accuracy, so you re-run your offline evaluation on the quantised model before you ship it.

Distillation

Distillation trains a model to imitate a larger one. Hinton and colleagues show how to compress the knowledge of an ensemble into a single model that is easier to deploy (Hinton et al., 2015). In practice the student is usually smaller and faster than the teacher (common practice). You pay for training twice and accept some quality loss in return for latency and cost.

Other levers: precompute heavy features, shrink the candidate list (see the table above), run feature fetches in parallel, and set timeouts with fallbacks.

Rollout

A model that wins offline can still lose online, because offline data is a recording of the past under the old system. Roll out in steps that each limit the damage and answer one question.

Diagram: The ladder runs from offline evaluation to shadow mode, a canary, an A/B test and a ramp, with rollback available from the canary and the...

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: The ladder runs from offline evaluation to shadow mode, a canary, an A/B test and a ramp, with rollback available from the canary and the A/B stages whenever a guardrail is breached.
StepQuestion it answersWhat users see
ShadowDoes it run, at what latency, and do its scores look sane?Nothing: the old model still decides
CanaryDoes it break anything at small scale?The new model, for a small share
A/B testIs it actually better on the primary metric, without breaking guardrails?A randomised split
Ramp and monitorDoes it hold up at full traffic?The new model for everyone

The statistics of the A/B step (randomisation unit, sample size, sample ratio mismatch, peeking, offline and online metrics disagreeing) are in the experiments section of the statistics lesson, and the book on online controlled experiments covers the practice. Always keep the previous model deployable so rollback is a switch, not a rebuild.

Monitoring and feedback loops

After launch, watch four layers, cheapest first (the same layers as the drift section of the previous module): data quality, feature drift, score drift, and performance once labels mature. Add the system’s own health: latency percentiles, error and timeout rates, and the fallback rate. A rising fallback rate means users are quietly getting a worse product while accuracy dashboards look fine.

Feedback loops are the monitoring problem specific to ML. The model’s output changes what users see, which changes the data the next model learns from. A toy example from the script: ten items, nine with a true click rate of 0.10 and item 7 with 0.15. A policy that always shows the item with the best observed click rate locks onto the first item to get a lucky click. Over 100 runs of 3,000 impressions, item 7 was the most shown in only 14 runs, the most shown item received 0.998 of all impressions, and about 9 of the 10 items stayed under 30 impressions. A policy that explores at random 10% of the time found item 7 in 55 of 100 runs and gave the most shown item 0.670 of the impressions. The toy is deliberately crude, but the mechanism is the one the technical-debt paper calls a hidden feedback loop.

Remedies, each with a cost (common practice): keep a small exploration or random holdout slice (costs some short-term quality), log propensities so you can correct for exposure, and evaluate on data collected without the model’s influence.

Fallbacks and humans in the loop

Plan for the model being slow, wrong or absent.

  • Fallback ladder. Full model, then a cheaper model, then a cached or popular default, then a rule. Decide the order in advance, make each step fast, and alert when the system is below the top rung.
  • Timeouts. Every remote call has one, shorter than the slice of the latency budget it gets.
  • Fail-open or fail-closed. For a safety or fraud check, decide explicitly whether a failure approves or blocks.
  • Human in the loop. Use review for the uncertain middle band, for high-cost errors, and as a source of labels. The limit is capacity: reviewers can handle only so many items per day, which sets the width of the middle band. In a clinical alert system the equivalent limit is alert fatigue, so you also cap alerts per patient per day (common practice).

Technical debt

ML systems can carry large maintenance costs: the paper’s abstract says it is common to incur massive ongoing maintenance costs in real-world ML systems. It lists the ML-specific risk factors from its abstract: boundary erosion, entanglement, hidden feedback loops, undeclared consumers, data dependencies, configuration issues, changes in the external world and system-level anti-patterns (Sculley et al., 2015). Those terms are the paper’s; the examples and defences in the table, including glue code and untested pipelines, are common practice and are not claimed from the paper.

DebtWhat it looks likeCheap defence
EntanglementChanging one feature shifts the behaviour of the othersPer-feature ablations, feature ownership
Undeclared consumersAnother team starts reading your scores, so you cannot change them safelyVersioned outputs, access control, a registry of consumers
Data dependenciesAn upstream table changes its meaningSchema checks, data contracts, monitoring
Hidden feedback loopsModel changes its own training dataExploration slice, holdout, logging
Configuration debtThresholds and flags that nobody can reproduceConfig in version control, reviewed
Glue code and untested pipelinesA model wrapped in scripts nobody ownsShared library, tests for the pipeline and not only the model

The practical rule: every part you add needs an owner, a test and a monitor. If you cannot say who gets paged when it breaks, it is debt.

Code

This standard-library script produced every number in the lesson that is computed here. The first part is the helper code from homework/solution.py (without docstrings); the rest is the experiments. It has fixed seeds and runs in about 2 seconds (Python 3.14.6, run with python3 -I). Another Python version may draw different random numbers, which moves the simulated figures (latency, funnel, cache and feedback-loop results) slightly but not their pattern. The closed-form numbers (capacity, batching, the cost threshold, the NDCG example) do not depend on the version.

Python

import math
from collections import OrderedDict


def percentile(values, p):
    if len(values) == 0:
        raise ValueError("percentile of an empty list")
    if not 0 < p <= 100:
        raise ValueError("p must satisfy 0 < p <= 100")
    s = sorted(values)
    rank = max(1, math.ceil(p / 100 * len(s) - 1e-9))
    return s[rank - 1]


def servers_needed(qps, latency_s, concurrency, target_util):
    if qps < 0 or latency_s < 0 or concurrency < 1 or not 0 < target_util <= 1:
        raise ValueError("bad capacity inputs")
    if qps == 0:
        return 0
    in_flight = qps * latency_s
    return max(1, math.ceil(in_flight / (concurrency * target_util) - 1e-9))


def path_latency(stages):
    total = 0.0
    for st in stages:
        group = st if isinstance(st, (list, tuple)) else [st]
        if any(g < 0 for g in group):
            raise ValueError("negative latency")
        total += max(group) if len(group) else 0.0
    return total


def cost_per_million_requests(servers, price_per_hour, qps):
    if qps <= 0 or servers < 0 or price_per_hour < 0:
        raise ValueError("bad cost inputs")
    return servers * price_per_hour / (qps * 3600) * 1_000_000


def recall_at_k(ranked, relevant, k):
    if k < 1:
        raise ValueError("k must be at least 1")
    rel = set(relevant)
    if not rel:
        return 0.0
    return len(set(ranked[:k]) & rel) / len(rel)


def ndcg_at_k(ranked, gains, k):
    if k < 1:
        raise ValueError("k must be at least 1")
    seen = set()
    dcg = 0.0
    for i, item in enumerate(ranked[:k]):
        if item in seen:
            continue
        seen.add(item)
        dcg += gains.get(item, 0) / math.log2(i + 2)
    ideal_gains = sorted(gains.values(), reverse=True)[:k]
    ideal = sum(g / math.log2(i + 2) for i, g in enumerate(ideal_gains))
    return dcg / ideal if ideal > 0 else 0.0


def two_stage(retrieved, scores, n_candidates, k):
    if n_candidates < 1 or k < 1:
        raise ValueError("n_candidates and k must be at least 1")
    cands = retrieved[:n_candidates]
    order = sorted(range(len(cands)), key=lambda i: (-scores[cands[i]], i))
    return [cands[i] for i in order[:k]]


def lru_hit_rate(requests, capacity):
    if capacity < 0:
        raise ValueError("capacity must not be negative")
    if len(requests) == 0 or capacity == 0:
        return 0.0
    cache = OrderedDict()
    hits = 0
    for key in requests:
        if key in cache:
            hits += 1
            cache.move_to_end(key)
        else:
            cache[key] = True
            if len(cache) > capacity:
                cache.popitem(last=False)
    return hits / len(requests)


def batch_stats(batch_size, fixed_ms, per_item_ms):
    if batch_size < 1 or fixed_ms < 0 or per_item_ms < 0:
        raise ValueError("bad batch inputs")
    latency = fixed_ms + per_item_ms * batch_size
    if latency <= 0:
        raise ValueError("latency must be positive")
    return latency, batch_size / latency * 1000


def best_batch_size(max_batch, fixed_ms, per_item_ms, latency_cap_ms):
    if max_batch < 1:
        raise ValueError("max_batch must be at least 1")
    best = 0
    for b in range(1, max_batch + 1):
        latency, _ = batch_stats(b, fixed_ms, per_item_ms)
        if latency <= latency_cap_ms + 1e-9:
            best = b
    return best


def timeout_fallback(latencies, timeout_ms, fallback_ms):
    if timeout_ms < 0 or fallback_ms < 0 or any(x < 0 for x in latencies):
        raise ValueError("negative latency")
    if len(latencies) == 0:
        return [], 0.0
    served, used = [], 0
    for x in latencies:
        if x <= timeout_ms:
            served.append(x)
        else:
            served.append(timeout_ms + fallback_ms)
            used += 1
    return served, used / len(latencies)


import math
import random
from statistics import NormalDist

print("== 1. Capacity: a feed for 5M daily users")
dau, sessions = 5_000_000, 4
per_day = dau * sessions
avg_qps = per_day / 86_400
peak_qps = avg_qps * 3
servers = servers_needed(peak_qps, 0.060, 8, 0.5)
print(f"requests per day {per_day:,}  average qps {avg_qps:.2f}  peak qps {peak_qps:.2f}")
print(f"in flight at peak {peak_qps * 0.060:.1f}  servers {servers}")
print(f"dollars per million requests at $0.40 per server-hour {cost_per_million_requests(servers, 0.40, avg_qps):.2f}")
print(f"daily server cost ${servers * 0.40 * 24:.2f}")
print(f"item embeddings, 200,000 x 64 floats of 4 bytes: {200_000 * 64 * 4 / 1e6:.1f} MB")
print(f"item embeddings, 100,000,000 x 128 floats of 4 bytes: {100_000_000 * 128 * 4 / 1e9:.1f} GB")
print(f"100M parameters: fp32 {100e6 * 4 / 1e6:.0f} MB, int8 {100e6 * 1 / 1e6:.0f} MB")

print("\n== 2. Latency: the mean hides the tail")
rng = random.Random(7)
lat = [rng.lognormvariate(math.log(40), 0.5) for _ in range(20_000)]
p50, p95, p99 = (percentile(lat, p) for p in (50, 95, 99))
print(f"mean {sum(lat) / len(lat):.1f} ms  p50 {p50:.1f}  p95 {p95:.1f}  p99 {p99:.1f}  max {max(lat):.1f}")
print(f"serial path 5 + 10 + 40 ms: {path_latency([5, 10, 40])}  with the two fetches in parallel: {path_latency([5, [10, 40]])}")
fan = 10
slow = sum(1 for _ in range(20_000) if max(rng.lognormvariate(math.log(40), 0.5) for _ in range(fan)) > p99)
print(f"fan-out {fan}: share of requests with at least one call above the single-call p99: {slow / 20_000:.4f} (formula {1 - 0.99 ** fan:.4f})")
nd = NormalDist()
q_est = nd.cdf((math.log(p99) - math.log(40)) / 0.5)
print(f"the estimated p99 {p99:.1f} ms is the true {q_est * 100:.2f}th percentile, so one call exceeds it with probability {1 - q_est:.5f}")
print(f"fan-out {fan} with that probability: {1 - q_est ** fan:.4f}")
served, rate = timeout_fallback(lat, 100.0, 5.0)
print(f"timeout 100 ms, fallback 5 ms: fallback rate {rate:.4f}  p99 served {percentile(served, 99):.1f}  max served {max(served):.1f}")

print("\n== 3. Batching: throughput against latency")
for b in (1, 8, 16, 64):
    l, t = batch_stats(b, 8, 0.5)
    print(f"batch {b:>2}: latency {l:5.1f} ms  throughput {t:7.1f} items/s")
bb = best_batch_size(256, 8, 0.5, 20)
print(f"largest batch within a 20 ms cap: {bb}  ({batch_stats(bb, 8, 0.5)[1]:.1f} items/s)")

print("\n== 4. Two stages: recall at the retriever, NDCG at the ranker")
N, USERS, REL = 20_000, 150, 20
sums = {}
ranker_all = []
retr_only = []
for u in range(USERS):
    r = random.Random(1000 + u)
    gain = {}
    for item in r.sample(range(N), REL):
        gain[item] = r.choice([1, 2, 3])
    cheap = [gain.get(i, 0) + r.gauss(0, 1.2) for i in range(N)]
    exact = {i: gain.get(i, 0) + r.gauss(0, 0.5) for i in range(N)}
    retrieved = sorted(range(N), key=lambda i: -cheap[i])
    retr_only.append(ndcg_at_k(retrieved, gain, 10))
    ranker_all.append(ndcg_at_k(sorted(range(N), key=lambda i: -exact[i]), gain, 10))
    for n in (50, 200, 500, 2000):
        final = two_stage(retrieved, exact, n, 10)
        a = sums.setdefault(n, [0.0, 0.0])
        a[0] += recall_at_k(retrieved, list(gain), n)
        a[1] += ndcg_at_k(final, gain, 10)
print(f"retriever alone, NDCG@10: {sum(retr_only) / USERS:.3f}")
for n, (rc, nd) in sums.items():
    print(f"candidates {n:>4}: recall@{n} {rc / USERS:.3f}  final NDCG@10 {nd / USERS:.3f}  ranker calls per request {n}")
print(f"ranker on all {N:,} items, NDCG@10: {sum(ranker_all) / USERS:.3f}  ranker calls per request {N}")

print("\n== 5. Cache: Zipf traffic and an LRU cache")
rng = random.Random(11)
keys = 10_000
w = [1 / (r + 1) for r in range(keys)]
reqs = rng.choices(range(keys), weights=w, k=200_000)
for cap in (10, 100, 1000):
    print(f"capacity {cap:>4} ({cap / keys:.1%} of keys): hit rate {lru_hit_rate(reqs, cap):.3f}")

print("\n== 6. Decisions from calibrated scores")
loss, friction = 80.0, 4.0
print(f"decline when p > friction / (friction + loss) = {friction / (friction + loss):.4f}")
print(f"expected value per impression at pCTR 0.02 and bid $1.50: ${0.02 * 1.50:.2f}; if pCTR is overstated 2x: ${0.04 * 1.50:.2f}")

print("\n== 7. A toy feedback loop")
CTR = [0.10] * 10
CTR[7] = 0.15
def run(seed, eps, rounds=3000):
    r = random.Random(seed)
    shows, clicks = [0] * 10, [0] * 10
    for _ in range(rounds):
        if r.random() < eps:
            i = r.randrange(10)
        else:
            est = [clicks[j] / shows[j] if shows[j] else 0.0 for j in range(10)]
            best = max(est)
            i = r.choice([j for j in range(10) if est[j] == best])
        shows[i] += 1
        clicks[i] += r.random() < CTR[i]
    return shows
for eps in (0.0, 0.1):
    top7 = never = 0
    share = 0.0
    for seed in range(100):
        s = run(seed, eps)
        top7 += s.index(max(s)) == 7
        share += max(s) / sum(s)
        never += sum(1 for x in s if x < 30)
    print(f"epsilon {eps}: item 7 most shown in {top7} of 100 runs, mean share of the most shown item {share / 100:.3f}, items with under 30 impressions per run {never / 100:.2f}")

What to look for: section 1 (the capacity arithmetic and where each assumption enters), section 2 (mean against percentiles, the fan-out effect with its explanation, and the timeout), section 3 (batching), section 4 (recall of the retriever caps the final quality; cost grows with candidates), section 5 (hit rate against cache size), section 6 (the decision threshold), section 7 (the feedback loop with and without exploration).

Output of the script as run for this lesson:

== 1. Capacity: a feed for 5M daily users
requests per day 20,000,000  average qps 231.48  peak qps 694.44
in flight at peak 41.7  servers 11
dollars per million requests at $0.40 per server-hour 5.28
daily server cost $105.60
item embeddings, 200,000 x 64 floats of 4 bytes: 51.2 MB
item embeddings, 100,000,000 x 128 floats of 4 bytes: 51.2 GB
100M parameters: fp32 400 MB, int8 100 MB

== 2. Latency: the mean hides the tail
mean 45.2 ms  p50 40.1  p95 91.5  p99 126.2  max 277.5
serial path 5 + 10 + 40 ms: 55.0  with the two fetches in parallel: 45.0
fan-out 10: share of requests with at least one call above the single-call p99: 0.1030 (formula 0.0956)
the estimated p99 126.2 ms is the true 98.92th percentile, so one call exceeds it with probability 0.01077
fan-out 10 with that probability: 0.1027
timeout 100 ms, fallback 5 ms: fallback rate 0.0320  p99 served 105.0  max served 105.0

== 3. Batching: throughput against latency
batch  1: latency   8.5 ms  throughput   117.6 items/s
batch  8: latency  12.0 ms  throughput   666.7 items/s
batch 16: latency  16.0 ms  throughput  1000.0 items/s
batch 64: latency  40.0 ms  throughput  1600.0 items/s
largest batch within a 20 ms cap: 24  (1200.0 items/s)

== 4. Two stages: recall at the retriever, NDCG at the ranker
retriever alone, NDCG@10: 0.214
candidates   50: recall@50 0.165  final NDCG@10 0.472  ranker calls per request 50
candidates  200: recall@200 0.284  final NDCG@10 0.654  ranker calls per request 200
candidates  500: recall@500 0.395  final NDCG@10 0.772  ranker calls per request 500
candidates 2000: recall@2000 0.613  final NDCG@10 0.903  ranker calls per request 2000
ranker on all 20,000 items, NDCG@10: 0.944  ranker calls per request 20000

== 5. Cache: Zipf traffic and an LRU cache
capacity   10 (0.1% of keys): hit rate 0.131
capacity  100 (1.0% of keys): hit rate 0.391
capacity 1000 (10.0% of keys): hit rate 0.675

== 6. Decisions from calibrated scores
decline when p > friction / (friction + loss) = 0.0476
expected value per impression at pCTR 0.02 and bid $1.50: $0.03; if pCTR is overstated 2x: $0.06

== 7. A toy feedback loop
epsilon 0.0: item 7 most shown in 14 of 100 runs, mean share of the most shown item 0.998, items with under 30 impressions per run 9.00
epsilon 0.1: item 7 most shown in 55 of 100 runs, mean share of the most shown item 0.670, items with under 30 impressions per run 1.68

Real-World Application

A sound recipe for an interview or a real design: write the goal, the metric and a guardrail, and ask for scale and latency. State the assumptions and do the capacity arithmetic. Ship the rule baseline first. Choose the slowest inference mode the product allows, and split the model into retrieval, ranking and re-ranking only if the catalogue is too large to score directly. Share one feature definition between training and serving and log what you served. Apply serving levers cheapest first, check quality after each. Roll out through shadow, canary and A/B with a rollback ready. Monitor data, features, scores, performance and the fallback rate, keep an exploration slice, and name who owns each part.

Interview Perspective

Expect “design a recommender for an e-commerce site”, “design a fraud detection system”, “how would you serve this model with a 50 ms budget”, “when would you not use ML”, “how do you handle position bias”, and “how do you roll out a new model”. A strong answer asks clarifying questions, states assumptions with numbers, draws the funnel, names trade-offs and failure modes unprompted, and ends with monitoring. A weak answer names a model and stops.

Provenance: Common industry pattern. These are standard ML system design topics for applied ML roles, not a verified list for any named company.

Practice Questions

  • Basic (Common industry pattern): When would you refuse to use ML for a problem, and what would you ship instead?
  • Basic (Common industry pattern): What is the difference between an objective and a metric? Give a guardrail for a feed ranking model.
  • Intermediate (Common industry pattern): Why do recommenders use a candidate generation stage before the ranker, and how do you measure each stage?
  • Intermediate (Generated practice): A service gets 400 requests per second at peak, each takes 50 ms, one server handles 4 at once, and you target 50% utilisation. How many servers? Say what you would change if the p99 were four times the median.
  • Intermediate (Common industry pattern): Your latency budget is 50 ms. List the levers you would pull, cheapest first.
  • Advanced (Common industry pattern): Design a real-time fraud system. Cover labels, features, the decision, the fallback policy and how you keep an unbiased holdout.
  • Advanced (Generated practice): Your ranking model improved NDCG offline and lowered orders in the A/B test. List three explanations and how you would tell them apart.
  • Product-Company (Generated practice): Design a search system for an e-commerce site with 50 million products. State your assumptions, draw the stages and name the metric for each.

Activity

Run the script, then change four things. In section 1, change the peak factor from 3 to 5 and the target utilisation from 0.5 to 0.7, and find the new server count and cost per million requests. In section 4, change the retriever noise from 1.2 to 2.0 and watch the recall column and the final NDCG@10. In section 5, change the Zipf weights from 1/rank to 1/rank^0.5 (flatter traffic) and compare the hit rates. In section 7, change the exploration rate to 0.3 and describe what you gain and what it costs. Then write the one-paragraph rollout plan you would send for a new ranking model, naming the guardrail metrics.

Homework

Build the system-design toolkit with the standard library only: nearest-rank percentile, Little’s-law server count, the latency of a path with parallel calls, cost per million requests, recall@k and NDCG@k, a two-stage ranker, an LRU hit-rate simulator, batch latency and throughput, the best batch under a latency cap, and a timeout-with-fallback applier. The code is in homework/; run the tests until they pass.

Quick Revision

  • Ask first whether ML is needed. Separate the business goal, the training objective and the metric, and name a guardrail. Constraints (scale, latency, freshness, cost, privacy) choose the architecture.
  • The framework: frame, data and labels, baseline, features, model, offline evaluation, serving, online evaluation and rollout, monitoring and risks. Say trade-offs aloud and start with a baseline.
  • Batch, online or streaming: pick the slowest mode the product tolerates; real systems mix them.
  • Capacity: requests in flight L=λWL=\lambda W. 694.44 requests per second at 0.060 s is 41.7 in flight, 11 servers at 8 each and 50% load, $5.28 per million requests.
  • Budget percentiles: mean 45.2 ms but p99 126.2 ms. Serial steps add, parallel steps take the maximum. Ten parallel calls give 1−0.9910=0.09561-0.99^{10}=0.0956 of requests a p99-slow call. Use timeouts and fallbacks and watch the fallback rate.
  • Funnel: candidate generation (recall), ranker (NDCG), re-ranker (policy). Final quality is capped by retrieval recall (NDCG@10 0.472 at 50 candidates, 0.903 at 2,000) while ranker cost grows with candidates.
  • Fraud acts when p>F/(F+L)p>F/(F+L) (0.0476 with the example costs), needs calibrated scores, a random approval holdout and a fail-open or fail-closed rule. Ads need calibration because value is pCTR times bid.
  • One feature definition for training and serving, log served features, feature store when many models share features.
  • Serving levers cheapest first: cache (0.391 hit rate at 1% of keys), batching (throughput up, latency up), quantisation (400 MB to 100 MB), distillation.
  • Rollout: shadow, canary, A/B, ramp, with rollback. Monitor data, features, scores, performance and fallbacks. Feedback loops: explore (item 7 found in 55 of 100 runs against 14).
  • Debt: entanglement, undeclared consumers, data dependencies, feedback loops, configuration, glue code. Every part needs an owner, a test and a monitor.

Check yourself

  • Walk-through: Without notes, run the nine steps for “design a feed for a food-delivery app” in five minutes, including one capacity estimate with stated assumptions.
  • Variation: The same system, but the catalogue grows from 200,000 to 100 million items and the latency budget is cut in half. Say which parts change and why.
  • Common misconception: “A better ranker fixes poor candidates”, “average latency is the number to budget”, and “the A/B test only matters if offline metrics look good”.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Research papers

More for this module: ML systems and interviews resources

Practice

Test what you just read. Quizzes and cards are grouped by module: ML systems and interviews.

Check yourself18 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 18 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveDecide whether a problem needs ML, turn a business goal into an objective, a metric and constraints, and run the nine-step design framework out loud with trade-offs.

  1. Question 1 of 18A product team wants a model to route support emails to one of three queues. A three-line keyword rule already routes 88% of emails correctly, and nobody has labelled any past emails. What is the best first move in a design discussion?

    Choose one answer.

  2. Question 2 of 18A feed model is trained to maximise predicted clicks. After launch, clicks per session rise 6% but orders per session fall 2%. Which statement explains the problem and the fix?

    Choose one answer.

  3. Question 3 of 18Which statements about running the nine-step design framework in an interview are correct? Select all that apply.

    Choose all that apply.

ObjectiveChoose batch, online or streaming inference, and do back-of-envelope capacity, latency-budget and cost estimates with stated assumptions, using percentiles and not means.

  1. Question 4 of 18A card-payment fraud check must answer within the payment request. It uses the card's embedding (changes weekly) and the number of transactions on that card in the last 10 minutes. Which inference design fits?

    Choose one answer.

  2. Question 5 of 18At peak a service receives 600 requests per second. Each request takes 40 ms. One server handles 6 requests at once, and you plan to load servers to 60% of that. How many servers do you need?

    Choose one answer.

  3. Question 6 of 18A service has a mean latency of 45 ms and a p99 of 126 ms. The product requirement is that 99% of requests finish within 100 ms. What is the right conclusion?

    Choose one answer.

  4. Question 7 of 18Each backend call is slower than its own p99 one time in 100, independently. A page waits for 10 such calls made in parallel. About what share of pages see at least one call slower than that p99?

    Choose one answer.

ObjectiveExplain why large systems retrieve, rank and re-rank, measure each stage with recall@k and NDCG@k, and sketch recommender, search, fraud and ads designs at overview level.

  1. Question 8 of 18In a two-stage system the retriever puts only 28% of a user's relevant items among its 200 candidates. The team replaces the ranker with a much more accurate one. What should they expect?

    Choose one answer.

  2. Question 9 of 18A ranker returns items x, y, z in that order with gains 0, 2 and 3. The ideal order is z, y, x. Using gain divided by log2(rank + 1), what is NDCG@3?

    Choose one answer.

  3. Question 10 of 18Which statements about the four designs (recommender, search, fraud, ads) are correct? Select all that apply.

    Choose all that apply.

  4. Question 11 of 18In a payments flow, a missed fraud costs $45 and wrongly declining a good customer costs $5 in friction. With calibrated fraud probabilities, at what probability should you start declining?

    Choose one answer.

ObjectiveName the serving levers (batching, caching, quantisation, distillation), keep training and serving features consistent, and roll a model out by shadow, canary and A/B.

  1. Question 12 of 18A batch costs 10 ms fixed plus 0.4 ms per item. Requests may wait for a batch only if the batch itself finishes within 30 ms. Ignoring the time spent filling a batch, what is the largest allowed batch?

    Choose one answer.

  2. Question 13 of 18Offline AUC was 0.91, and in production the model is clearly worse. Feature code was written twice, once in SQL for training and once in the service. Which fix attacks the cause most directly?

    Choose one answer.

  3. Question 14 of 18A new ranking model must show it runs at the right latency and that its scores look sane, with no change visible to users. Which rollout step is for that?

    Choose one answer.

  4. Question 15 of 18Quantising a model to 8-bit integers makes it 4x smaller and faster on your hardware. What should you do before sending it to production?

    Choose one answer.

ObjectiveMonitor a live ML system, spot feedback loops, design fallbacks and human review, and name the main sources of ML technical debt.

  1. Question 16 of 18A dashboard shows model accuracy unchanged for a month, yet users complain that results got worse. Accuracy is computed on the requests the model answered. The fallback rate (requests served by the popular-items default) rose from 0.5% to 6%. What most likely happened?

    Choose one answer.

  2. Question 17 of 18A ranking model is retrained every week on clicks from items that the previous model chose to show. The same few items dominate more each week. Which change addresses the cause?

    Choose one answer.

  3. Question 18 of 18Which of these are sources of ML technical debt named in the hidden technical debt paper's abstract? Select all that apply.

    Choose all that apply.