Design a News Feed Ranking System
Understanding the Problem
📰 What is news feed ranking? A social feed (Facebook, LinkedIn, the X home timeline) shows posts from the people, pages and groups you're connected to, plus some recommended posts from outside your network. Since the last time you opened the app, your network produced far more posts than you'll scroll through, often a thousand or more. Feed ranking decides which of them you see and in what order, trading off what you'll engage with, what you'll value, and what the platform wants less of (clickbait, misinformation).
Compared with a short-video feed like TikTok's, three things are different. Most candidates come from the user's own social graph, not from the whole corpus. Posts are many types (text, photos, links, videos, reshares, event updates), each with different engagement patterns. And the platform has explicitly multiple objectives, some of which pull against raw engagement.
The infrastructure for collecting candidate posts (fan-out on write vs read, timeline caches) is covered in Design Twitter and Design Instagram. Here we focus on ranking.
Functional Requirements
Core Requirements
- The system should rank posts from the user's friends, followed pages and groups, plus recommended posts from outside their network, into a personalized feed.
- Ranking should balance multiple objectives: engagement (likes, comments, shares), time well spent, meaningful interactions between people, and integrity (less clickbait, borderline content and misinformation).
- The feed should respect explicit preferences: favorites, snooze, unfollow, "show me less like this", hide.
- The feed should be fresh: a close friend's post should appear within seconds, and posts the user has already seen shouldn't come back unless something new happened (a friend commented on it).
Below the line (out of scope)
- Fan-out and timeline storage.
- Ads in the feed (a separate auction; see Ads Ranking).
- Comment ranking within a post, notifications.
- The integrity classifiers themselves (we consume their scores).
Non-Functional Requirements
Core Requirements
- 1 billion daily active users, each loading the feed about 10 times a day: 10 billion feed requests a day, ~115,000 QPS on average and around 300,000 QPS at peak.
- Each request ranks around 1,500 unseen candidate posts; the user scrolls through maybe 30 to 50 of them.
- The first page of the feed should be ranked in under 300 ms at p99.
- Freshness: new posts are eligible within seconds, engagement counters update within a minute, and the ranker model updates at least daily.
- Safety: integrity demotions are always applied; ranking must never promote content that policy says to reduce.
Below the line (out of scope)
- Global consistency of seen state across regions.
At peak, 300,000 requests × 1,500 candidates is 450 million candidate scorings per second. With a heavy multi-task model that's a large but realistic GPU fleet, provided a cheap pre-ranker trims the 1,500 to ~500 first.
The more important number is the ratio: we show 3% of the inventory. Ranking isn't nudging an order, it's deciding which 50 of 1,500 posts exist for this user today. A friend's post ranked 400th is, in practice, never seen. That's why the choice of objective is the real design question here.
If you remember one thing: the ranker doesn't decide what's "best". It predicts what will happen if we show a post, and a separate value model, owned by product and tuned by experiments, decides how much each outcome is worth. Keeping those two separate is what makes multi-objective ranking manageable.
Framing It as an ML Problem
ML Objective
The business objective is long-term: people keep using the product and feel it's worth their time. Measurable proxies are daily active users, sessions per user, and retention. None of these can be attributed to one post.
So the ranker predicts per-post outcomes, each of which we can label:
- Positive engagement: P(like), P(comment), P(share), P(click), P(dwell > 10 s), P(follow author), P(friend replies to your comment).
- Negative: P(hide), P(report), P(unfollow author), P(see less).
- Satisfaction: P(user rates "worth your time" in a survey). Rare but valuable.
And a value model combines them:
value(post) = Σ_i w_i · P_i(post) − Σ_j v_j · P_j^negative(post)
score(post) = value(post) × integrity_multiplier(post) × preference_multiplier(post)
The weights encode what the platform cares about: a comment between friends is usually weighted far above a like, and a share above both. Integrity multipliers (< 1 for borderline content) and preference multipliers (> 1 for favorites, ~0 for snoozed authors) are applied on top.
Inputs and Outputs
- Input: viewer, their connections and preferences, request context, and the candidate posts with their authors and current engagement.
- Output: an ordered list of posts for the first page (and a cursor for the next), each with its predicted outcomes logged for training and analysis.
Choosing the ML Approach
Pointwise multi-task ranking with a value model on top:
- Inventory: gather unseen posts from connections (from the fan-out cache), recommended posts from retrieval, and older posts with new activity from friends.
- Pre-ranking: integrity filters and a light model reduce ~1,500 to ~500.
- Ranking: a multi-task deep model predicts every outcome for each of the ~500.
- Value model: combine predictions into one score.
- Final pass: diversity, dedupe, rules (don't show three posts from one page in a row), and interleaving with ads.
Pointwise prediction plus a value model is the standard choice for feeds because it decouples learning from preferences. You can change what you want (the weights) without retraining, you can add a new objective by adding a head, and every head is a calibrated probability you can monitor on its own.
Data and Labels
Sources
- Impressions: viewport-level logs of which posts were actually on screen and for how long. A post that was in the response but never scrolled to isn't a negative.
- Actions: like (and reaction type), comment, share, click, video play, profile visit, follow, hide, report, unfollow, snooze.
- Dwell time per post, from the client.
- Surveys: a small, random sample of users is asked about specific posts they saw ("Was this worth your time?"). Hundreds of thousands of answers a day, compared with billions of impressions.
- Graph: friendships, follows, group memberships, interaction history between viewer and author.
- Content: post type, text, images, link domain, author, integrity classifier scores.
How labels are produced
Each head has its own label: like = 1 if the viewer liked within the session (or within an hour), and so on. Delayed actions matter more here than in video: a comment can come an hour later when the viewer returns to the post. We hold examples for a join window (say 1 hour) before emitting them, and accept a small fraction of late labels as noise.
Survey labels are the closest thing we have to ground truth for satisfaction. They're too sparse to train the main model on, but they work well to train a dedicated head on a lightly weighted task, to evaluate value-model weightings, and to check that engagement predictions still track what people say they want.
Class imbalance. Likes happen on a few percent of impressions; comments and shares on well under 1%; reports on a tiny fraction. Rare heads get their own negative downsampling and correction, so they don't get drowned out.
Label leakage. Engagement counters ("this post has 240 likes") are strong features, and they leak if computed after the impression. Log the exact values used at serving time and train on those.
Position bias applies here too: the first few feed slots get much more attention. Log position, feed it as a training-only feature, and evaluate with it held fixed. Otherwise the model learns to predict "we ranked it first" instead of "the user wanted it."
Feature Engineering
Viewer features
- Activity level, preferred content types (some people only click links, others only watch video), language, device.
- Typical actions: heavy commenters vs silent scrollers. This matters for the value model as much as for prediction.
Author and viewer × author features (the strongest group)
- Tie strength: how often the viewer has liked, commented on, messaged, or visited the author's profile in the last 7, 30 and 90 days; whether they're tagged in photos together; mutual friends.
- Whether the author is a close friend, family (declared), a favorite, a page, a group member, or a creator the viewer follows.
- The author's historical engagement rate from this viewer and from everyone.
Post features
- Type (text, photo, link, video, reshare, life event), age, length, language.
- Content embeddings from text and image encoders, for topic matching with the viewer's interests.
- Early engagement velocity: likes and comments in the first minutes, overall and from the viewer's friends.
- Integrity scores: engagement-bait classifier, borderline-content score, misinformation label, link domain quality.
- Whether a friend of the viewer has commented on or reshared it.
Context features
- Time since last session (a returning user after three days wants catch-up; someone refreshing every 10 minutes wants new), time of day, position in the feed, device and network.
Real-time vs batch
- Batch (daily): tie-strength features, viewer and author profiles, interest embeddings.
- Streaming (seconds to a minute): post engagement counters and velocity, friend-activity on posts, viewer's in-session actions.
All of it lives in a feature store, with the per-request feature log written by the ranking service.
Modeling
Ranking Model
Bad Solution: Chronological or a Hand-Tuned Formula
Approach
Show posts newest first. Or the slightly smarter version that early social networks used: score = author affinity × post-type weight × time decay, with the three factors hand-tuned.
Challenges
Chronological is easy to explain and some users ask for it, so offer it as an option. As the default, it means whoever posts most wins: a page that posts 40 times a day buries your sister's wedding photos. A hand-tuned formula is better, but it has three knobs for a problem with thousands of signals, and every tweak is guesswork.
Good Solution: Separate Models per Objective
Approach
Train a GBDT or logistic regression per outcome (P(like), P(comment), P(share), P(hide)), each on its own label with hand-built features. Combine them with the value model.
Challenges
It works, and it's how many feeds evolved. But each model has its own feature pipeline and training job. Rare objectives (share, report) have little data and can't benefit from what the like model learned about the viewer. Running several models per candidate also multiplies serving cost.
Great Solution: One Multi-Task Deep Model
Approach
A single deep model with a shared representation and a head per outcome:
- Embeddings for viewer, author, post and sparse attributes; content embeddings for text and image; dense features (counters, tie strength) through an MLP.
- Interaction layers (DCN-v2 or DLRM-style) to learn crosses like "this viewer × close-friend author × photo post."
- Sequence attention over the viewer's recent engagements, with the candidate as the query.
- MMoE or PLE for the heads, so the many tasks share experts without the common ones (like, click) overwhelming the rare ones (share, report).
- Calibrated sigmoid heads, because the value model multiplies them by weights; a head that's 2× overconfident is effectively 2× overweighted.
Challenges
A dozen or more heads means a dozen calibration curves to monitor, and changing the shared bottom can move all of them at once. Adding a new head changes the shared representation for the others, so each change needs its own experiment. Serving a large model on ~500 candidates at 300,000 QPS needs batched GPU inference with the viewer side computed once.
Multi-Objective Ranking: Setting the Weights
This is the part interviewers push on. Given calibrated predictions, how do we decide what a comment is worth relative to a like, or how much a P(hide) should cost?
Bad Solution: Optimize One Metric
Approach
Rank by P(click) or P(like), the metric that's easiest to move.
Challenges
You get engagement bait: "Like if you agree!", outrage, misleading link headlines. Clicks go up for a while, satisfaction drops, and eventually so does usage. Single-metric feeds are the textbook example of optimizing a proxy until it stops measuring what you care about.
Good Solution: A Weighted Sum Tuned by A/B Tests
Approach
Use the value model with weights set by product judgment, then adjust them one at a time through A/B tests against top-line metrics (sessions, time spent, survey scores).
Challenges
A dozen weights interact, so tuning one at a time is slow and gets stuck in local optima. Each test needs a week or more. And the top-line metric you test against can itself be gamed by a weighting that boosts short-term engagement.
Great Solution: Systematic Tuning With Constraints and Long-Term Checks
Approach
- Offline: replay logged sessions with different weight vectors and trace a Pareto frontier: for each level of predicted engagement, the best achievable predicted satisfaction (survey head) and integrity exposure. This rules out clearly dominated weightings cheaply.
- Online: run many small experiments on candidate weight vectors at once and use Bayesian optimization to choose the next batch, maximizing a primary metric subject to constraints ("hides must not increase", "integrity-flagged views must not increase", "friend-content share must stay above X").
- Long-term validation: keep a holdout on the previous weights for months and measure retention and survey scores, which can move in the opposite direction from one-week engagement.
Weights can also be personalized: users who never comment shouldn't have their feed driven by a comment head they'll never trigger, so the value of each action can be normalized by how often this viewer takes it.
Challenges
The constraints are policy decisions (how much short-term engagement is a reduction in borderline content worth?), and the ML system should make those trade-offs visible, not hide them in a weight. Many simultaneous experiments need a solid experimentation platform.
Final Pass
After scoring, a lightweight re-ranking pass turns a sorted list into a good feed:
- Diversity: no more than two posts in a row from the same author or page, a mix of content types, topic diversity via content embeddings.
- Connected vs recommended mix: cap and space out unconnected recommendations so the feed still feels like your network.
- Dedupe: one copy of a viral link even if five friends shared it, with the friend who shared it shown as context ("Alex and 4 others shared this").
- Hard rules: snoozed authors removed, policy removals, age-appropriate filters.
Training
Losses. Binary cross-entropy per head, summed with task weights (the training-loss weights, which balance gradient contributions, are separate from the value-model weights, which express product value). For dwell time, either a binary head on dwell > threshold or a regression on log dwell.
Negatives. Viewed impressions without the action. For rare heads, downsample negatives and correct with p = q / (q + (1 − q) / w).
Cadence. Daily full training on the last few weeks of data, plus incremental updates every few hours so new authors, pages and trending topics are learned. The value-model weights change separately, through config, after experiments.
Scale. 10 billion requests × ~50 viewed posts is 500 billion impressions a day. We sample: keep all rare positives, a fraction of everything else, and a few weeks of history. Embedding tables for a billion viewers and hundreds of millions of authors and pages need sharded, model-parallel training.
Evaluation
Offline Metrics
- Per head: AUC, normalized entropy and calibration, on a time-based split. Watch the rare heads; a regression in P(report) won't show up in an average.
- Value-weighted ranking quality: NDCG where each post's gain is its realized value (the weighted sum of what actually happened). This measures the thing the feed actually optimizes.
- Survey alignment: how well the value score ranks posts that users rated as worth their time.
- Composition: share of friend posts, recommended posts and integrity-flagged posts in the simulated top 50.
Online Metrics and A/B Testing
- Primary: daily active users and sessions per user; time spent with a cap on passive consumption; meaningful interactions (comments and shares between people who know each other).
- Satisfaction: survey "worth your time" score.
- Guardrails: hides, reports, unfollows; views of integrity-flagged content; share of feed from friends; latency.
Feed experiments have network effects. If the treatment shows more friends' posts, those friends (in control or treatment) get more likes and comments, and post more, which changes the control arm's inventory too. User-level randomization underestimates or misreads such effects. Cluster randomization (assign whole friend clusters from a graph partition to the same arm) or author-side measurement fixes it, at the cost of statistical power.
Serving
On each feed request, the Feed Service:
- Pulls unseen posts from the inventory cache (fan-out of recent posts from connections) and removes ones in the seen-state store, unless they have new friend activity.
- Calls unconnected retrieval (two-tower embeddings + ANN index) for recommended posts.
- Sends the merged candidates to the Ranking Service, which fetches features, runs the pre-ranker and the multi-task model, and applies the value weights from config.
- Runs the final pass and returns the first page, with a cursor. Later pages reuse the ranked list, re-scored lightly with in-session actions.
Latency budget for 300 ms at p99:
| Step | Budget |
|---|---|
| Inventory + seen-state + unconnected retrieval, in parallel | ~40 ms |
| Feature fetch for ~1,500 posts (batched) | ~40 ms |
| Integrity filter + pre-rank to ~500 | ~20 ms |
| Multi-task model on ~500 (GPU) | ~60 ms |
| Value model, final pass, ads interleave | ~20 ms |
| Network and slack | the rest |
This is online prediction: the inventory changes every few seconds and the value of a post depends on how much engagement it has right now. A precomputed fallback (yesterday's top posts from close friends) covers ranking outages.
Potential Deep Dives
1) How do we keep engagement bait and harmful content out without losing relevance?
Engagement-optimized models learn to love what people react to, and people react strongly to outrage, sensationalism and bait. The integrity side of ranking:
- Classifiers as inputs. Separate models score each post for engagement bait ("comment YES if…"), clickbait headlines, borderline content (close to violating policy but not over the line), and misinformation as judged by fact-checkers. Their outputs become multipliers in the score, not features in the engagement model. As features, the model would learn that bait gets engagement and rank it up.
- Demotion curves. Borderline content gets a demotion that grows as it approaches the policy line, which reverses the tendency of borderline content to get more engagement the closer it gets.
- Source quality. Link domains with a history of misleading content or ad-farm landing pages get demoted.
- Don't reward raw reactions. Weight comments by whether they're between people who know each other and by comment length, so a pile-on of strangers doesn't count as "meaningful."
Interviewers often ask, "Wouldn't demoting borderline content hurt engagement?" The honest answer is yes, in the short term, and that's exactly why it's a multiplier set by policy and measured with long-term holdouts, not something the engagement model learns.
2) How do we mix connected and recommended content?
Recommended (unconnected) posts help users with small networks and help creators grow, but too many make the feed feel like it's not yours.
- Separate candidate quotas, then rank everything with the same model, so the scores are comparable.
- A recommended-content penalty or cap that depends on the viewer: someone with 30 active friends has a thin connected inventory and gets more recommendations; someone with 800 doesn't.
- Explicit signals: "show me less from this group or topic" and hides on recommended posts are weighted heavily.
- Separate metrics: track satisfaction for recommended posts alone, because a weak recommendation source can hide inside a healthy overall feed.
3) How do we respect explicit user preferences?
Implicit signals are noisy; explicit ones should be trusted more.
- Hard rules: snoozed and unfollowed authors are removed before ranking; "hide post" removes it and similar reshares.
- Strong multipliers: favorites get a large boost and are guaranteed placement near the top when they post.
- "See less of this": a topic or author penalty that decays over weeks, plus a training label for the hide head.
- A chronological or favorites-only view as a product option. It's also a useful long-term holdout: if many users switch to it, the ranked feed isn't serving them.
4) How do we keep the feed fresh between visits?
The right feed after three days away is different from the right feed 10 minutes after the last one.
- Time since last visit is a context feature, and it changes the value weights: catch-up sessions favor important posts from close ties (a life event, a friend's photo album); frequent refreshers get the newest high-score posts.
- Seen state removes posts already viewed, except when a friend has commented or reacted since (bumping), which reranks the post with the new activity as a feature.
- Recency decay lives in the model (post age as a feature) rather than a hand-tuned decay, so the model learns that a news link loses value in hours and a wedding album over days.
- Streaming counters mean a post that's taking off in your network is noticed within a minute.
5) How do we monitor the system?
- Per-head calibration and prediction distributions, by country, content type and surface. A broken head silently skews the value model.
- Feed composition dashboards: share of friend, page, group and recommended posts; share of integrity-flagged views.
- Data quality: event volumes by client version, counter freshness, missing features.
- Weights changes go through the same experiment and rollback process as models, since they change rankings just as much.
What is Expected at Each Level?
Mid-level
You should frame feed ranking as predicting engagement for candidate posts, propose sensible features (especially viewer × author affinity and post engagement counts), choose labels from impressions, start with a GBDT or logistic regression baseline, and evaluate with AUC and an A/B test on engagement. With prompting, you should see why optimizing likes alone leads to clickbait.
Senior
You should design the multi-task model with a separate value model, explain calibration of each head and why it matters, and discuss how weights are tuned through experiments. Expect to cover delayed labels, position bias, integrity scores as multipliers rather than features, the connected vs recommended mix, and a serving pipeline with pre-ranking and a latency budget.
Staff+
You should lead with the objective question: what the platform is trying to maximize, how surveys and long-term holdouts check the proxies, constrained optimization of value weights, and the organizational split between modeling teams and policy owners. Expect to discuss network effects in experiments and cluster randomization, personalization of weights, and the integrity trade-offs with clear reasoning about who decides them.