ML System Design · Module 14 of 47 · 10 concepts · about 12 min

Ranking and Multi-Stage Systems

How the final order of results is decided: the cascade of increasingly accurate stages, the three ways to learn to rank, the features rankers use, balancing several goals, re-ranking for variety and rules, exploration, and serving a ranker within its budget.

At work: The core of search, feeds, recommendations and ads, where most of the measurable business value of ML at consumer companies is created.

The ranking cascade

What it is

Large ranking systems pass items through several stages, each more accurate and more expensive per item than the last:

  • Retrieval: thousands of candidates from the whole catalogue, in milliseconds.
  • Light ranker (pre-ranking): a small, fast model cuts thousands to hundreds.
  • Heavy ranker: the most accurate model scores the hundreds.
  • Re-ranking: rules and adjustments (variety, freshness, business limits) produce the final list.

Why it matters

Each stage spends effort only where it matters.

  • The expensive model sees only items that are already plausible.
  • The total time fits the budget even though the heavy model alone could never score the whole catalogue.
  • Stages can be improved independently, each with its own measure.

In the real world: Meta, Pinterest and TikTok describe cascades of three or four stages; Kirana Kart, with a smaller catalogue, uses the four shown here.

Visual example

Computed

Kirana Kart's home-screen cascade. Each stage is costlier per item and sees fewer items: about 62 ms in all.

Illustrative per-item costs; retrieval and re-ranking given as totals
stageitems initems outms per itemstage time
Retrieval (ANN + sources)50,0002,000—10 ms
Light ranker2,0005000.00510 ms
Heavy ranker500500.0840 ms
Re-ranking and rules5020—2 ms

Retrieval and the light ranker together fit the 20 ms that module 4 gave to finding candidates; the heavy ranker's 40 ms is its ranking budget.

Training each stage on its own without thinking of the next. A light ranker that optimises a different goal from the heavy ranker throws away items the heavy ranker would have put first.

Practise it: Design a Recommendation System, Design a Personalized News Feed

Learning to rank

What it is

Three ways to train a ranking model, by what one training example is:

  • Pointwise: one item. Predict its score (will it be added?) and sort by it. Simple; most common.
  • Pairwise: two items. Learn which of the pair should be higher. Closer to what ranking needs. Example: RankNet, LambdaRank.
  • Listwise: a whole list. Optimise a list measure such as NDCG directly. Example: LambdaMART, listwise softmax losses.

Why it matters

Pointwise is often good enough and gives calibrated probabilities that can be combined with other goals.

  • Pairwise and listwise focus training on getting the order right at the top, which can improve the measures that matter for search.
  • LightGBM and XGBoost offer LambdaMART-style ranking objectives with one setting.

In the real world: Web search engines long used LambdaMART-style boosted-tree rankers; Kirana Kart's search uses LightGBM's lambdarank objective with graded labels.

Visual example

LTR

Pointwise is the common default; listwise when top-of-list order is everything.

Pointwise, pairwise and listwise compared
approachone example islearnsstrengthweakness
PointwiseOne itemA score per itemSimple; calibratedIgnores the other items
PairwiseTwo itemsWhich is betterFocuses on orderMany pairs; scores not probabilities
ListwiseA whole listThe best listOptimises NDCG-like goalsMore complex to train
import lightgbm as lgb

# One row per (query, product); group = how many rows belong to each query.
ranker = lgb.LGBMRanker(objective="lambdarank", n_estimators=500)
ranker.fit(
    X_train, y_train,            # y = graded relevance: 0 shown, 1 clicked, 2 added, 3 bought
    group=query_sizes_train,
    eval_set=[(X_val, y_val)], eval_group=[query_sizes_val],
    eval_at=[10],
)

Using a pairwise or listwise model and then treating its scores as probabilities. Their scores only order items; they cannot be combined with prices or other models' probabilities without calibration.

Practise it: Design a Search Ranking System

Features for ranking

What it is

Rankers combine four groups of features:

  • User: history, preferences, segment, embedding.
  • Item: category, price, popularity, quality, embedding.
  • User-item: how this user relates to this item. Bought it before? Similarity of embeddings? Bought from this brand?
  • Context: time, day, device, location, what is in the basket, the search query.

Why it matters

The user-item features are usually the most powerful, and they are what the ranker can do that two-tower retrieval cannot.

  • 'This user bought this exact item four times' beats any general signal.
  • Context changes what is relevant: breakfast items in the morning, party snacks on Friday evening.

In the real world: In Kirana Kart's ranker, 'times this customer bought this product' and 'days since they last bought it' are the two most important features.

Only using features that describe the item. The ranker then orders everyone's list the same way, which is popularity with extra steps.

Practise it: Design a Recommendation System, Design a Personalized News Feed

Balancing several goals

What it is

Ranking usually serves several goals at once: engagement, revenue, long-term satisfaction. Common approach:

  • predict each goal separately (or with a multi-task model): probability of adding, margin, chance of returning;
  • combine them into one score with weights the business sets;
  • test different weights with online experiments.

Why it matters

Optimising one goal alone hurts others.

  • Pure engagement fills the screen with cheap, low-margin items.
  • Pure revenue shows expensive items people do not want, and they stop opening the app.
  • Weights make the trade-off visible and adjustable without retraining.

In the real world: Kirana Kart blends engagement and expected margin at 70:30; an experiment with 50:50 raised margin but cut basket additions enough that overall profit fell.

Visual example

Computed

Five products. Score = 0.7 × (chance of adding, scaled to the best) + 0.3 × (expected margin, scaled to the best). The blend sits between the two pure orders.

Expected margin = chance of adding × margin per unit
productchance of addingexpected margin ₹rank by addingrank by marginblended scoreblended rank
Toned milk 1 L30%1.2150.761
Basmati rice 5 kg8%4.8420.434
Bananas 6 pcs22%1.76240.62
Olive oil 1 L5%6510.425
Chocolate bar15%2.25330.463

Combining raw scores on different scales. A probability (0 to 1) added to a margin in rupees (0 to 120) means the margin decides everything. Normalise, or combine as expected value.

Re-ranking: variety, freshness and rules

What it is

The heavy ranker scores items one at a time. The final list also needs list-level properties, added in re-ranking:

  • variety (diversity): not ten kinds of milk in a row. A method such as MMR picks each next item for a high score and low similarity to items already chosen;
  • freshness: some room for new items;
  • business rules: no out-of-stock items, a cap on promoted items, legal restrictions;
  • de-duplication: one listing per product.

Why it matters

A list of individually best items is often a poor list.

  • Ten near-identical items waste the screen.
  • Users engage more with varied lists, and the system learns more from them.
  • Rules belong here, in readable code, not hidden in the model.

In the real world: Kirana Kart allows at most two products from one sub-category in the top ten, and exactly one promoted slot in positions 3 to 6.

Encoding business rules as model features. 'Never show alcohol to under-21s' must be a hard filter, not a pattern the model may or may not learn.

Practise it: Design a Recommendation System, Design an Image Search System, Design Feature Monitoring, Debug a Production ML Model, Design a Personalized News Feed, Design a Search Ranking System, Design an Ad Ranking System

Exploration

What it is

A ranker trained only on what it chose to show keeps showing the same things. Exploration deliberately shows some items it is less sure of, to learn about them:

  • epsilon-greedy: a small share of the time, put a random candidate in a slot;
  • Thompson sampling and upper confidence bound: favour items whose score is uncertain, because they might be better than thought;
  • reserved slots for new items.

Why it matters

Without exploration the system learns only about what it already believes.

  • New and niche items never get enough exposure to prove themselves.
  • The data becomes narrower over time (a feedback loop, module 22).
  • Exploration costs a little engagement now for better models later; the cost is measured and capped.

In the real world: Many feed and recommendation systems explore on a small single-digit percentage of impressions, and log the probability with which each item was shown for later correction.

Exploring in the top slot. Put exploratory items where they cost little (lower positions, a small share of traffic) and log that they were exploratory, so training can account for it.

Practise it: Design a Personalized News Feed, Design a Search Ranking System

Session and real-time signals in ranking

What it is

What the user is doing right now is often the strongest signal:

  • items viewed or added in this session;
  • the current search query and its refinements;
  • what was just skipped or removed from the basket.

These are on-demand or streaming features (modules 9 and 10), or a sequence model over the session's events.

Why it matters

Intent changes within minutes.

  • Someone who just added pasta wants sauce and cheese now, whatever they usually buy.
  • A ranker using only yesterday's features cannot react.

In the real world: Kirana Kart's basket page ranks 'goes well with' products using the items currently in the basket as features, updated on every change.

Letting one session signal overwhelm everything. One accidental view of baby food should not turn the whole home screen into baby products.

Practise it: Design a Recommendation System, Design a Personalized News Feed

Serving a ranker

What it is

To score hundreds of candidates inside the budget:

  • fetch user and context features once, item features for all candidates in one batched read;
  • score all candidates in one batched call to the model;
  • cache item features and item-only parts of the model;
  • keep a fallback order (popularity, or the retrieval order) if the ranker times out.

Why it matters

Batching is the difference between 40 ms and 400 ms.

  • 500 separate model calls each pay the fixed overhead; one call with 500 rows pays it once.
  • A timeout with a sensible fallback keeps the screen working when the ranker is slow.

In the real world: Kirana Kart's ranking service sets a 60 ms timeout on the heavy ranker; on timeout it returns candidates in retrieval order, which happens on well under 0.1% of requests.

Fetching item features one candidate at a time. 500 lookups at a millisecond each use the whole budget before the model runs.

Interview questions: ranking

What it is

The questions interviewers ask about ranking, from the first screening call to the senior round. Cover the answer, say yours aloud, then compare.

Why it matters

Reading an idea and explaining it are different skills.

  • Each answer below is the two or three sentences an interviewer is listening for.
  • The reasoning behind each one is in the cards above. If an answer surprises you, go back to that card.

In the real world: Feed, search and ad interviews are largely ranking interviews. The cascade and the multi-objective score are the two diagrams most often drawn.

Q: Why use a cascade of rankers?

To spend expensive computation only on plausible items: retrieval narrows thousands, a light ranker cuts to hundreds, a heavy ranker orders those, and re-ranking applies list-level rules. Total time fits the budget.

Q: Pointwise, pairwise or listwise?

Pointwise predicts a score per item and is simple and calibrated; pairwise learns which of two items is better; listwise optimises list measures like NDCG. Pointwise is the usual start; LambdaMART-style objectives when order at the top is everything.

Q: How do you rank for several goals?

Predict each goal separately or with a multi-task model, combine with business-set weights after normalising or as expected value, and tune the weights with experiments.

Q: What happens in re-ranking?

List-level adjustments the item scorer cannot make: diversity (for example MMR), freshness, hard business and legal rules, de-duplication.

Q: Why explore, and how?

To learn about items the model is unsure of and avoid feedback loops: epsilon-greedy, Thompson sampling or reserved slots, on a small, logged share of traffic in low-cost positions.

Q: How do you serve a ranker within 40 ms?

Batched feature reads, one batched model call for all candidates, caching item features, and a timeout with a fallback order.

Describing only one model, with no retrieval, no re-ranking and no word on how goals are combined.

Practise it: Design a Recommendation System, Design a Personalized News Feed, Design a Search Ranking System, Design an Ad Ranking System

Exercise: build a two-stage ranker

What it is

A short build that uses this module's ideas. Write it yourself before looking anything up; the checks at the end tell you whether it works.

Why it matters

An idea you have only read fades in a week.

  • Building it once, even in fifty lines, is what makes it yours.
  • Interviewers can tell the difference between someone who has read about a loop and someone who has debugged one.

In the real world: Ranking take-home tasks at e-commerce and media companies look very much like this.

Your task. Add a learned ranker on top of a retrieval stage and show that it improves the top of the list.

Steps

  1. Start from your retrieval exercise in module 13 (or popularity plus item-to-item candidates).
  2. For each user and time, take the top 200 candidates and label them: 1 if the user engaged with the item in the next period, else 0.
  3. Add user-item features (past interactions with the item's category, embedding similarity) and context features.
  4. Train LightGBM with a lambdarank objective, grouped by user.
  5. Compare NDCG at 10 of retrieval order against ranker order on a later period.
  6. Add an MMR re-ranking step and measure how many distinct categories appear in the top 10, and what it costs in NDCG.

You are done when

  • The ranker beats retrieval order on NDCG at 10.
  • You can state the variety gained and the NDCG given up by re-ranking.

Stretch. Add a second objective (for example item price as a stand-in for margin) and plot NDCG against average price as you vary the blend weight.