LearnTopic guide

Recommendation and ranking systems

Recommendation questions appear in MLE loops at marketplaces, media and retail companies and increasingly in applied LLM loops where an LLM sits on top of an existing ranking stack. Interviewers expect the multi-stage architecture (candidate generation, ranking, re-ranking), the standard models (matrix factorisation, two-tower retrieval, deep ranking models with multi-task heads), the ranking metrics and their exact definitions, and why offline wins often fail online: logged data are biased by the policy that produced them. Strong candidates can estimate a new policy from logs, handle cold start and explain where generative recommenders fit: since 2025, generative retrieval over semantic IDs and end-to-end generative models have reached production at Kuaishou, YouTube and Spotify, and LLM-scale recommendation foundation models such as Meta’s GEM now teach the smaller models that actually serve traffic.

ML engineering · Applied LLM · Research8 key concepts8 questions

Start: Key concepts 6 lessons · about 17 min
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

How a request moves through candidate generation, ranking and re-rankingThe diagram shows offline jobs training models and building embeddings and indexes, while an online request enters candidate generation with millions of items. Cheap models narrow the set to hundreds, the heavy ranker scores them with rich features, and re-ranking applies diversity, freshness, business rules and fairness constraints before the served items leave.Offline jobstrain models and build indexesEmbeddings andindexesembeddings andindexesRequestCandidate generationcheap modelsRankingrich features and a heavy modelRe-rankingdiversity, freshness, rules, fairnessServed itemsbuildtrained modelsembeddings and indexesmillions of itemshundreds12345OfflineOnlineOutput
  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.

A request is narrowed from millions of items to hundreds, scored by a heavy ranker, then re-ranked before serving.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Offline buildOffline jobs train models and build embeddings and indexes.
2Request entersA request enters candidate generation with millions of items.
3NarrowingCheap models narrow millions of items to hundreds.
4ScoringThe heavy ranker scores the hundreds with rich features.
5Re-rankingRe-ranking applies diversity, freshness, business rules and fairness constraints.

Source: This page's text

Boxes
BoxGroupDetail
Offline jobsOfflinetrain models and build indexes
Embeddings and indexesOfflineembeddings and indexes
RequestOnline
Candidate generationOnlinecheap models
RankingOnlinerich features and a heavy model
Re-rankingOnlinediversity, freshness, rules, fairness
Served itemsOutput

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

How generative retrieval decodes the next itemThe flow runs left to right: a user history enters the generative model, which decodes the next item as a semantic ID built from an RQ-VAE with three levels of 256 codes plus a collision-breaking token. The decode is constrained to valid IDs with a prefix trie, then the ID is mapped back to a catalogue item.user historysequence ofpast itemsgenerativemodeldecodes nextitemsemantic ID3 levels x 256codes + collisiontokencatalogueitemnext item servedvalid IDs onlymap1234InputDecodeOutput
How generative retrieval decodes the next itemThe flow runs left to right: a user history enters the generative model, which decodes the next item as a semantic ID built from an RQ-VAE with three levels of 256 codes plus a collision-breaking token. The decode is constrained to valid IDs with a prefix trie, then the ID is mapped back to a catalogue item.user historysequence of past itemsgenerative modeldecodes next itemsemantic ID3 levels x 256 codes + collisiontokencatalogue itemnext item servedvalid IDs onlymap1234InputDecodeOutput
  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.

A user history is decoded into a semantic ID, constrained to valid IDs, and mapped back to a catalogue item.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Read historyThe user history is read as a sequence.
2Decode next itemThe generative model decodes the next item as a semantic ID.
3Keep IDs validBeam search is constrained to valid IDs with a prefix trie, so invalid IDs are not served.
4Map to catalogueThe valid semantic ID is mapped back to a catalogue item.

Source: This page's text

Boxes
BoxGroupDetail
user historyInputsequence of past items
generative modelDecodedecodes next item
semantic IDDecode3 levels x 256 codes + collision token
catalogue itemOutputnext item served

Source: This page's text

Next: Worked examples Lesson 3 of 6 · about 5 min

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

How logged events become an off-policy estimateThe flow starts with logged events and propensities, moves through IPS and variance-reducing variants, then checks effective sample size before deciding whether to test online. It shows why an offline estimate is promising but not proof.Logged eventsrewards + propensitiesIPS reweightingπ_new(a|x) / π_log(a|x)SNIPS, clipping, robusttrade bias for lower varianceEffective sample size(Σw)² / Σw²A/B testpromising, not proofstochastic loggerhigh varianceweightspromising1234InputEstimateDecide
  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.

Logged events are reweighted by the new policy, checked for variance, and turned into a decision to run an A/B test.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Check the logsUse only logs from a stochastic logging policy with propensities logged.
2ReweightIPS reweights logged rewards by π_new(a|x) / π_log(a|x); unbiased but high-variance when policies differ.
3StabiliseSNIPS, weight clipping and doubly robust estimators trade a little bias for much lower variance.
4DecideCheck effective sample size and compare with the logging policy; if promising, run an A/B test.

Source: This page's text

Boxes
BoxGroupDetail
Logged eventsInputrewards + propensities
IPS reweightingEstimateπ_new(a|x) / π_log(a|x)
SNIPS, clipping, robustEstimatetrade bias for lower variance
Effective sample sizeEstimate(Σw)² / Σw²
A/B testDecidepromising, 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.
Next: What changed Lesson 4 of 6 · about 2 min

What changed recently

  1. 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.

    Source

  2. 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.

    Source

  3. 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.

    Source

  4. 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.

    Source

Next: Pitfalls and interview angles Lesson 5 of 6 · about 2 min

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.
Next: Quiz Lesson 6 of 6 · about 3 min

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.

  1. Question 1 of 3 · ML engineering · Technical · Medium

    Define NDCG@k, MAP and MRR. Why might a model that wins on offline NDCG lose in an online A/B test?

  2. Question 2 of 3 · ML engineering · Technical · Hard

    How can you estimate a new recommendation policy’s performance from logs collected by the old policy?

  3. Question 3 of 3 · ML engineering · Technical · Medium

    How do you recommend to brand-new users, or forecast a brand-new product?

Reading

Practise this topic

  1. Define NDCG@k, MAP and MRR. Why might a model that wins on offline NDCG lose in an online A/B test?ML engineering · Technical · Medium
  2. How can you estimate a new recommendation policy’s performance from logs collected by the old policy?ML engineering · Technical · Hard
  3. How do you recommend to brand-new users, or forecast a brand-new product?ML engineering · Technical · Medium
  4. How would you let users generate a playlist from a free-text prompt while still using the existing recommendation stack?Applied LLM · System design · Hard
  5. 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?Applied LLM · Technical · Easy
  6. 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?ML engineering · System design · Hard
  7. 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.Research · Technical · Hard
  8. 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.ML engineering · System design · Hard

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.