---
title: News-feed ranking for a social network
url: https://gurkanozkan.ai/learn/design/mle-news-feed-ranking-for-a-social-network-04/
markdown: https://gurkanozkan.ai/learn/design/mle-news-feed-ranking-for-a-social-network-04.md
kind: design
role: ML engineering
json: https://gurkanozkan.ai/api/learn/design/mle-news-feed-ranking-for-a-social-network-04.json
---

# News-feed ranking for a social network

Rank the posts a user sees when opening their feed.

## Constraints

- 1,000+ eligible candidates per user per day, trimmed to ~500 by a light model
- ~1 s total budget for feed assembly
- billions of users

## What to cover

- **Requirements**: Rank the posts a user sees when opening their feed.
- **Estimates**: about 1,000+ eligible candidates per user per day, trimmed to ~500 by a light model before heavy ranking; ~1 s total budget for feed assembly; billions of users.
- **API**
- **Data model**
- **Architecture**: Inventory gathering (friends, groups, pages, unseen and re-engaged posts) and integrity filtering first.; Pass 0 lightweight model → Pass 1 multi-task neural model predicting P(like), P(comment), P(share), P(hide)... → weighted value score.; Pass 2 contextual rules for diversity.; Embeddings for users and posts; real-time engagement features.; Distributed predictor fleet; logging for training; survey signals for "meaningful" value.
- **Deep dives**
- **Trade-offs**: the value-model weights encode product choices (engagement vs well-being); recency vs relevance; calibrated multi-task heads vs separate models; compute per request vs quality.
- **Evaluation**: Offline: per-task AUC and log-loss, calibration of each head, NDCG.; Online: A/B on sessions, meaningful interactions, survey scores.; Guardrails: integrity violations shown, hides and reports, creator distribution.

## Reference design

### Requirements

**Functional**: when a user opens the feed (and on each scroll page), return an ordered page of posts from friends, groups and pages they follow, plus unseen and re-engaged posts; mixed formats (text, photo, video, link); support "see first", snooze and hide controls; respect integrity decisions (removed, demoted or borderline content).

**Non-functional**: ~1 s total budget for feed assembly at p99; graceful degradation (fall back to a cheaper ranking or a cached page) under load; global, multi-region.

**Objective**: maximise long-term value to the user — meaningful interactions and satisfaction as measured by surveys — not raw engagement; protect integrity and creator ecosystem health.

**Assumptions to confirm**: ~2B daily active users, ~10 feed loads each per day; the candidate inventory per user per day is ~1,000+ eligible posts (trimmed to ~500 by a light model); pages of ~20 posts; product leadership owns the value-model weights; integrity classifiers exist upstream and expose scores we can use.


### Estimates

- **Requests**: 2B DAU × 10 loads = 20B/day ÷ 86,400 ≈ **230k QPS average**, ~500k QPS peak.
- **Scoring**: Pass 0 trims 1,000+ candidates to ~500 with a cheap model; Pass 1 runs the heavy multi-task model on ~500 → 500k × 500 = **250M candidate scorings/s at peak**. At ~100k scorings/s per inference host, that is ~2,500 hosts for Pass 1 alone, before redundancy — so model cost per candidate is a design constraint, not an afterthought.
- **Features per candidate**: a few hundred (user–author affinity, post engagement counters, embeddings, content type) → multiple GB/s of feature reads at peak; real-time counters (likes in the last 5 minutes) need a streaming pipeline with seconds of lag.
- **Training data**: ~20 posts viewed per load → ~400B impressions/day; train on a sample (e.g. 1–5% of negatives, all positives for rare tasks) with weights.
- **Latency budget (~1 s)**: inventory gathering 150 ms, integrity filtering 50 ms, Pass 0 50 ms, feature fetch 150 ms, Pass 1 250 ms, Pass 2 rules 50 ms, assembly and hydration 100 ms, ~200 ms slack for tails.


### API

```
GET /v1/feed?cursor=…&count=20&surface=home&connection=wifi
  → {request_id, items: [{post_id, rank, author_id, format, reason?}], next_cursor}

POST /v1/feed/events  (batched)
  {request_id, events: [{post_id, type: "impression"|"dwell"|"like"|"comment"|"share"|
                         "hide"|"report"|"see_less", position, value_ms?, ts}]}

Internal:
  Inventory.gather(user_id, since) → candidate post ids with source
  Ranker.score(user features, [post features]) → {p_like, p_comment, p_share, p_hide,
                                                  p_report, e_dwell, ...}
```
The cursor carries the already-shown set so later pages do not repeat posts and can be ranked with knowledge of what the user saw.
Ranking is server-driven; head outputs and value scores are internal debug fields only. Events are batched, delivered at least once and de-duplicated on (request_id, post_id, type), because they become training labels.


### Data model

- **Post**: post_id, author, audience, format, created_at, text and media references, integrity scores and labels, language.
- **Social graph**: friend, follow, group and page membership edges with interaction strength.
- **Embeddings**: user and post embeddings (two-tower), refreshed daily for users and at creation for posts.
- **Real-time counters**: per post likes, comments, shares, hides over 5 min / 1 h / 24 h; per author recent engagement.
- **SeenState**: per user, post ids shown recently and last seen time (for unseen and re-engagement logic).
- **ImpressionLog**: request_id, user, post, position, Pass 1 head outputs, value score, model versions, feature snapshot reference.
- **TrainingExample**: impression joined with each task's label within its window (like within 24 h, comment, share, hide, dwell) and, for a sampled subset, survey answers ("Was this worth your time?").


### Architecture

```
Client ─► Feed API ─► Feed aggregator (per request)
   1. Inventory: friends, groups, pages, unseen + re-engaged posts (~1,000+)
   2. Integrity filter: remove violating posts, apply demotions
   3. Pass 0: lightweight model (two-tower dot product + small MLP) → ~500
   4. Feature hydration: user, author, post, real-time counters, embeddings
   5. Pass 1: multi-task neural model (shared bottom, task heads)
         p(like), p(comment), p(share), p(hide), p(report), E[dwell], ...
      value = Σ wᵢ · headᵢ  (weights set by product; negatives for hide/report)
   6. Pass 2: contextual rules — diversity (author, format, topic), no
      back-to-back posts from one author, freshness, integrity demotions
   7. Page assembly, logging with request_id
Distributed predictor fleet (batched inference, autoscaled per region)
Logs ─► label joins ─► continuous/daily training ─► offline gates ─► A/B ─► ramp
Survey programme ─► "meaningful value" model ─► feeds into value weights
```


### Deep dives

**Why calibration matters here.** The value score multiplies each head's probability by a weight. If p(comment) is systematically over-predicted, comments get more weight than product intended. Each head is calibrated (isotonic or a calibration layer per segment), and calibration is checked per head after every retrain.

**Choosing the weights.** Weights encode product decisions, not something the model learns. Tune them with online experiments against long-term outcomes (sessions over weeks, survey scores), using a model that predicts survey answers from engagement to turn "meaningful" into a scalable label.

**Position bias and delayed labels.** Logged engagement depends on rank; include position as a training feature and fix it at serving, or reweight. Shares and comments arrive minutes to hours later; train with label windows and handle not-yet-observed positives.

**Degradation.** Under load, shrink Pass 1's candidate set from 500 to 200, then fall back to Pass 0 ranking; never fail the feed.


### Trade-offs

- **Value-model weights encode product choices (engagement vs well-being)**: upweighting comments raises engagement but can reward outrage; downweighting it may cut time spent. Make weights explicit, owned and reviewed, with integrity and survey guardrails.
- **Recency vs relevance**: chronological feels fresh but buries important posts; pure relevance resurfaces old posts. Use recency as a feature plus a freshness constraint in Pass 2, and re-engagement for active conversations.
- **Calibrated multi-task heads vs separate models**: one shared multi-task model is cheaper to serve and shares signal across tasks (rare tasks such as shares benefit); separate models are easier to own and retrain independently but cost N× inference.
- **Compute per request vs quality**: a bigger Pass 1 or more candidates improves ranking at thousands of extra hosts; spend compute where users scroll — rank the first page with the full model and later pages more cheaply.


### Evaluation

- **Offline**: per-task AUC and log-loss on a time-based holdout; calibration (predicted/observed ratio) per head and segment; NDCG of the value score against observed value on logged data; results by country, user tenure and content type.
- **Online**: A/B tests on sessions and time-in-app over several weeks, meaningful interactions (comments and shares between people who know each other), and survey scores.
- **Guardrails**: views of integrity-violating content, hides and reports, creator distribution (concentration of impressions across creators, new-creator reach), latency and degradation rate.
- **Monitoring**: feature freshness of real-time counters, calibration drift per head, prediction distribution shifts after each retrain, Pass 0 recall (how often the eventual top posts were dropped early).


## What a strong design shows

- Uses a multi-stage funnel (inventory, integrity, Pass 0, multi-task Pass 1, contextual Pass 2) sized against a 1 s budget and 250M scorings/s.
- Explains that a value score over calibrated heads encodes product choices and needs explicit ownership.
- Defines success beyond engagement: meaningful interactions, surveys, integrity and creator-health guardrails.
- Handles position bias, delayed labels and graceful degradation.
- Evaluates per head offline and runs long online experiments with guardrails.

---

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