Contents
Key concepts
Multi-stage architecture
Candidate generation narrows millions of items to hundreds with cheap models (two-tower ANN, item-to-item co-occurrence, popularity, follow graphs); ranking scores those hundreds with rich features and a heavy model; re-ranking applies diversity, freshness, business rules and fairness constraints. Offline jobs train models and build embeddings and indexes; online services fetch features and serve within a latency budget of tens of milliseconds per stage.
Flow · 5 stepsHow a request moves through candidate generation, ranking and re-ranking
- Offline build Offline jobs train models and build embeddings and indexes.
- Request enters A request enters candidate generation with millions of items.
- Narrowing Cheap models narrow millions of items to hundreds.
- Scoring The heavy ranker scores the hundreds with rich features.
- Re-ranking Re-ranking applies diversity, freshness, business rules and fairness constraints.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Offline build | Offline jobs train models and build embeddings and indexes. |
| 2 | Request enters | A request enters candidate generation with millions of items. |
| 3 | Narrowing | Cheap models narrow millions of items to hundreds. |
| 4 | Scoring | The heavy ranker scores the hundreds with rich features. |
| 5 | Re-ranking | Re-ranking applies diversity, freshness, business rules and fairness constraints. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Offline jobs | Offline | train models and build indexes |
| Embeddings and indexes | Offline | embeddings and indexes |
| Request | Online | |
| Candidate generation | Online | cheap models |
| Ranking | Online | rich features and a heavy model |
| Re-ranking | Online | diversity, freshness, rules, fairness |
| Served items | Output |
Source: This page's text
Matrix factorisation and implicit feedback
Factorise the user–item interaction matrix into user and item vectors whose dot product predicts preference. Implicit data (clicks, plays) has no explicit negatives, so treat unobserved pairs as weak negatives with lower confidence (weighted ALS) or sample negatives (BPR’s pairwise loss). Factorisation is a strong baseline and a source of embeddings for retrieval.
Two-tower retrieval and sampling bias
A user tower and an item tower produce embeddings trained so that engaged pairs score higher; items are pre-indexed for ANN search. In-batch negatives over-penalise popular items because they appear as negatives more often; the logQ correction subtracts the log of each item’s sampling probability from the logit (Yi et al., RecSys 2019, estimated item frequency from the stream). Item towers that use content features also help cold-start items.
Ranking models and objectives
Rankers predict several engagement signals (click, watch time, add to basket, skip) with shared layers and task heads, then combine them in a value formula tuned to business goals. Wide & Deep pairs a memorising linear part with a generalising deep part; YouTube’s ranker predicted expected watch time with weighted logistic regression rather than click probability. Losses are pointwise, pairwise or listwise.
Ranking metrics
Precision@k and recall@k count relevant items in the top k; MRR averages the reciprocal rank of the first relevant item; average precision averages precision at each relevant position; nDCG@k discounts graded gains by log₂(rank + 1) and normalises by the ideal ordering. Always state the gain convention (linear or 2^rel − 1) and how queries with no relevant items are handled. Add coverage, diversity, novelty and calibration, which accuracy metrics ignore.
Bias in logged data and offline–online mismatch
Logs only contain feedback on items the old policy showed, in positions it chose (exposure and position bias), so offline metrics favour models that imitate the old policy. Feedback loops narrow recommendations over time. Offline NDCG also ignores latency, diversity and long-term satisfaction, so an offline winner can lose an A/B test; interleaving is a much more sensitive online comparison for rankers.
Counterfactual (off-policy) evaluation
If the logging policy was stochastic and its propensities were logged, inverse propensity scoring reweights logged rewards by π_new(a|x) / π_log(a|x) to estimate a new policy’s value without deploying it. It is unbiased but high-variance when policies differ; self-normalised IPS, weight clipping and doubly robust estimators trade a little bias for much lower variance. Replay evaluation for bandits uses only events where the new policy agrees with a uniformly random logger.
Cold start, exploration and generative recommenders
New users get context, onboarding and popularity priors; new items get content embeddings and an exploration budget (bandits, boosted slots). Generative recommenders treat user histories as sequences and decode the next item: Meta’s HSTU reported a 1.5-trillion-parameter model with 12.4% online metric gains, and TIGER-style semantic IDs quantise each item’s content embedding into a short tuple of codewords (an RQ-VAE with three levels of 256 codes plus a collision-breaking token), so similar and brand-new items share prefixes and the model can generalise to items with no interactions. In 2025 Kuaishou’s OneRec replaced its retrieve-then-rank cascade with one generative model serving a quarter of its traffic, and YouTube’s PLUM continued pre-training an LLM on semantic-ID tokens for retrieval. LLMs also act as query understanding (turning ‘upbeat songs for a rainy run’ into constraints) on top of the existing ranker, selecting only from catalogue IDs they are given or decoding valid semantic IDs.
Flow · 4 stepsHow generative retrieval decodes the next item
- Read history The user history is read as a sequence.
- Decode next item The generative model decodes the next item as a semantic ID.
- Keep IDs valid Beam search is constrained to valid IDs with a prefix trie, so invalid IDs are not served.
- Map to catalogue The valid semantic ID is mapped back to a catalogue item.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Read history | The user history is read as a sequence. |
| 2 | Decode next item | The generative model decodes the next item as a semantic ID. |
| 3 | Keep IDs valid | Beam search is constrained to valid IDs with a prefix trie, so invalid IDs are not served. |
| 4 | Map to catalogue | The valid semantic ID is mapped back to a catalogue item. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| user history | Input | sequence of past items |
| generative model | Decode | decodes next item |
| semantic ID | Decode | 3 levels x 256 codes + collision token |
| catalogue item | Output | next item served |
Source: This page's text
Worked examples
nDCG@5, MRR and average precision for one ranked list
A ranker returns five items with graded relevance [3, 0, 2, 0, 1] (3 = perfect). Compute nDCG@5 with linear gains and with 2^rel − 1 gains, the reciprocal rank and average precision (treat relevance ≥ 1 as relevant, and assume all relevant items are in the list).
Discounts 1/log₂(rank + 1) for ranks 1–5: 1.000, 0.631, 0.500, 0.431, 0.387.
Linear gains
- DCG = 3(1.000) + 0 + 2(0.500) + 0 + 1(0.387) = 4.387
- ideal order [3, 2, 1, 0, 0]: IDCG = 3 + 2(0.631) + 1(0.500) = 4.762
- nDCG@5 = 4.387 / 4.762 = 0.921
Exponential gains (7, 0, 3, 0, 1)
- DCG = 7 + 3(0.500) + 1(0.387) = 8.887; IDCG = 7 + 3(0.631) + 1(0.500) = 9.393
- nDCG@5 = 0.946
Reciprocal rank: first relevant item at rank 1 → 1.0
Average precision: relevant at ranks 1, 3, 5 → precisions 1/1, 2/3, 3/5 AP = (1.000 + 0.667 + 0.600) / 3 = 0.756
The two nDCG conventions differ by 2.5 points on the same list, so never compare numbers across papers or teams without checking the gain definition.
Estimating a new policy from logs with IPS and SNIPS
A stochastic logging policy showed one article per visit and logged its probability. Six events (shown article, logging probability, click): (A, 0.5, 1), (B, 0.3, 0), (A, 0.5, 0), (C, 0.2, 1), (B, 0.3, 1), (A, 0.5, 1). A deterministic new policy would have chosen A, A, A, C, B, B in those six contexts. Estimate its click-through rate.
The weight is 1/π_log when the new policy matches the logged action, otherwise 0.
| event | match? | weight | weight × click |
|---|---|---|---|
| 1 | yes (A) | 2.0 | 2.0 |
| 2 | no | 0 | 0 |
| 3 | yes (A) | 2.0 | 0 |
| 4 | yes (C) | 5.0 | 5.0 |
| 5 | yes (B) | 3.33 | 3.33 |
| 6 | no | 0 | 0 |
IPS = (2.0 + 5.0 + 3.33) / 6 = 10.33 / 6 = 1.72, an impossible CTR above 1. It is unbiased in expectation, but with six events one rare action (probability 0.2) dominates the estimate.
SNIPS divides by the sum of weights instead of n: 10.33 / (2.0 + 2.0 + 5.0 + 3.33) = 10.33 / 12.33 = 0.84
The logging policy’s own CTR is 4/6 = 0.67, so the new policy looks better, but with this little data the honest conclusion is ‘promising, run an A/B test’. In practice use thousands of events, clip weights, check effective sample size (Σw)² / Σw², and add a doubly robust estimator with a reward model.
Flow · 4 stepsHow logged events become an off-policy estimate
- Check the logs Use only logs from a stochastic logging policy with propensities logged.
- Reweight IPS reweights logged rewards by π_new(a|x) / π_log(a|x); unbiased but high-variance when policies differ.
- Stabilise SNIPS, weight clipping and doubly robust estimators trade a little bias for much lower variance.
- Decide Check effective sample size and compare with the logging policy; if promising, run an A/B test.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Check the logs | Use only logs from a stochastic logging policy with propensities logged. |
| 2 | Reweight | IPS reweights logged rewards by π_new(a|x) / π_log(a|x); unbiased but high-variance when policies differ. |
| 3 | Stabilise | SNIPS, weight clipping and doubly robust estimators trade a little bias for much lower variance. |
| 4 | Decide | Check effective sample size and compare with the logging policy; if promising, run an A/B test. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Logged events | Input | rewards + propensities |
| IPS reweighting | Estimate | π_new(a|x) / π_log(a|x) |
| SNIPS, clipping, robust | Estimate | trade bias for lower variance |
| Effective sample size | Estimate | (Σw)² / Σw² |
| A/B test | Decide | promising, not proof |
Source: This page's text
Semantic ID capacity and collisions for a 20M-item catalogue
You want generative retrieval over a catalogue of 20 million videos using TIGER-style semantic IDs: three residual-quantisation levels with 256 codes each, plus a final token that separates items sharing the same three codes. Assuming codes were spread uniformly at random, how many items would need a non-zero disambiguation token? What changes with a fourth 256-code level, and what does that cost?
Capacity of three levels: 256³ = 16,777,216 distinct tuples, already fewer than 20M items, so collisions are guaranteed.
Occupied tuples (balls in bins, n = 20,000,000 items into m = 16,777,216 tuples):
- load n/m = 1.192
- expected occupied tuples = m(1 − e^(−n/m)) = 16,777,216 × (1 − 0.3036) ≈ 11.68M
- items needing a non-zero final token = 20M − 11.68M ≈ 8.32M (about 42%)
Four levels: 256⁴ ≈ 4.29 billion tuples, load 0.0047. Expected colliding items ≈ n² / 2m = (2 × 10⁷)² / (2 × 4.29 × 10⁹) ≈ 46,600 (about 0.2%).
Trade-offs
- Real codes are far from uniform: semantically similar items crowd into the same branches, so measure the actual collision rate and the deepest collision chain, which sets the size of the final token’s vocabulary.
- Each extra level is one more autoregressive decoding step per item, multiplied by the beam width, inside the retrieval latency budget.
- Not every generated tuple maps to an item: TIGER reported roughly 0.1–1.6% invalid IDs in its top-10 results. Constrain beam search with a prefix trie of valid IDs, or over-generate and filter.
- Re-training the content encoder or quantiser remaps IDs, so the generative model must be retrained or the old codebook frozen.
What changed recently
Meta's GEM becomes one central ads foundation model
Meta’s 2026 generation of GEM replaces separately tuned per-surface ad models with one LLM-style recommendation foundation model trained on data from all its ad surfaces, and reports that prediction quality follows a power law in user-sequence length. The giant model does not serve traffic directly: its representations are transferred to hundreds of smaller, latency-bound vertical models, which Meta says is about twice as effective as plain distillation. Interviewers now ask about scaling laws for recommenders and how to move knowledge from a foundation model into a production ranker.
Spotify ships semantic-ID generative retrieval for podcasts
Spotify’s GLIDE frames podcast recommendation as instruction following over a catalogue discretised into semantic IDs, conditioning on recent listening and injecting long-term user embeddings as soft prompts to stay within latency limits. Large A/B tests reported up to 14.3% more new-show discovery and 5.4% more non-habitual streaming. It is a concrete answer to the interview question of how to ground an LLM recommender in a real catalogue and use it for discovery rather than repeat consumption.
YouTube's PLUM adapts pre-trained LLMs for generative retrieval
PLUM tokenises videos as semantic IDs, continues pre-training a language model on domain data, then fine-tunes it to generate the semantic IDs of videos to recommend from user context. The authors report substantial retrieval gains over a heavily tuned production model built on large embedding tables, plus a scaling study and the serving work needed for YouTube’s scale. Expect questions on reusing an LLM backbone instead of training ID embeddings from scratch.
Kuaishou's OneRec replaces the recommendation cascade
The OneRec technical report describes an end-to-end encoder–decoder recommender, aligned with a reward model through reinforcement learning, that handles 25% of requests in the Kuaishou apps. It reports training and inference MFU of 23.7% and 28.8%, operating cost at 10.6% of the traditional pipeline and App Stay Time gains of 0.54% and 1.24%; OneRec-V2 later moved to a lazy decoder-only design scaled to 8B parameters. It is the reference case when interviewers ask whether retrieve-then-rank is still the right architecture.
Pitfalls
- Training and evaluating only on logged impressions, then trusting offline gains that reflect the old policy’s exposure.
- Running IPS on logs from a deterministic policy or without logged propensities.
- Reporting nDCG without stating the gain convention, cut-off and handling of queries with no relevant items.
- Using in-batch negatives without a popularity correction, which suppresses popular items.
- Optimising click-through alone and creating clickbait or filter bubbles; add satisfaction and diversity guardrails.
- Letting an LLM generate free-text titles that must then be fuzzy-matched to the catalogue; ground it on retrieved catalogue IDs or decode semantic IDs constrained to valid items (Spotify’s Text2Tracks found artist-and-title IDs worse than learned semantic IDs).
How interviewers probe it
- Define NDCG@k, MAP and MRR precisely, then explain why an offline NDCG winner can lose online.
- Design a feed or ‘more like this’ system end to end: stages, models, features, latency, evaluation.
- Estimate a new policy’s performance from old logs; what must have been logged and what breaks IPS?
- Cold start for new users and new items, and how you would measure those cohorts separately.
- Add an LLM to an existing recommender (free-text playlist or search) without discarding the ranking stack.
- Generative retrieval versus two-tower ANN: how semantic IDs are built, collisions and invalid IDs, cold start, decoding latency, and how you would test it against the incumbent retriever.
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Define NDCG@k, MAP and MRR. Why might a model that wins on offline NDCG lose in an online A/B test?
Model answer, written in a candidate's voice
- NDCG@k: graded gains, log2(i+1) discount, DCG/IDCG per query with IDCG from the ideal ordering of all judged items, averaged over queries
- MAP: per-query average precision over relevant items, averaged over queries
- MRR: per-query reciprocal rank of first relevant item, averaged over queries
- Offline NDCG can be biased by old-policy exposure and position bias
- Offline metrics miss diversity, novelty, latency, and long-term satisfaction
- Fixes: IPS/counterfactual evaluation, interleaving, guardrails, longer-horizon metrics
How can you estimate a new recommendation policy’s performance from logs collected by the old policy?
Model answer, written in a candidate's voice
- Log the chosen action, its outcome and its propensity under the old policy (ideally the full action distribution).
- Use IPS for unbiased off-policy value, self-normalised IPS for lower variance, and doubly robust estimators, which stay consistent if either the propensities or the outcome model is right.
- Expect variance blow-up when old and new policies differ; clip or truncate weights and check effective sample size.
- Replay for bandits: keep only logged events where the candidate picks the logged action and average their rewards; unbiased under uniformly random logging, otherwise reweight.
- Keep some exploration in the old policy and log it, because counterfactual estimation needs overlap and known propensities.
How do you recommend to brand-new users, or forecast a brand-new product?
Model answer, written in a candidate's voice
- Initialise from content/metadata and editorial priors, not user history.
- Use onboarding signals to personalize quickly.
- Explore with bandits and transfer from similar items or markets.
- Use hierarchical models to borrow strength across users, items, and segments.
- Measure cold-start cohorts separately from mature users.
You have finished this topic.
Reading
- Recommendation Systems (Google Machine Learning course)Free short course on candidate generation, matrix factorisation, deep retrieval and re-ranking.
- System Design for Recommendations and SearchThe offline/online and retrieval/ranking split, illustrated with industry systems.
- Deep Neural Networks for YouTube RecommendationsThe canonical two-stage deep recommender, including watch-time ranking and training-data choices.
- A Survey on Generative Recommendation: Data, Model, and TasksA 2025 map of LLM-based recommenders, large recommendation models and diffusion approaches, with open problems in evaluation and deployment cost.
- Sampling-Bias-Corrected Neural Modeling for Large Corpus Item RecommendationsTwo-tower retrieval with in-batch negatives and the streaming frequency estimate for logQ correction.
- Unbiased Offline Evaluation of Contextual-bandit-based News Article Recommendation AlgorithmsThe replay method for evaluating bandit policies from logged random traffic.
- Actions Speak Louder than Words: Trillion-Parameter Sequential Transducers for Generative RecommendationsMeta’s HSTU: recommendation as sequence modelling, with scaling results and online gains.
- OneRec Technical ReportKuaishou’s end-to-end generative recommender in production: encoder–decoder generation guided by a reward model, RL, scaling, MFU and operating-cost numbers versus the cascade.
Practise this topic
- Define NDCG@k, MAP and MRR. Why might a model that wins on offline NDCG lose in an online A/B test?
- How can you estimate a new recommendation policy’s performance from logs collected by the old policy?
- How do you recommend to brand-new users, or forecast a brand-new product?
- How would you let users generate a playlist from a free-text prompt while still using the existing recommendation stack?
- How are text-embedding models trained, and which decisions matter when you use them for search — similarity metric, normalisation, dimensionality, domain shift and multilingual content?
- Your team retrieves candidates for a 50-million-item video catalogue with a two-tower model and ANN search. A research group proposes replacing it with generative retrieval over semantic IDs, as YouTube (PLUM) and Spotify (GLIDE) have deployed. How would you build the semantic IDs, serve the model within the retrieval latency budget, and decide whether to ship it?
- Kuaishou’s OneRec replaced the retrieve-then-rank cascade with one generative encoder–decoder, aligned through a reward model and reinforcement learning, and reported operating cost at about a tenth of the cascade. Make the case for and against end-to-end generative recommendation, and say how you would test the idea at a company that runs a mature cascade today.
- Meta trains one LLM-scale ads foundation model (GEM) but serves hundreds of smaller vertical models under tight latency budgets. Design the knowledge-transfer path from a large recommendation foundation model to a production ranker, and explain how you would know the transfer is actually working.