Recommendation System Fundamentals
Recommendation questions are the most common ML system design prompt by a wide margin. "Design the TikTok feed," "recommend restaurants on the home page," "rank posts in a news feed," "suggest people you may know," "pick which ads to show": the products are different, but underneath they're the same machine. Given a user and a context, choose a handful of items out of millions, in a fraction of a second, so that the user does something you value.
If you understand that machine, every recommendation question becomes a matter of adjusting it: what the items are, what counts as success, which signals exist, and which constraints matter most. If you don't, each question feels new, and you end up drawing one giant model that scores every item, which is the most common way these interviews go wrong.
We'll build it up in this order:
- Why recommenders are built as a funnel: retrieval, ranking, re-ranking.
- Candidate generation, from co-occurrence and matrix factorization to the two-tower model and approximate nearest neighbor search.
- Ranking: what the model predicts, which losses, and how multiple objectives combine.
- Re-ranking: diversity, business rules and exploration.
- Cold start, feedback loops and bias.
- How to evaluate a recommender offline and online.
The worked problem breakdowns (TikTok's video feed, homepage recommendations, news feed ranking) apply all of this to specific products. Here we focus on the shared foundations.
The Funnel
Suppose we have 100 million items and a latency budget of about 200 ms. Even a tiny model that takes 1 microsecond per item would need 100 seconds of compute per request to score everything. A real ranking model, with hundreds of features and a few million multiply-adds per item, takes far longer than that. Scoring the whole catalog with the best model is impossible.
So every large recommender splits the work into stages, each looking at fewer items with a more expensive model:
- Candidate generation (retrieval): from the whole catalog (10^8 items) down to a few thousand plausible candidates, in about 10 to 30 ms. Uses cheap methods that can search the catalog without scoring every item: precomputed lists, inverted indexes, and nearest neighbor search over embeddings. Optimized for recall: don't miss the good items.
- Pre-ranking (lightweight ranking): optional. From a few thousand to around 500 with a small model, often a two-tower model with a few extra features.
- Ranking: a heavy model scores each remaining candidate with rich user, item, context and cross features. Optimized for precision at the top: put the best items first. This is where most of the modeling effort goes.
- Re-ranking: turns a list of independently scored items into a good page or feed. Applies diversity, freshness, business rules, deduplication, and exploration.
The split also helps organizationally: retrieval sources can be added and tuned independently, the ranker can be retrained without touching retrieval, and the re-ranker encodes product policy separately from the models.
When you draw the funnel in an interview, put numbers on every stage: "10^8 items → 2,000 from retrieval in 20 ms → 500 after pre-ranking → top 50 from the ranker in 40 ms → 10 shown after re-ranking." It shows you understand why the funnel exists, and it gives you the latency budget you'll need later for serving.
Candidate Generation
Retrieval answers the question: out of everything, which few thousand items are worth looking at for this user right now? There's no single best method, so production systems run several retrieval sources in parallel and merge them with per-source quotas.
Heuristic Sources
Don't skip these; they're cheap, explainable and surprisingly hard to beat for certain slices:
- Popular and trending, per region, language or category. The default for brand-new users.
- Social and subscription: items from creators, friends or stores the user follows.
- Recently engaged: items or categories the user interacted with, re-surfaced (re-ordering a favorite restaurant).
- Geographic: restaurants that deliver to the user's address, rides near the pickup point. For local products this is a hard filter, not just a source.
Item-to-Item Collaborative Filtering
The oldest idea in recommendation that still works at scale: users who engaged with item A also engaged with item B. Count co-occurrences in user histories (within a session or a time window), normalize them so popular items don't dominate (cosine similarity, or pointwise mutual information), and store the top 50 or so neighbors for each item.
sim(A, B) = co_count(A, B) / sqrt(count(A) * count(B))
At request time, take the user's last few engaged items and union their neighbor lists. The lookups are fast, the neighbor lists are computed offline in Spark, and results are easy to explain ("because you watched X"). Item-to-item CF is still a strong retrieval source for e-commerce and media. Its weaknesses: it can't recommend items with no interactions, and it's limited to items near something the user already touched.
Matrix Factorization
Arrange interactions in a giant sparse matrix: users as rows, items as columns, an entry where a user engaged with an item. Matrix factorization learns a low-dimensional vector for every user and every item such that their dot product approximates the matrix:
R (users × items) ≈ U (users × k) · Vᵀ (k × items), score(u, i) = u · v_i
With k around 64 to 256, two people who like similar things end up with similar vectors, even if they never engaged with the same item. Training uses alternating least squares (ALS), which alternately solves for user and item vectors and parallelizes well (Spark MLlib has it), or SGD. For implicit feedback (clicks and views rather than star ratings), the standard formulation treats every unobserved entry as a weak negative and every observed one as a positive weighted by confidence, such as the number of plays.
Matrix factorization was the core of the Netflix Prize era and is a fine baseline to name. Its limits are why the field moved on: it only knows user and item IDs, so it can't use context (time of day, device), content (an item's text or image), or the user's most recent actions without retraining; and new users and items have no vector at all.
The Two-Tower Model
The two-tower model generalizes matrix factorization by replacing the ID lookup tables with neural networks that take features:
- The user (query) tower takes user ID embedding, demographics, the recent interaction sequence (often pooled or passed through a small transformer), and request context, and outputs a vector
u. - The item tower takes item ID embedding, content features (text and image embeddings, category, price), and aggregate stats, and outputs a vector
v. - The score is the dot product
u · v(or cosine similarity).
The crucial property is that the towers don't interact until the final dot product. That means every item vector can be computed offline and loaded into an approximate nearest neighbor (ANN) index. At request time we compute one user vector (a few milliseconds) and ask the index for the top 1,000 items by dot product, which takes a few milliseconds even over hundreds of millions of items. Content features in the item tower give new items a useful vector before they have any interactions.
Training. Each example is a (user, positive item) pair from logged engagement. The model is trained to score the positive higher than negatives with a sampled softmax loss:
u = user_tower(user_features) # [B, d]
v = item_tower(item_features) # [B, d], positives for each user in the batch
logits = u @ v.T / temperature # [B, B]: every other user's positive is a negative
logits -= log_sampling_prob[None, :] # logQ correction for popularity
loss = cross_entropy(logits, labels=arange(B))
The cheapest negatives are in-batch negatives: the positives of the other users in the same batch. They're free, but popular items appear in many batches and so get used as negatives far more often than random sampling would, which teaches the model to under-score popular items. The logQ correction subtracts the log of each item's sampling probability from its logit to undo that bias. Many systems also mix in random negatives from the whole catalog (so the model sees the long tail) and a few hard negatives (items shown to the user and ignored), though too many hard negatives can confuse a retrieval model whose job is coarse filtering.
Serving the index. The ANN index is usually HNSW (a navigable graph, fast and accurate, memory-hungry) or IVF with product quantization (cluster the vectors, search only the nearest clusters, store compressed codes). Size it: 100 million items × 128 dimensions × 4 bytes is about 51 GB in float32, which fits in RAM across a few machines or one large one; PQ with 64-byte codes shrinks it to 6.4 GB at some cost in recall. Libraries and systems: Faiss, ScaNN, and vector databases like Milvus or Pinecone. See Vector Databases.
Keeping it fresh. Item vectors must be recomputed when the item tower is retrained, and both towers must come from the same model version; a user vector from model v12 searched against item vectors from v11 is garbage. Rebuild or swap the index atomically, and add new items to the index incrementally as they're created (HNSW supports inserts).
The key interview insight about two-tower models: the lack of interaction between the towers is both why they're fast and why they're not enough. A dot product can't express "this user likes horror, but not at 8 a.m. on a weekday", so retrieval gets the candidate set roughly right and the ranker, which can cross user and item features freely, gets the order right.
Other Retrieval Sources
- Graph-based: random walks or graph neural networks over the user-item graph (Pinterest's PinSage is a well-known example), or friend-of-friend for social products. See People You May Know.
- Sequential / next-item: a transformer over the user's recent sequence predicts the next item's embedding, which is then used as the ANN query. Strong for session-based products.
- Search-like: inverted indexes on tags, categories or keywords the user has engaged with.
Merging Sources
Each source returns a scored list, but scores from different sources aren't comparable. Give each source a quota ("up to 800 from two-tower, 300 from item-to-item, 200 from follows, 100 from trending, 100 from fresh items"), dedupe the union, and let the next stage sort it out. Then apply hard filters: already seen, out of stock, blocked creators, not available in the user's region, policy violations. Filtering after retrieval rather than inside it can leave you with too few candidates, so either over-fetch or push the most selective filters into the index (most vector databases support filtered search).
Ranking
The ranker takes the few hundred to few thousand candidates and scores each one carefully. This is where rich features and big models pay off.
What the Ranker Predicts
Nearly every modern ranker is pointwise: for each (user, item, context) it predicts the probability of specific actions, like P(click), P(purchase), P(watch > 50%), P(like), P(hide). These are trained as binary classifiers on logged impressions: items that were actually shown, labeled with what the user did. A separate head may regress continuous outcomes like watch time.
Why predict actions instead of a single "relevance" score? Because actions are observable and loggable, each one can be calibrated and monitored, and the business can change how much each one matters without retraining.
The final ranking score combines the predictions with a value model:
score = w_click · P(click) + w_buy · P(buy) · price_margin + w_like · P(like) − w_hide · P(hide)
The weights encode product priorities and are tuned with A/B tests rather than learned. In ads, the combination is economic: expected value = bid × P(click) × P(convert | click), which is why ads rankers obsess over calibration. See Design an Ads Ranking System.
Pointwise, Pairwise and Listwise
There are three ways to set up the learning problem:
| Approach | Learns | Typical loss | Notes |
|---|---|---|---|
| Pointwise | P(action) for each item independently | Binary cross-entropy | Calibrated probabilities; easy to combine objectives; the industry default |
| Pairwise | Which of two items the user preferred | BPR, RankNet | Directly optimizes order; needs pairs from the same request |
| Listwise | The best ordering of a whole list | Softmax / ListNet, LambdaMART | Closest to ranking metrics like NDCG; common in search |
Pointwise models win in recommendation mostly because their outputs are probabilities, which you need for value models, auctions and monitoring. Listwise methods (LambdaMART on GBDTs, for example) are common in search ranking, where human relevance labels exist and the metric is NDCG.
Model Families
The usual progression, which is also a good way to structure the modeling part of an interview answer:
- Logistic regression on hand-crossed features. Fast and interpretable, but every interaction must be engineered by hand.
- Gradient-boosted trees (XGBoost, LightGBM) on a few hundred dense features: counters, affinities, embedding similarities. Strong, easy to debug, and the right first model when data is moderate. They can't consume raw IDs or sequences well.
- Deep models with embeddings: Wide & Deep, DeepFM, DCN, DLRM. Learn embeddings for sparse IDs and learn feature interactions automatically. The standard at large scale.
- Sequence-aware models: attention over the user's recent history with the candidate as the query (the idea behind Deep Interest Network), or a transformer over the sequence.
- Multi-task architectures like MMoE that predict all the actions from shared representations with task-specific gates, so related tasks share what they learn and conflicting ones don't interfere.
Common ML Models for System Design compares these families in detail.
Features
Ranking features fall into four groups:
- User: demographics, long-term interest embeddings, activity counts, recent sequence.
- Item: category, creator, price, age, content embeddings, aggregate engagement rates (CTR over the last hour, day and week).
- Context: time of day, day of week, device, location, surface (home page vs. search), what's already on the page.
- Cross features: how this user relates to this item: past engagement with this creator or category, similarity between the user embedding and the item embedding, the retrieval source and its score.
Cross features are usually the most predictive. Aggregates need to be fresh (a creator's CTR over the last hour matters for trending content), which means streaming computation in Flink or a similar system, served from a feature store. Training must use feature values as they were at the time of each impression, not as they are now, or the model learns from the future (point-in-time correctness). See Design a Feature Store.
Re-Ranking
The ranker scores items one at a time. A page of ten items isn't ten independent decisions, though: the top ten by score might be five videos from the same creator, or ten nearly identical blue sneakers. Re-ranking fixes the list as a whole.
- Diversity: maximal marginal relevance (MMR) builds the list greedily, picking at each step the item that maximizes
λ · score − (1 − λ) · max similarity to items already picked. Determinantal point processes are a more principled version that rewards sets of items that are jointly diverse. - Business rules: no more than two items from one seller in the top ten, a freshness quota, promoted content in fixed slots, age-appropriate filtering.
- Deduplication and fatigue: don't show what the user has seen several times without engaging; keep a per-user record of recent impressions (a Bloom filter or a small set in Redis).
- Fairness and supply health: make sure new or small creators get some exposure, so the ecosystem doesn't collapse onto the top 1 percent.
- Exploration: reserve a few slots for items the model is uncertain about (covered next).
A common mistake is to stuff diversity into the ranker's objective. The ranker can't see the other items on the page, so it can't know that an item is redundant. Keep the ranker pointwise and handle list-level goals in a re-ranking pass; mention a learned listwise re-ranker (a transformer over the top candidates) as the advanced version.
Cold Start
New users and new items have no interaction history, which is exactly what most of the machinery above depends on.
New Users
- Start from context: country, language, device, time of day, referral source, and the first query or category they open. These alone support a decent popularity-by-segment feed.
- Onboarding: ask for a few interests, or show a diverse grid and learn from the first clicks.
- Learn fast within the session: features built from the session's own clicks (in the user tower and as ranker features) let the second page be personalized even when the first wasn't.
- Lean on exploration more heavily for new users, because there's so much to learn.
New Items
- Content features: the item tower's text, image and metadata embeddings give a new item a reasonable vector immediately, so it can be retrieved for users whose interests match.
- Creator and category priors: a new video from a creator with a high historical completion rate starts with a better prior than one from an unknown account.
- Boosted exploration: give new items a guaranteed amount of exposure to a targeted audience, measure how they perform, and promote the ones that do well into wider distribution.
Exploration vs Exploitation
If the recommender only shows what it already believes is best, it never learns whether it's wrong. Exploration spends a small share of impressions to reduce uncertainty:
- Epsilon-greedy: in a small fraction of slots, show a random (or randomly sampled from a broader pool) candidate. Simple, but the random choices are often bad.
- Upper confidence bound (UCB): boost items whose score is uncertain, in proportion to the uncertainty.
- Thompson sampling: sample a plausible score from each item's posterior and rank by the sample, so uncertain items sometimes come out on top.
Contextual bandits combine these with features. In practice, exploration is usually a budgeted re-ranking step ("one exploration slot per ten items for established users, three for new users") with its traffic logged separately, because randomized traffic is also the cleanest data for measuring bias.
Feedback Loops and Bias
A recommender trains on data its previous versions produced. That loop is the source of most of the subtle problems:
- Exposure bias: items that weren't shown have no labels. The model can't learn that an unseen item was good, so it keeps not showing it. Exploration and the logQ-style corrections in retrieval are partial fixes.
- Position bias: items at the top get clicked more because they're at the top. If you train naively, the model learns "whatever we ranked first is good." Fixes: add position as a training feature and set it to a constant at serving time; train a separate shallow position tower whose output is dropped at serving; or weight examples by inverse propensity estimated from randomized traffic.
- Popularity bias and rich-get-richer: popular items get more exposure, so more engagement, so more exposure. Without correction the catalog's long tail never gets a chance.
- Filter bubbles: the system narrows each user onto what they already engaged with. Diversity in re-ranking and exploration push back.
- Clickbait: optimizing short-term clicks rewards items that attract clicks but disappoint. Use deeper signals (dwell time, completion, purchase, return visits) and negative signals (hide, quick bounce) in the value model.
Delayed labels are a related issue. A click is known in seconds, a purchase in hours or days, a return in weeks. Training only on examples whose labels have matured slows the model; training on fresh examples biases toward negatives (the conversion hasn't happened yet). Common answers are a short attribution window with later correction, or modeling the delay explicitly.
Evaluation
Offline Metrics
Evaluate each stage with metrics that match its job:
- Retrieval: recall@K. Of the items the user actually engaged with in a held-out period, what fraction appeared in the top K retrieved? Retrieval's job is to not miss things, so recall matters more than precision. Also track coverage (what share of the catalog ever gets retrieved).
- Ranking: AUC and normalized cross-entropy / log loss. AUC measures how well the model orders positives above negatives; log loss also checks that the probabilities are right, which matters for value models and auctions. Compute AUC per user and average (group AUC), because a global AUC can be high just from separating heavy and light users.
- List quality: NDCG@K, MRR, precision@K. Reward getting the best items near the top.
- Beyond accuracy: diversity within lists, novelty, catalog coverage, calibration error per segment.
Split data by time: train on days 1 to 28, evaluate on day 29. A random split leaks the future into training (the model sees tomorrow's popularity), and offline numbers end up far more optimistic than online results.
Online Metrics and A/B Testing
Offline metrics are a filter, not a verdict; the change that wins offline often doesn't move the online metric. Online, measure:
- Engagement: CTR, conversion rate, watch time, items consumed per session.
- Long-term value: retention (day-7 and day-28 return), sessions per user per week, subscriptions. These are what the business actually wants, and they move slowly, so experiments run for weeks.
- Guardrails: latency, hides and reports, complaints, revenue, creator-side or seller-side health.
Run A/B tests with randomization by user, watch for novelty effects (users click on anything new for a few days), and remember that recommenders have network effects on the supply side: a test that boosts small creators changes their behavior for everyone. Interleaving (merging two rankers' results into one list and seeing whose items users pick) detects ranking differences with far less traffic than a standard A/B test and is a good tool for screening many candidate models.
Recommendation Systems in an Interview
How to Structure Your Answer
A recommendation answer that hits the main points in order:
- Clarify the objective: which action defines success, and what are the guardrails (hides, diversity, long-term retention)?
- Draw the funnel with numbers: catalog size, candidates per stage, latency per stage.
- Retrieval: several sources including a two-tower model with ANN, quotas, filters.
- Ranking: multi-task pointwise model, the features, the value model, calibration.
- Re-ranking: diversity, rules, exploration.
- Data and training: impressions as training data, labels, negatives, point-in-time features, retraining cadence.
- Evaluation: recall@K, AUC/NDCG offline; A/B test on engagement and retention online.
- Deep dives: cold start, position bias, feedback loops, freshness.
Common Follow-ups
- "Why not just use one model?" Cost: scoring 10^8 items with a heavy model per request is impossible. Show the arithmetic.
- "How do you handle a new item?" Content features in the item tower, creator priors, a boosted exploration budget, fast feedback from streaming counters.
- "How do you choose negatives for the two-tower model?" In-batch negatives with logQ correction, plus random negatives, plus a few hard negatives.
- "Your offline AUC went up but the A/B test is flat. Why?" Leakage or a bad split, the improvement is in a segment that doesn't matter, the ranker is limited by retrieval, position bias in the evaluation data, or the online metric isn't the one the model optimizes.
- "How do you avoid filter bubbles?" Diversity in re-ranking, exploration slots, long-term metrics in the objective, and measuring diversity as a guardrail.
- "How fresh does the model need to be?" Depends on the product: news and short video need streaming features and frequent retraining; a catalog of movies changes slowly. Separate feature freshness (minutes) from model freshness (hours to days).
Summary
A recommender is a funnel: cheap, high-recall retrieval narrows a huge catalog to thousands of candidates; a rich ranker orders them by predicted actions combined in a value model; a re-ranker turns the scored list into a good, diverse page. Retrieval runs several sources in parallel, with the two-tower model at the center: independent user and item encoders trained with sampled softmax and logQ-corrected negatives, item vectors served from an ANN index like HNSW or IVF-PQ. Collaborative filtering and matrix factorization are the ideas it grew from and remain good baselines.
Ranking is pointwise and multi-task in practice, because calibrated probabilities can be combined, monitored and used in auctions. Rankers progress from logistic regression and GBDTs to deep models with embeddings, attention over user history and multi-task heads. Cold start is handled by content features, priors and budgeted exploration. Because the system trains on its own outputs, position bias, exposure bias and feedback loops need explicit corrections. Evaluate each stage with its own offline metric, split by time, and trust only online A/B tests on engagement and long-term retention for the final call.