ML System Design · Module 26 of 47 · 10 concepts · about 12 min

Design: A Recommendation System

A complete design for Kirana Kart's 'Top picks for you' row on the home screen, following the eight steps: requirements, framing, data, features, a retrieval-and-ranking architecture, serving at scale, evaluation, and monitoring, with the follow-up questions interviewers ask.

At work: The single most common ML system design interview question, in many variants: products, videos, music, friends, jobs, restaurants.

Requirements

What it is

Clarify first. For 'Top picks for you' on the home screen:

  • goal: more products added to baskets from the row, without hurting order value or satisfaction;
  • scale: 8,000,000 home-screen opens a day, about 278 a second at peak; 50,000 products per city, stock differs by store;
  • latency: the row must be ready within 100 ms (p99) of the request;
  • freshness: react to what the customer is doing in this session; new products recommendable within a day;
  • constraints: only in-stock items at the customer's store; no restricted items (alcohol, tobacco) where not allowed; at most one sponsored item.

Why it matters

Each requirement removes options.

  • 100 ms and 50,000 items rule out scoring everything with a heavy model: a two-stage design is needed.
  • Per-store stock means filtering must happen at request time or per store.
  • Session freshness means some features must be computed live.

In the real world: In interviews, writing these five lines on the board in the first five minutes and referring back to them is the strongest opening.

Skipping straight to 'collaborative filtering'. Without the goal and limits, you cannot justify any architecture.

Framing

What it is

Turn the goal into an ML task:

  • prediction target: the probability that this customer adds this product to the basket in this session, if shown;
  • task: retrieval (find ~2,000 candidates) then pointwise ranking (score them), with re-ranking for variety and rules;
  • offline metrics: recall at 2,000 for retrieval; NDCG at 10 and add-to-basket AUC for ranking;
  • online metric: basket additions from the row per home-screen view;
  • guardrails: order value, cancellations, p99 latency, share of views with an empty or short row.

Why it matters

'Added to basket' is close to revenue, frequent enough to train on, and arrives within minutes.

  • Clicks alone reward curiosity; purchases alone are rarer and noisier.
  • A multi-task model can predict click, add and purchase together and blend them (module 12).

In the real world: Kirana Kart blends predicted add-to-basket with expected margin at 70:30 (module 14), tuned by experiment.

Optimising clicks. On a grocery app, a tempting snack image gets clicks and few purchases; the row looks busy and sells little.

Data and labels

What it is

What to collect and how labels are built:

  • impressions: every product shown, with position, request ID, model version and context (module 5);
  • actions: clicks, additions, removals, purchases, joined by request ID;
  • catalogue: product attributes, images, prices, stock by store;
  • labels: 1 if added to basket within the session after being shown, else 0;
  • sampling: keep all positives and about 10% of negatives (module 4); correct probabilities if they are used directly (module 7).

Why it matters

Impressions are what make negatives possible.

  • Position must be logged to correct for position bias (module 7).
  • Logging the served features lets training use exactly what serving saw (module 5).

In the real world: Kirana Kart's training table is built nightly from impression logs joined to basket events, with served features already attached.

Treating every non-added impression as a dislike. Items in positions 15–20 were often never seen; down-weight or drop deep-position negatives, or correct by examination probability.

Practise it: Design Model Monitoring, Design a Search Ranking System

Features

What it is

Four groups (module 14):

  • customer: purchase history by category, average basket, Kart Plus member, days since last order, embedding;
  • product: category, brand, price, margin, popularity in this store this week, image-and-title embedding;
  • customer × product: times bought, days since last bought, typical repurchase interval, embedding similarity, brand affinity;
  • context: time of day, day of week, store, items in the current basket, items viewed this session.

Why it matters

Customer × product features dominate in grocery: people buy the same things again.

  • 'Days since last bought ÷ usual interval' captures 'running low on milk'.
  • Context changes intent: breakfast in the morning, snacks on Friday night.
  • Session features let the row react to what was just added.

In the real world: The two most important features in Kirana Kart's ranker are 'times bought' and 'days since last bought relative to the customer's usual interval'.

Visual example

Features

The cheapest kind that is fresh enough.

Features by group and freshness
groupexamplekind
CustomerOrders by category, 90 daysBatch, nightly
ProductPopularity in this store this weekBatch, hourly
Customer × productDays since last bought ÷ usual intervalBatch, nightly
ContextItems in the basket right nowOn-demand
SessionProducts viewed in the last 10 minutesStreaming

Features that cannot be fetched in time. Every feature needs a live source and freshness (module 9); batch the reads into one call.

Practise it: Design a Demand Forecasting Platform, Design a Predictive Maintenance System, Design a Real-Time Fraud Detection System, Design an ML Feature Store

Architecture

What it is

A four-stage cascade (modules 13 and 14):

  • candidate sources: two-tower embedding retrieval from a per-store index; buy-again from history; item-to-item from the basket; trending in the store;
  • light ranker: a small model cuts ~2,000 to ~500;
  • heavy ranker: a gradient-boosted or multi-task neural model scores ~500;
  • re-ranking: in-stock filter, restricted-item rules, variety (at most two per sub-category in the top ten), one sponsored slot, some exploration.

Why it matters

Each stage spends effort where it matters, keeping total time within budget.

  • Per-store indexes make 'in stock here' a pre-filter (module 13).
  • Rules live in re-ranking, where they are readable and guaranteed.

In the real world: This shape (several retrieval sources, a ranker, rule-based re-ranking) is what most large e-commerce and content platforms describe publicly.

Visual example

Architecture

Heavy work on few items; rules last.

The Top picks cascade

  1. candidate sources, in parallel
    EmbeddingsNearest to the customer
    Buy againTheir usual items
    Goes with basketBought together
    TrendingPopular in this store
  2. Light ranker~2,000 → ~500Small, fast model
  3. Heavy ranker40 msAccurate model
  4. Re-rankStock, rules, variety, exploration
  5. Show and log20 itemsTop 20 on the home screen
Home-screen request
  -> fetch customer + context features (one batched read)           ~15 ms
  -> candidate sources in parallel: ANN (store index), buy-again,
     goes-with-basket, trending  -> ~2,000                          ~10 ms
  -> light ranker -> ~500                                           ~10 ms
  -> heavy ranker (one batched call) -> scores                      ~40 ms
  -> re-rank: stock, rules, variety, sponsored slot, exploration     ~2 ms
  -> top 20 to the app; log impressions with request ID
Fallback on timeout: buy-again + trending, no ranking

One model doing everything. A single deep model over the whole catalogue cannot meet 100 ms; a single popularity list cannot personalise.

Training and serving at scale

What it is

Offline and online parts:

  • nightly: retrain the two-tower model and ranker; recompute item vectors; rebuild per-store indexes; compute batch features;
  • streaming: session features (recent views and additions) into the online store;
  • online: the ranking service, autoscaled on requests per replica (module 19), with a timeout and fallback;
  • release: gate, shadow, canary, A/B (modules 15, 17 and 20).

Why it matters

The heavy work happens once a day; the per-request work is a lookup, a search and one batched model call.

  • Vectors and indexes are rebuilt together after each retrain, so spaces never mix (module 13).

In the real world: Kirana Kart's nightly job finishes by 5 a.m.; the new index is swapped in atomically per store before the morning rush.

Visual example

Computed

Peak 278 requests a second; 64-number vectors.

Memory for vectors, 4 bytes per number
whatcountmemory
Customer vectors (all monthly users)5,000,0001.3 GB
Product vectors (one city)50,00012.8 MB
Heavy-ranker scores at peak138,889 a second—

Customer vectors fit in one online store; per-city product indexes are tiny. The ranker's 278 × 500 scores a second set the serving fleet (module 4: 8 CPU replicas).

Retraining the two-tower model without rebuilding the index. User vectors from the new model are compared with item vectors from the old one, and recommendations become random.

Practise it: Design an ML Training Pipeline, Design Feature Monitoring, Diagnose Training-Serving Skew, Design an ML Feature Store

Evaluation

What it is

Offline, then online:

  • offline: time-split evaluation on the latest week; recall at 2,000 per candidate source; NDCG at 10 and AUC for the ranker; slices for new customers, new products, each city;
  • online: A/B test by customer, primary metric basket additions from the row per view, guardrails order value, cancellations, latency; at least two weeks for novelty;
  • faster screening: interleaving to choose among several rankers before the A/B test (module 17).

Why it matters

Offline wins often do not carry over (module 16), so offline is a filter and the A/B test decides.

  • Slices matter: a model that helps loyal customers and hurts new ones may still win overall.

In the real world: About half of Kirana Kart's offline-winning rankers fail to beat the champion online; the A/B gate catches them.

Judging retrieval and ranking only by the online result. When something regresses, you cannot tell which stage did it.

Practise it: Design a Large-Scale Classification Platform, Design a Predictive Maintenance System, Design a Real-Time Anomaly Detection System, Design a Recommendation System, Diagnose Training-Serving Skew, Improve a Low-Recall Model, Design a Search Ranking System

Monitoring and failure modes

What it is

What can go wrong, and what is watched:

  • empty or short rows (stock filters too strict, index not rebuilt): share of views with fewer than 10 items;
  • stale features (session stream stalled): freshness alerts and fallback rate;
  • popularity collapse (feedback loop): number of distinct products receiving meaningful exposure per week;
  • cold start: performance for new customers and products, with exploration slots;
  • drift: festivals and promotions change baskets; nightly retraining plus event-triggered checks.

Why it matters

Recommenders fail quietly: a worse row still loads.

  • Diversity and coverage metrics catch feedback loops that click metrics hide (module 22).
  • Business guardrails catch rows that sell more snacks but fewer staples.

In the real world: Kirana Kart alerts if fewer than a set number of distinct products appear in the top ten across a store's customers in a day, its main guard against a narrowing loop.

Monitoring only click-through on the row. A feedback loop raises it while the range of products shown shrinks.

Practise it: Design Feature Monitoring, Design Model Monitoring

Interview questions: the recommendation design

What it is

The questions interviewers ask about the recommendation design, from the first screening call to the senior round. Cover the answer, say yours aloud, then compare.

Why it matters

Reading an idea and explaining it are different skills.

  • Each answer below is the two or three sentences an interviewer is listening for.
  • The reasoning behind each one is in the cards above. If an answer surprises you, go back to that card.

In the real world: Interviewers usually push on one of three areas after the overview: cold start, the feedback loop, or how the 100 ms budget is met.

Q: How do you handle a brand-new customer?

Popular-in-store and trending candidates, context (time, location), a short onboarding preference choice if available, and fast updates from the first clicks through session features.

Q: How do you handle a new product?

Content features (title and image embeddings, category, brand) in the item tower so it has a sensible vector at once, plus guaranteed exploration impressions for its first weeks.

Q: Why not just use collaborative filtering?

Matrix factorisation is a fine retrieval source, but it cannot use context, session or content features and handles cold start poorly; a ranker on top combines all signals.

Q: How do you avoid recommending things they just bought?

A customer × product feature for days since last bought relative to their usual interval, plus a re-ranking rule excluding items already in the basket.

Q: How would you include business goals like margin?

Predict add-to-basket and expected margin, blend with tuned weights, and cap sponsored items in re-ranking; choose weights by A/B test with order value and satisfaction as guardrails.

Q: What is your fallback?

If ranking times out, serve buy-again and trending candidates in a fixed order; if everything fails, a cached popular list for the store.

Drawing only the model and leaving out candidate generation, logging and fallbacks.

Practise it: Design a Recommendation System

Exercise: design a variant

What it is

A short build that uses this module's ideas. Write it yourself before looking anything up; the checks at the end tell you whether it works.

Why it matters

An idea you have only read fades in a week.

  • Building it once, even in fifty lines, is what makes it yours.
  • Interviewers can tell the difference between someone who has read about a loop and someone who has debugged one.

In the real world: Practising variants is how candidates stop memorising one design and start reasoning from requirements.

Your task. Adapt this design to a different recommendation problem and present it in 35 minutes, as in an interview.

Steps

  1. Pick one: 'recommend restaurants on a food app', 'recommend videos for a short-video feed', or 'people you may know'.
  2. Write requirements with numbers; state what is different from Kirana Kart (item lifetime, catalogue size, label).
  3. Choose the prediction target and say why.
  4. Draw the cascade with candidate sources specific to the problem.
  5. List the key features in four groups.
  6. Plan offline and online evaluation, and three monitored failure modes.
  7. Time yourself presenting it aloud.

You are done when

  • Every architecture choice points back to a requirement.
  • Cold start and the feedback loop are both addressed.
  • You finish inside 35 minutes with time for questions.

Stretch. Have someone interrupt with three follow-up questions and answer each in under a minute.