Design: news feed ranking
Gather ~1,000+ candidates, prune to ~500 with a light model, predict like, comment, share, hide and dwell with a multi-task model, combine them with tunable weights, then re-rank for diversity and integrity.
Fundamentals you'll use
How it works
- Scale: ~2B daily users, ~500k feed requests/s at peak, ranking within ~300 ms p99.
- The value model weights are policy: tune them with A/B arms over weeks, not gradient descent.
- Correct for position bias: an unliked post in slot 30 may never have been seen.
- The worst failure is optimizing an easy proxy like comments; long-running holdouts catch slow decay in retention.
- Measure each funnel stage by its recall of the final top 50, per source.
Check yourself
Answer to mark it learned; your answers aren't scored.
A value-model change raises the weight on comments. A one-week A/B test shows comments clearly up and time spent flat. The PM wants to ship to everyone. What do you do?
Go deeper
Full explanation
Requirements
Functional: rank the posts a user may see (friends, groups, followed pages and creators, plus recommendations from accounts they don't follow) on every app open and scroll; honor hide, snooze and unfollow at once; ads are slotted in by a separate system. Non-functional: ~2B daily users and ~500k feed requests/s at peak (assumed); ranking within ~300 ms p99 server-side; a new post rankable within seconds; degrade to a cached or recency-ordered feed, never an error.
Questions I'd ask:
- What is the north star: time spent, meaningful interactions or long-term retention? It sets the value-model weights and the A/B primary metric.
- Connected content only, or unconnected recommendations too? That changes candidate sources and integrity risk.
- Which integrity rules remove content and which only demote it?
- Must we offer a non-personalized feed (the EU DSA requires one option)?
- How much of the app's load budget does ranking get?
The highest-cost failure is optimizing a proxy that is easy to move: a weight change that lifts comments by surfacing outrage and engagement bait looks green in a one-week test while trust and retention erode for months.
High-level design
- Candidate generation: in parallel, pull recent posts from the user's graph out of an inventory index, plus two-tower recommendations from an ANN indexes: HNSW, IVF, PQ index; dedupe and apply eligibility (privacy, blocks, already seen): ~1,000–2,000 candidates.
- First pass: a light model, distilled from the heavy one (Knowledge distillation), keeps ~500.
- Main pass: a multi-task DNN scores each candidate independently: P(like), P(comment), P(share), P(hide) and expected dwell. Features come from a real-time Feature stores: user, author and post counters, user–author affinity and learned ID embeddings.
- Value model:
V = Σ w_k · ŷ_k, with negative weights on hide and report. The weights are a product decision, tuned by A/B tests on long-term metrics. - Final pass: re-rank the list as a whole: author and format diversity, freshness boosts, integrity demotions.
Learning loop: every impression is logged with its position and the exact features served (Training–serving skew); actions join in streaming (Queues vs streams (Kafka)); models train continuously with position-bias correction, and each head is calibrated so the weighted sum means something (Class imbalance & calibration).
Code Value model and greedy final pass
import numpy as np
# Illustrative weights: a product decision, tuned by A/B tests on long-term metrics
W = {"like": 1.0, "comment": 4.0, "share": 6.0, "dwell_min": 0.5, "hide": -40.0}
def value(p: dict[str, np.ndarray]) -> np.ndarray:
# Every head must be calibrated, or "a comment is worth 4 likes" means nothing
return sum(w * p[k] for k, w in W.items())
def final_pass(items: list[dict], v: np.ndarray, n: int = 25, decay: float = 0.6) -> list[dict]:
v = v * (1 - np.array([it["integrity_demotion"] for it in items])) # 0 = none, 1 = remove
left = v > 0 # negative expected value: never show
feed, per_author = [], {}
for _ in range(min(n, int(left.sum()))):
# Re-score what is left given what is already on the page
adj = np.array([v[i] * decay ** per_author.get(it["author"], 0) for i, it in enumerate(items)])
i = int(np.argmax(np.where(left, adj, -np.inf)))
left[i] = False
feed.append(items[i])
per_author[items[i]["author"]] = per_author.get(items[i]["author"], 0) + 1
return feed
# preds come from the main pass: one batched call per request, all 500 candidates
feed = final_pass(candidates, value(preds))Real example
Juan opens the app at 7:40 pm. Sources return 1,800 candidates in ~40 ms: friends' posts since his last visit, 3 groups, followed pages and 400 two-tower recommendations; eligibility drops 300 already seen or blocked. The first pass keeps 500 (~15 ms); the main pass scores them in one batch (~60 ms). With the code's illustrative weights, his cousin's wedding photo has P(like) 0.42, P(comment) 0.09, P(share) 0.01, 0.4 min of dwell and P(hide) 0.001: V ≈ 1.0, top. A viral meme page has P(like) 0.30, P(comment) 0.02, P(share) 0.05 and 0.2 min, but P(hide) 0.02: V ≈ −0.02, never shown. The final pass demotes repeated authors and lifts a 20-minute-old group post. Total ~180 ms.
Trade-offs +4 · −4
+ You gain
- The funnel spends heavy compute on only ~500 candidates, so latency stays bounded as inventory grows.
- Multi-task heads plus a value model let product change objectives by editing weights, without retraining.
- A shared network gives rare signals (shares, hides) enough data to learn from.
- The final pass handles list-level goals (diversity, integrity) that per-item scores can't express.
− You pay
- Many stages, many models: if the first pass disagrees with the main pass, good posts die early, unseen.
- Value weights have slow, political feedback loops: weeks of A/B tests for every change.
- Heavy infrastructure: TB-scale embedding tables, streaming feature pipelines and hundreds of TB of logs a day.
- Engagement predictions reward borderline content unless integrity models sit in the loop.
Use it when
Large inventories (thousands of eligible items per user), many engagement signals, an objective that blends several outcomes, and a latency budget of a few hundred milliseconds.
Avoid it when
Small or chronological products (team chat, a newsletter with ~100 items), feeds that must be non-personalized, or too little interaction data to train beyond one GBDT ranker.
Numbers to know 5
- Traffic: 2B DAU × 10 feed loads/day (assumed) = 20B requests/day ≈ 230k QPS average, ~500k at a ~2× peak.
- Main pass: 500k QPS × 500 candidates = 250M heavy scores/s at peak; the first pass scores ~3× more items at a fraction of the cost each.
- One user-ID table: 3B rows × 128 dims × 2 bytes (fp16) ≈ 770 GB; add post, author and group tables and you are in TBs, sharded.
- Latency p99 ~300 ms (assumed): candidates 50 + features 40 + first pass 20 + main pass 80 + final pass 20 + network and headroom 90.
- Logs: 20B loads × ~20 viewed posts × ~2 KB of features ≈ 800 TB/day (assumed): downsample non-action impressions and reweight.
Common pitfalls 4
- Uncalibrated heads: after a retrain P(comment) runs 2× high, and comment bait floods the feed without anyone touching a weight. Monitor calibration per head and segment.
- Training on logged impressions without position correction: the model learns that slot 1 is good and freezes the current ranking.
- Judging a weight change on a one-week engagement A/B test: novelty and bait win short-term. Keep long-running holdouts and track retention, hides, reports and survey scores.
- Recomputing features offline instead of logging served values: counters that include the impression itself leak the label, and offline gains vanish online.
Interview questions 3
Answer out loud first, then reveal.
How do you set the weights in the value model?Show answer
They are a product decision expressed as numbers, so I don't let the ranking model learn them. First, every head must be calibrated, or a weight means nothing. Then I run several weight vectors as A/B arms for weeks and measure two layers: short-term proxies like likes, comments, hides and reports, and the north star, such as 28-day retention or survey-rated meaningful interactions. Long-running holdouts tell me which proxies actually predict the long-term metric, and I pick weights on that Pareto frontier with integrity guardrails. Weights live in versioned config with an owner, because changing them is shipping policy.
The new main model is 2× bigger and blows the latency budget. What do you do?Show answer
I'd measure where the time goes before touching the model. Cheap wins first: compute the user side once per request instead of per candidate, score all candidates in one batch, cache hot embedding rows and serve in fp16 or int8. If that's not enough, I shrink the input: a better first pass, distilled from the new model, so the main pass scores 300 candidates instead of 500 at nearly the same recall of the final top 50. I'd plot quality against candidate count to justify the cut. A smaller model is the last resort, and the A/B test decides whether the extra quality is worth the hardware.
How do you know position bias is distorting your training data, and how do you fix it?Show answer
I'd compare action rates for the same posts shown at different positions: if the like rate drops sharply just because a post sat lower, the labels carry position. To measure it cleanly, I randomize the order of the top few slots for a tiny slice of traffic, around 0.5–1%, and estimate the examination probability per slot. Then I fix it in one of two ways: a shallow position tower in training, set to missing at serving, or inverse-propensity weights. Randomization costs some engagement, so I keep the slice small but permanent: it's also my unbiased data for evaluating the next model offline.
Deep dive 5
The funnel and candidate sources
Each stage trades recall for cost. Sources run in parallel with their own quotas: friends and groups from an inventory index of posts since the last visit, followed pages and creators, and unconnected recommendations from a two-tower model (Contrastive learning & CLIP) over an ANN index. Meta reports more than 1,000 eligible posts per user per day on average, and a lightweight pass that keeps ~500 for the main model. Train the first pass to imitate the main pass, not raw clicks: Instagram Explore distills its second-stage ranker into the first stage, so the cheap model learns what the expensive one would keep. Measure each stage by its recall of the final top 50, per source; a source that never survives ranking is wasted latency.
Multi-task model and features
One network, many heads: a shared bottom learns from every action, so rare labels (shares, hides) borrow signal from frequent ones (likes, dwell). When tasks conflict, a Multi-gate Mixture-of-Experts (MMoE) lets each head weight shared experts differently, as YouTube does in its watch-next ranker. Inputs follow the DLRM pattern (Neural networks & backpropagation): sparse IDs (user, author, post, group) become embeddings, dense counters (author like rate, user–author interactions over 28 days, post velocity over 10 minutes) go through an MLP, then explicit feature interactions. Counters come from streaming jobs into the Feature stores; post velocity must be seconds-fresh, affinity can be hourly. Thousands of features are normal (Feature engineering & data leakage); every one must be logged at serving time, or training sees different values than serving did.
Training data: position bias and calibration
Logs only contain what the old model showed, in the order it showed it. An unliked post in slot 1 is a real negative; in slot 30 the user may never have looked. Correct for it: feed position into a shallow tower that is added to the logit in training and set to missing at serving (YouTube's approach), or reweight by examination propensity measured on a small randomized slice. A non-action becomes a negative only after a window closes; too short, and late likes turn into false negatives. Then calibrate each head on recent data, with isotonic regression or Platt scaling per surface and country, and alert when Σ predicted / Σ actual leaves ~0.95–1.05. Split train and test by time and retrain continuously (Learning to rank (LTR)).
Value model and long-term metrics
The heads predict; the value model encodes what the company wants. Meta describes its feed score as a weighted sum of predictions and uses surveys asking people how meaningful an interaction was to decide which actions count most. Instagram Explore publishes the same shape: W_click·P(click) + W_like·P(like) − W_see_less·P(see less). Tune weights by experiment, not gradient descent: run several weight vectors as A/B arms, measure short-term proxies (likes, comments, hides) and the north star over weeks, and keep long-running holdouts to catch slow decay (A/B testing LLM features, Offline vs online evaluation). Integrity is a separate model whose scores demote or remove in the final pass, so a weight change can't trade it away. Keep the weights in versioned config with an owner: they are policy.
Scale, latency and fallbacks
At ~500k requests/s × 500 candidates, the main pass is ~250M scores per second, so serving runs on GPUs or accelerators with all of a request's candidates in one batch. Compute the user side once per request (user embedding and counters) and broadcast it over the 500 candidates, never 500 times. Embedding tables reach TBs: shard them across parameter servers, cache hot rows on inference hosts, serve in fp16 or int8. Budget (p99 ~300 ms, assumed): candidates 50 ms in parallel, features 40, first pass 20, main pass 80, value and final pass 20, the rest network and headroom. On timeouts, degrade by stage: skip the final pass, then rank by first-pass score, then serve a cached feed (SLIs, SLOs & error budgets). A slightly worse feed beats a spinner.