SysDesignAtlas

Ranking & Recommendation Systems

Candidate generation, ranking, and re-ranking — the funnel that picks 10 items out of 100 million in under 100 milliseconds, and why each stage uses a different model.

HLDHard11 min readairankingrecsysretrieval
Confidence

#The constraint that shapes everything

Score 100 million items for one user in 100 milliseconds. A good ranking model takes ~1 ms per item. The arithmetic doesn't work — by six orders of magnitude.

So you don't score everything. You build a funnel, where each stage is cheaper per item and handles more items than the next.

  1. 1 Corpus 100,000,000 items
  2. 2 Candidates ~1,000 · ANN + heuristics · ~10 µs/item
  3. 3 Ranking ~100 · rich model, hundreds of features · ~1 ms/item
  4. 4 Re-ranking ~10 · diversity, business rules, whole-slate
Each stage is ~100× cheaper per item and handles ~100× more items than the next.

#Candidate generation

Get from 100M to ~1,000 with high recall — the right items must be in the set, because nothing downstream can recover an item that was never retrieved. Precision doesn't matter here; ranking handles that.

Real systems run several retrievers in parallel and merge, because each has different failure modes:

SourceMechanismCatches
Two-tower ANNEmbedding similarity between a user vector and item vectorsPersonalised, semantic matches
Collaborative filtering"Users like you also engaged with…"Taste-based, non-obvious matches
Content/tag matchSame category, creator, or topicExplicit interest signals
Trending / popularGlobal engagementCold-start users; the safe fallback
RecencyNewest itemsFreshness-sensitive feeds
Follow graphItems from followed entitiesSocial products, and usually the strongest source there

The two-tower model is the workhorse, and its odd shape exists for one reason: the item side must be computable in advance. Two separate networks — one turning a user into a vector, one turning an item into a vector — that only meet at the very end, in a single similarity comparison. Because they never interact before that point, you can embed all 100 million items overnight and, at request time, embed only the user and search.

   TWO-TOWER (dual encoder)

     user features ──► user tower ──► user vector (256-dim)
                                              │
                                        dot product / cosine
                                              │
     item features ──► item tower ──► item vector (256-dim)

   The towers never interact until the final dot product.
   That separation is the entire point:

     · item vectors are computed OFFLINE for all 100M items
       and loaded into an ANN index
     · the user vector is computed ONCE per request
     · retrieval is then a nearest-neighbour lookup

The towers are trained with in-batch negatives: for each user in a training batch, the item they actually engaged with is the positive example, and the other users' items in the same batch serve as negatives the model must score lower. It's the same contrastive setup as embeddings, with users and items in place of queries and passages.

The cost of that separation is the same as with bi-encoders in retrieval: the model never sees user and item together, so it cannot learn interactions between them. That's what ranking is for.

#Ranking

Now you have 1,000 candidates and a budget of roughly a millisecond each. You can afford a model that sees user and item jointly, with hundreds of features.

   FEATURES AT RANKING TIME

     user      demographics, long-term interests, recent
               activity, session context, device
     item      content features, age, creator, historical
               engagement rates, quality score
     CROSS     ← where the signal is
               user's past engagement with this creator,
               with this topic, at this hour;
               similarity between the user vector and item
               vector; how many of the user's follows
               engaged with this item
     context   time of day, session length, position on
               the page, what was just shown

Cross features carry most of the predictive power. "This user has watched 40 videos from this creator" is far more informative than any user feature or item feature alone — and it's exactly what the two-tower model structurally cannot express.

Multi-task is standard. A single model predicts several outcomes at once: probability of click, of a long dwell, of a like, of a share, of a report. Sharing a representation across tasks improves all of them, and it lets the final score be a weighted combination:

   score = w₁·P(click) + w₂·P(long_dwell) + w₃·P(share)
                                          − w₄·P(report)

   The weights are a PRODUCT decision, not a modelling one.
   They encode what the business considers valuable, and
   changing them changes the product's character far more
   than a model improvement will.

#Re-ranking

The top 100 are individually good. That doesn't make a good slate — the set of items shown together on one screen.

Diversity. Ten near-identical items is a worse experience than eight good ones plus two different ones, even though the greedy ranking says otherwise. Maximal Marginal Relevance is the standard tool: score = λ·relevance − (1−λ)·max_similarity_to_already_selected. Items are picked one at a time, and each candidate is penalised for resembling anything already picked; λ sets the balance between relevance and variety.

Business rules. Sponsored placement, freshness quotas, creator diversity limits, regulatory constraints, and content policy — none of which the ranking model knows about.

Position effects. Users click position 1 far more than position 5 regardless of relevance. Training on click data therefore teaches the model that whatever was shown first is good — a feedback loop. Two fixes:

  • Position as a feature. Include position as a training feature, so the model learns how much of each click was due to position alone. At serving time, set it to the same constant for every item, so they're compared on relevance alone.
  • Inverse-propensity weighting. Weight each training click by how unlikely the item was to be seen in its slot — a click at position 8, where few people look, counts for more than a click at position 1.

Whole-slate optimisation. Rather than picking the top 10 independently, score the set. Expensive and better, and mostly used where the slate is small and valuable.

#Cold start

CaseApproach
New userPopular and trending items; onboarding interest selection; contextual signals (locale, device, referrer); explore aggressively
New itemContent-based features; a deliberate exploration budget; borrow signal from similar items
New systemContent-based only until you have interaction data; consider importing a public dataset for bootstrapping

Exploration is mandatory, and it costs. A system that only shows what it already believes is good never learns whether anything else was better, and its data narrows. Allocate a percentage of impressions to exploration — epsilon-greedy (show a random item some fixed small fraction of the time) is fine; Thompson sampling (show items in proportion to how likely they are to be the best, given how uncertain you still are about them) is better — and treat the cost as the price of not degrading over time. The feedback loop hazard is the same one classical ML systems face, here at much higher volume.

#Generative recommenders

Since 2024, large platforms have been testing a different shape. Treat each user's history as a sequence of actions and train a transformer to predict the next one, the way a language model predicts the next token. Meta's HSTU work (ICML 2024) scaled such "sequential transducers" to over a trillion parameters and found that recommendation quality kept improving with compute — a scaling law, like language models. Google's TIGER (2023) gives every item a semantic ID, a short sequence of codes learned from its content, so a model can generate candidate items directly instead of looking them up.

The funnel doesn't disappear. These models usually slot in as a stronger retrieval or ranking stage, and they inherit every concern on this page — cold start, position bias, the choice of objective — while adding the serving cost of a large sequence model at feed scale.

#The infrastructure

   OFFLINE (hourly to daily)         ONLINE (per request)

   train ranking model               fetch user features        ~5 ms
   compute item embeddings           candidate generation      ~10 ms
   build the ANN index                 (parallel retrievers)
   precompute item features          fetch candidate features  ~10 ms
   push to the online store          rank (batched on GPU)     ~30 ms
                                     re-rank + rules            ~5 ms
                                     log everything for training

Two things dominate the online latency budget and are easy to underestimate:

Feature fetching. Ranking 1,000 candidates with 200 features each is 200,000 feature lookups. This must be a batched multi-get against the online store, and it is frequently the largest single term in the budget — bigger than the model.

Logging. Every impression, its features, its position, and the resulting interaction must be logged, or you have no training data for tomorrow's model. At millions of impressions per minute this is a serious data pipeline in itself, and logging the features as they were at scoring time — rather than recomputing them later — is what prevents training/serving skew.

#Check yourself

Why do recommenders use a funnel?Show answer
Scoring 100M items at 1 ms each takes ~28 hours. Candidate generation (~1,000 by ANN), ranking (~100 with a rich model) and re-ranking (~10) fit in ~45 ms.
What does candidate generation optimise, and how?Show answer
Recall — an item never retrieved can't be recovered. Run several retrievers in parallel (two-tower ANN, collaborative filtering, content, trending, recency, follow graph) and merge.
Why does the two-tower model have its shape?Show answer
User and item towers meet only in a final dot product, so all item vectors can be computed offline into an ANN index — at the cost of never learning user–item interactions.
What carries most of the ranking signal?Show answer
Cross features — the user's past engagement with this creator or topic, user–item similarity, follows who engaged — which two-tower retrieval can't express.
What is multi-task ranking, and who sets the weights?Show answer
One model predicts click, long dwell, like, share and report; the final score is a weighted sum. The weights are a product decision that shapes the product's character.
Why does optimising CTR degrade a product?Show answer
It rewards clickbait and outrage, raising short-term clicks while 30-day retention falls. Weight deep engagement and negative signals, and measure long-term outcomes in holdouts.
What does re-ranking handle?Show answer
Diversity (MMR), business rules, position bias (position as a feature set to a constant at serving, or inverse-propensity weighting) and whole-slate quality.
What dominates online latency, and how is skew prevented?Show answer
Fetching hundreds of features for ~1,000 candidates — batch multi-gets often outweigh the model. Log features as they were at scoring time to build training data without skew.

#What to carry forward

  • The funnel exists because flat scoring is six orders of magnitude too slow. Each stage is cheaper per item and handles more of them.
  • Candidate generation optimises recall; ranking optimises precision. Run several retrievers in parallel.
  • Two-tower separation enables offline item embeddings and structurally prevents learning interactions.
  • Cross features carry most of the ranking signal.
  • Optimising CTR degrades the product. Weight deep engagement and negative signals; measure retention in holdouts.
  • Re-ranking handles diversity, business rules, and position bias — none of which the ranker knows.
  • Feature fetching often dominates the latency budget, and logging features at scoring time is what prevents skew.
00:00
/ 11m