"Design a recommendation system" is a machine learning question inside a systems interview, and the trap is to spend all your time on the model. The interviewer is not hiring you to derive matrix factorization. They want to see that you can build the platform around the model: where the data comes from, how features are computed once and used twice, how candidates are retrieved fast, and how you know the new model is better than the old one.
The most important idea is a split: what you compute offline, ahead of time and cheaply, versus what you compute online, at request time, with fresh context. Everything else follows from where you draw that line.
This page is the general design, for any catalog (movies, products, articles). The short-video version, with its streaming feedback loop, is in Design TikTok, and the playback side of a streaming product is in Design Netflix. The machinery here is explained in ML pipelines and feature stores.
Clarify the requirements
Functional requirements:
- Given a user and a context (the home page, a product page), return a ranked list of about 20 items.
- Recommendations improve as users interact: clicks, purchases, ratings, skips.
- New users and new items get sensible results.
- Results exclude items the user has already consumed or cannot access.
- The team can train, evaluate and ship new models safely.
Out of scope, said aloud: the user interface, ads, deep model architecture choices, content moderation.
Non-functional requirements: these decide the architecture.
- Responses in under about 100 ms, since the list appears on the first screen.
- Always return something. A recommendations row that fails to load is worse than one that is slightly less relevant.
- Fresh enough. A user who buys a laptop should stop seeing laptops within the session, not tomorrow.
- Reproducible training. A model must be trainable on the same data later, and its features must be computed the same way in training and serving.
- Safe change. Any new model is launched to a small share of users with a measured comparison before it reaches everyone.
Estimate the scale
Assume 100 million daily active users and a catalog of 10 million items. Each user triggers about 5 recommendation requests a day, and generates about 60 logged events a day (impressions, clicks, purchases).
Requests: 100M × 5 = 500 million a day, about 5,800 per second, and about 17,000 per second at peak.
Events: 100M × 60 = 6 billion a day, about 69,000 per second. At 200 bytes each, that is about 440 TB a year, and a 90-day training window holds about 108 TB.
Embeddings: with 128 dimensions of 4 bytes, an item vector is 512 bytes. 10M items is 5 GB, small enough to hold in memory on one machine. 100M user vectors is 51 GB, which spreads across a few.
Ranking work: if the ranker scores 500 candidates per request, that is 5,800 × 500 = 2.9 million scores per second. This is the expensive step.
Batch table: precomputing 50 item IDs for each of 100M users is 5 billion IDs at 8 bytes, or 40 GB.
"Retrieval is cheap: 5 GB of item vectors in memory and a few thousand lookups a second. Scoring is the cost, at about 3 million scores per second. And all of the volume, 6 billion events a day, goes through a data pipeline. So the design is about keeping the expensive model off most candidates, and keeping the data pipeline correct."
The capacity estimator reproduces the event rate, the request rate and the yearly volume.
API and data model
GET /v1/recommendations?userId=...&surface=home&n=20&context={...}
-> { items[{itemId, score, reason}], modelVersion }
POST /v1/events [{ userId, itemId, type: impression|click|purchase, position, ts, requestId }]events append-only log, partitioned by userId (impressions carry requestId + position)
user_features (user_id PK, long_term_embedding, recent_items[], counts...) -- online store
item_features (item_id PK, embedding, category, price, age, popularity) -- online store
batch_recs (user_id PK, items[50], model_version, computed_at) -- precomputed
model_registry (model_id, version, training_data_range, metrics, status)The non-obvious choice: every impression is logged with the request ID, position and model version. Without it, you cannot tell which model produced which result, you cannot correct for the fact that items shown higher get more clicks, and you cannot run a fair experiment.
High-level design
We simulate the serving path: a recommendation API reads user features from a fast store, retrieves candidates from a vector index, and publishes events to a stream, where a feature pipeline keeps the online features fresh.
- The API reads user features from Redis and retrieves nearest-neighbor candidates from the vector index.
- Events flow through Kafka to a pipeline that writes fresh features back to Redis.
Describe this diagram
Components
- users (Client)
- recommendation api (Service)
- feature store (Redis)
- candidate index (Vector database)
- event stream (Kafka)
- feature pipeline (Service)
Connections
- users sends to recommendation api
- recommendation api sends to feature store
- recommendation api sends to candidate index
- recommendation api sends to event stream
- event stream sends to feature pipeline
- feature pipeline sends to feature store
Run it, then try more load or removing the feature store. Staleness and latency both come from that store.
The serving path: load the user's features, retrieve a few hundred candidates by similarity to the user's embedding, fetch item features, score with the ranking model, filter and diversify, and return 20.
The learning path: events stream into a log. A stream job updates the online features within seconds. A scheduled job joins events into a training set, trains a new model and writes it to the registry. The same job refreshes embeddings and the item index.
The interesting problem: offline versus online
Where do you compute the answer?
Approach A: fully offline
Every night, compute the top 50 items for every user and store them in a key-value table. Serving is a lookup.
Good: serving is trivial and almost free, with latency of a few milliseconds and no model at request time. Easy to operate.
Bad: it is stale by up to a day and blind to the session. It computes lists for the 70% of users who will not visit today. New items cannot appear until the next run, and new users have no list.
Approach B: fully online
At request time, retrieve and score from scratch using the freshest data.
Good: the freshest results and full use of session context.
Bad: every request pays the full cost, 2.9 million scores per second at peak, with a tight latency budget. A slow model or feature store breaks the page.
Approach C: hybrid, a funnel with an offline foundation
Split by what changes slowly and what changes fast:
- Offline (hours to days): train models, compute item and user embeddings, build the vector index, and precompute a fallback list for each user.
- Nearline (seconds): a stream job updates each user's recent-activity features and counters as events arrive.
- Online (milliseconds): retrieve candidates by embedding similarity, add a few from the precomputed list and from popularity, score about 500 with the ranker using fresh features, apply business rules and return.
Retrieval typically uses a two-tower model: one network turns a user and its context into a vector, another turns an item into a vector, and a high dot product means a good match. The item tower is run offline for the whole catalog, so serving is one user-tower call plus an approximate nearest-neighbor search.
The recommended answer is C, and the key sentence is: heavy and slow offline, light and fresh online, with an offline fallback if the online path fails.
Evaluating models and cold start
Offline metrics first. Replay logged interactions and measure whether the held-out item appears in the top K (recall@K), and how well the ranking orders relevant items (NDCG). Split by time, training on the past and testing on the following days, so the model never sees the future. Offline gains are a filter, not a proof.
Online A/B tests decide. Route a small, random share of users (1 to 5%) to the new model and compare the metric the business cares about (purchases, watch time, retention) with guardrails (latency, error rate, diversity, complaints). Assign by user ID hash so each person has a consistent experience, and run long enough to cover weekly cycles.
Beware the feedback loop. The model only learns from what it showed. Items never shown never get data, and the system narrows. Reserve a small exploration share of slots, and log the position so that training can correct for the fact that higher positions get more clicks.
Cold start. A new item has no interactions, so score it with content features (category, text and image embeddings, price) and give it a limited exposure budget. A new user starts with popularity within their country and device, and shifts to personalization as events arrive within the session.
Bottlenecks and failures
The feature store is slow or down. Fetching features for 500 candidates is the largest latency cost. Batch the lookups into one call, keep item features in a local in-process cache, and set a short timeout. On failure, fall back to the precomputed list.
Stale or broken features. A pipeline bug silently feeds old values, and quality drops with no error. Monitor feature freshness and distributions against training, and alert on drift.
A bad model rollout. Compare online metrics against the control during the A/B and keep the previous model loaded for instant rollback. Version every response with its model ID.
What if the vector index is unavailable? Serve the batch fallback list and popular items for the user's segment. The page remains full, and personalization gets coarser.
Trade-offs to name aloud
- Hybrid serving: more components than either extreme, and the right balance of cost and freshness.
- Two-tower retrieval: fast and scalable, at the price of a weaker interaction between user and item than a full ranker, which is why a ranker follows it.
- A feature store: one definition for training and serving, and a platform to run.
- Exploration slots: a small drop in short-term metrics for long-term learning and fairness to new items.
What interviewers listen for
- A working answer: collect interaction events, train a model offline, store recommendations in a key-value store and serve them.
- A strong answer: a funnel with retrieval and ranking, an offline and nearline and online split with numbers, a feature store to avoid skew, a precomputed fallback, and A/B tests for launching models.
- A standout answer: also logs impressions with positions for unbiased training, splits evaluation by time, handles cold start with content features and exploration, monitors feature freshness and drift, and plans rollback by model version.
Check your understanding
Common mistakes
Spending the whole interview on the model. The platform around it is what a systems interview examines. State the model in a sentence and design the rest.
Computing everything online. At 3 million scores a second it is expensive and fragile. Retrieve cheaply and score a small set.
Computing everything offline. Stale, blind to the session and wasteful for inactive users.
No story for cold start. New items and new users are daily events, not edge cases.
Evaluating only offline. A good offline metric is necessary and not sufficient. Describe the A/B test and its guardrails.
Practice
After a launch, click-through rate rises 5% but purchases fall 2%. How do you decide whether to keep the new model?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Think about which metric reflects the goal, and what might explain the gap.
Show a strong answer
Decide the primary metric before the test. If the goal is purchases or revenue, then clicks are a proxy, and a proxy that rises while the real goal falls is a warning. The primary metric decides unless there is a reason to distrust it.
Check that the drop is real. Use the experiment's confidence interval, not the raw difference, and make sure the run covered a full weekly cycle. A 2% fall within the noise is not a result.
Look for the mechanism. The new model may favor attractive but low-intent items, such as cheap or clickbait products. Break down the results by category, price and user segment. Check whether it reduced the diversity of what is shown.
Decide with guardrails. Without a clear win on the primary metric, do not ship. Use the findings to retrain with a purchase-weighted objective or add a purchase-prediction head, and run again.
The pattern worth keeping: optimize and judge by the metric that matches the business goal, and treat a proxy moving the wrong way as a reason to investigate.
The nightly job that computes embeddings and the batch fallback list now takes 26 hours. What are your options?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Look at what needs full recomputation and what could be incremental.
Show a strong answer
Find what dominates the time. Usually it is scoring every user, though only a minority are active. Split users into active (seen in the last 14 days) and inactive, and run the full computation only for active users, about 30% of the total.
Make the work incremental. Item embeddings change only when the model changes or the item does, so recompute for new and changed items daily and the whole catalog only on a new model. User embeddings can be updated from new events instead of recomputed from history.
Parallelize by partition. Partition users by ID and run the job across many workers, with checkpoints so a failed worker restarts only its partition.
The pattern worth keeping: recompute only what has changed, partition the rest, and design serving to survive a late batch.
Key takeaways
- The design is the line between offline and online. Heavy and slow offline, light and fresh online.
- Use a funnel: cheap retrieval over embeddings, then a ranker on a few hundred candidates.
- One feature definition for training and serving prevents skew.
- Keep an offline fallback list so the page is never empty.
- Evaluate offline by time-split, decide online with A/B tests and guardrails.
- Log impressions with position and model version, handle cold start and keep exploring.
Further reading
- P. Covington, J. Adams and E. Sargin, "Deep Neural Networks for YouTube Recommendations", ACM RecSys (2016): the two-stage candidate generation and ranking design.
- Y. Koren, R. Bell and C. Volinsky, "Matrix Factorization Techniques for Recommender Systems", IEEE Computer (2009): learned user and item vectors.
- C. A. Gomez-Uribe and N. Hunt, "The Netflix Recommender System: Algorithms, Business Value, and Innovation", ACM Transactions on Management Information Systems (2015): evaluation, A/B testing and business metrics.