LearnSystem design

News-feed ranking for a social network

Rank the posts a user sees when opening their feed.

ML engineering8 parts

Contents

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

Sketch your own design first. A complete answer has these parts; the notes say what each should settle.

  1. RequirementsRank the posts a user sees when opening their feed.
  2. Estimatesabout 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.
  3. API
  4. Data model
  5. ArchitectureInventory 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.
  6. Deep dives
  7. Trade-offsthe 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.
  8. EvaluationOffline: 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

One way to answer it, part by part. Open a part once you have your own version of it.

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

Stack · 5 layersLatency budget for feed assembly

  1. Inventory gathering 150 ms, integrity filtering 50 ms.

  2. Lightweight model trims ~1,000+ candidates to ~500.

  3. User, author, post, real-time counters and embeddings.

  4. Multi-task neural model on ~500 candidates.

  5. Contextual rules 50 ms, assembly and hydration 100 ms.

The ~1 s budget is split across inventory, integrity filtering, Pass 0, feature fetch, Pass 1, Pass 2 and assembly, with ~200 ms slack for tails.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
  • 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

Flow · 4 stepsHow a feed request moves through the ranking funnel

How a feed request moves through the ranking funnelThe diagram shows the per-request path for ranking a user's feed. It starts at the client and Feed API, gathers roughly 1,000+ candidates, filters integrity, trims to about 500 with Pass 0, hydrates features, scores with the multi-task Pass 1 model, applies contextual Pass 2 rules, then assembles and logs the page.Clientopens the feedFeed APIGET /v1/feedInventory~1,000+ candidatesIntegrity filterremove, demote, borderlinePass 0two-tower + small MLPFeature hydrationuser, author, post, counters,embeddingsPass 1p(like), p(comment), p(share),p(hide)Pass 2diversity, freshness, demotionsPage assemblyordered page, request_idGET /v1/feedcandidates~500featuresvalue scoreranked posts1234RequestFunnelOutput
  1. Gather and filter The client asks the Feed API; inventory gathers candidates, then integrity filtering removes and demotes violating posts.
  2. Trim and hydrate Pass 0 trims the candidates to about 500, then user, author, post, real-time counters and embeddings are hydrated.
  3. Score and rank Pass 1 runs the multi-task model and value score; Pass 2 applies diversity, freshness and integrity demotions.
  4. Assemble and log The ordered page is assembled and logged with request_id.

A feed request moves from the client through inventory, integrity filtering, Pass 0, feature hydration, Pass 1 and Pass 2 before an ordered page is assembled and logged.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Gather and filterThe client asks the Feed API; inventory gathers candidates, then integrity filtering removes and demotes violating posts.
2Trim and hydratePass 0 trims the candidates to about 500, then user, author, post, real-time counters and embeddings are hydrated.
3Score and rankPass 1 runs the multi-task model and value score; Pass 2 applies diversity, freshness and integrity demotions.
4Assemble and logThe ordered page is assembled and logged with request_id.

Source: This page's text

Boxes
BoxGroupDetail
ClientRequestopens the feed
Feed APIRequestGET /v1/feed
InventoryFunnel~1,000+ candidates
Integrity filterFunnelremove, demote, borderline
Pass 0Funneltwo-tower + small MLP
Feature hydrationFunneluser, author, post, counters, embeddings
Pass 1Funnelp(like), p(comment), p(share), p(hide)
Pass 2Funneldiversity, freshness, demotions
Page assemblyOutputordered page, request_id

Source: This page's text

CalculatorPass 1 load at peak

Scorings per second = Peak QPS × 1000 × Candidates per user

Pass 1 hosts = Scorings per second ÷ (100 × 1000)

Worked cases
CasePeak QPS (k QPS)Candidates per userScorings per secondPass 1 hosts
Peak500500250,000,000 scorings/s2,500 hosts
Peak QPS times candidates per user gives candidate scorings per second, and dividing by per-host throughput gives the Pass 1 host count.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
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.