Skip to content

Design a Recommendation System (Twitter For You)

Advanced 102 min read Part 17 of 18

Pick about 50 posts from hundreds of millions for each For You request in under 1.5 seconds: candidate sources, light and heavy rankers, filters and feedback.

The Problem#

Open the X app (formerly Twitter) and the first tab is For You. It is not a list of posts from the accounts you follow, in time order. It is a feed that a machine picked for you: some posts from people you follow, some from people you have never heard of, ordered by how likely you are to care about each one. We will design that feed, and in doing so the general shape of a large-scale recommendation system.

This problem has an unusually good public reference. In March 2023 Twitter published a post on its engineering blog, "Twitter's Recommendation Algorithm", and open-sourced most of the code behind For You in the twitter/the-algorithm and twitter/the-algorithm-ml repositories on GitHub. The blog gives the headline numbers we will design against:

  • About 500 million posts are created every day.
  • For each request, the system tries to pick the best 1,500 candidates from a pool of hundreds of millions.
  • On average the feed is 50% in-network (from accounts you follow) and 50% out-of-network.
  • A neural network of about 48 million parameters ranks the candidates. It predicts ten kinds of engagement using thousands of features.
  • The whole pipeline runs about 5 billion times a day and completes in under 1.5 seconds on average.

Those numbers already tell you the shape of the answer. You cannot run a 48-million-parameter model on hundreds of millions of posts per request. You can run it on 1,500. So the core of any recommender at this scale is a funnel: cheap methods narrow a huge pool to a few thousand candidates, more expensive models rank those candidates, and rules shape the final page. The hard parts sit around that funnel:

  1. Where do candidates come from? Posts from accounts you follow are easy to find. Good posts from accounts you do not follow are hard: out of hundreds of millions, which few hundred might you like? This needs graph traversals ("what did the people I follow like?") and embeddings (numeric representations in which similar users and posts are close together).
  2. How do you rank thousands of posts per request, billions of times a day? The model needs thousands of features per (user, post) pair, fetched in milliseconds, and the scoring cost must fit a tight latency and hardware budget.
  3. Features must be fresh and consistent. A post that got 10,000 likes in the last ten minutes is a different candidate from the same post an hour ago. Real-time signals must reach the ranker within seconds, and the features the model sees in production must match the ones it was trained on.
  4. The best-scored list is not the best feed. Ten posts in a row from one author, posts you already saw, posts from accounts you blocked, or a feed with no posts from friends all make a bad experience. Filters and diversity rules reshape the ranked list.
  5. The system trains on its own output. Users can only engage with what they were shown. That creates feedback loops and biases, and makes "is the new model better?" a hard question.
  6. Cold start. A new user has no history. A post created a second ago has no engagement. A new account has no followers. The system must still do something sensible for all three.

An analogy. Think of a personal shopper in a huge department store, serving thousands of regular customers at once. When Asha walks in, the shopper does not walk every aisle. They grab a cartful of likely items quickly: new arrivals from brands Asha already buys (in-network), items that shoppers with similar taste bought this week (collaborative filtering), and items that "feel like" Asha's style (embeddings). Then they look closely at each item in the cart, thinking about Asha's size, budget and what Asha returned last time, and put them in order (ranking). Before handing over the selection, they remove anything Asha has already bought or said they dislike, and make sure it is not ten shirts from the same brand (filtering and diversity). Finally they note what Asha picked up and what they ignored, so tomorrow's cart is better (feedback). The design questions are the shopper's questions:

  • How do you fill the cart fast enough, from a store too large to walk?
  • How do you judge each item carefully without keeping the customer waiting?
  • How do you know what the customer likes right now, not just last month?
  • How do you avoid showing only what the customer already knows?
  • What do you do for a customer you have never met?

Background: a few terms used in this design#

  • Post (tweet). A short message, possibly with images, video or a link. We use "post" and "tweet" interchangeably; the open-source code says "tweet".
  • In-network and out-of-network. A post is in-network for a viewer if its author is someone the viewer follows. Otherwise it is out-of-network (OON).
  • Engagement. Any action on a post: like, repost (retweet), reply, click, profile visit, video watch, or a negative action such as "show less often", mute, block or report.
  • Candidate generation (retrieval, candidate sourcing). The first stage of the funnel. Cheap methods pick a few thousand plausible posts out of hundreds of millions. Each method is a candidate source.
  • Ranking (scoring). Predicting, for each candidate, how likely the viewer is to engage with it in each way, and combining the predictions into one score.
    • A light ranker is a small, cheap model (for example logistic regression) used to rank many candidates inside a source.
    • A heavy ranker is a large neural network used on the final few thousand candidates.
  • Feature. One input number (or category, or vector) for a model, such as "how many of the viewer's follows liked this post", "the author's follower count" or "the viewer's language". Feature hydration means fetching all features for a batch of candidates.
  • Feature store. A system that computes, stores and serves features. It has an online store (low-latency reads at serving time) and an offline store (historical values for training). See ML System Design and Feature Stores.
  • Embedding. A list of numbers (a vector) that represents a user, post or topic, learned so that similar things have similar vectors. Similarity is usually the dot product or cosine similarity of two vectors.
  • ANN (approximate nearest neighbour) search. Finding the vectors most similar to a query vector without comparing against every vector, trading a little accuracy for a large speed-up. HNSW and IVF-PQ are common index types. See Vector Databases and Similarity Search.
  • Collaborative filtering. Recommending items because people similar to you engaged with them, without needing to understand the items themselves. "People who liked this also liked that" is the classic form.
  • Multi-task model. One model that predicts several outcomes at once (like, reply, repost, report), sharing most of its internal layers.
  • Cold start. The problem of recommending for a user, item or system with little or no interaction history.
  • Feedback loop. The model's choices decide what users see. What users see decides what they engage with, which becomes the next training data.
  • Impression. One post shown on one user's screen. Impressions without engagement are the negative examples for training.

Clarifying Questions#

QuestionWhy it mattersAssumed answer
Which surface are we designing: home feed only, or also search, notifications and explore?Each surface has its own candidates, objectives and latencyThe home For You feed; the same platform could power other surfaces later
What should the feed optimise for?Defines the labels and the scoreA weighted mix of predicted positive engagements minus predicted negative ones, with guardrails on time spent and reports
How fresh must content be?Decides how real-time the pipeline and indexes must beMostly posts from the last 1 to 2 days; a new post should be recommendable within a minute or two
How many users and requests?SizingAbout 250 million daily active users and about 5 billion feed requests a day
How many new posts?Size of the candidate pool and indexesAbout 500 million new posts a day
What latency is acceptable?Shapes the whole serving pathUnder about 1.5 seconds on average for a fresh page, under 2 seconds at p99; scrolling within a session should feel instant
What mix of in-network and out-of-network content?Balance between familiar and discoveryAround 50/50 on average, adapted per user (new users see more out-of-network)
Must we respect blocks, mutes, sensitive-content settings and legal restrictions?Hard filters that must never fail openYes, always, applied after ranking and before serving
Can users give explicit feedback ("not interested", "show less")?Negative signals for ranking and fatigueYes, and it must take effect in the next request
Are ads and other modules mixed into the feed?Mixing stage and layoutYes: ads, who-to-follow and prompts are inserted, but their selection is a separate system
Do we need a non-personalised fallback?Availability when ML services failYes: a reverse-chronological feed from followed accounts must always be available
Is model training in scope?Scope controlWe design the data and training pipelines at the system level, not the model internals in full detail

Requirements#

Functional requirements#

  1. Serve a ranked feed. Given a viewer, return about 50 posts for the For You feed, mixing posts from followed accounts and recommended posts, with cursor-based paging for "load more".
  2. Find candidates. Retrieve recent, relevant posts from followed accounts and from the wider network (graph-based and embedding-based sources), about 1,500 per request.
  3. Rank candidates. Score each candidate with a model that predicts several kinds of engagement, and combine them into one score.
  4. Filter and diversify. Remove posts the viewer must not or should not see (blocked or muted authors, already-seen posts, unsafe content) and enforce author diversity and a balance of in-network and out-of-network posts.
  5. Mix. Insert ads, who-to-follow modules and prompts, and thread replies with their parent posts.
  6. Record feedback. Log every impression and engagement, including negative feedback, with enough context to train models and to update real-time features.
  7. Handle cold start. Produce a reasonable feed for new users, and give new posts and new authors a chance to be seen.

Non-functional requirements#

  • Latency: under about 1.5 seconds on average for a full ranked page, p99 under 2 seconds; the first screen should appear fast, and later pages should come from a cache.
  • Throughput: about 58,000 requests per second on average, with daily peaks of about 3 times that, and spikes around major live events.
  • Freshness: a new post is retrievable within about a minute; engagement counts used as features are at most seconds to a minute old; negative feedback takes effect on the next request.
  • Availability: 99.9% or better for the feed. Under partial failure the feed degrades (fewer sources, simpler ranking, reverse-chronological fallback) rather than returning an error.
  • Safety: filters for blocks, mutes and legal restrictions must fail closed: if the filter cannot be evaluated, the post is not shown.
  • Cost: ranking is the dominant cost; every stage has a candidate and compute budget.
  • Privacy: private signals (profile visits, address book matches) are used only as aggregated features and never exposed.
  • Measurability: every change to models, weights or rules can be tested with controlled experiments.

Capacity Estimation#

We start from the public numbers and fill the gaps with labelled assumptions. A day has 86,400 seconds, so 1 billion events a day is about 11,600 per second. See Back-of-the-Envelope Estimation.

Feed requests.

  • Twitter's blog says the For You pipeline runs about 5 billion times a day. 5 × 10⁹ ÷ 86,400 ≈ 58,000 requests per second on average.
  • Assume a daily peak of about 3 times the average, so about 175,000 per second, and short spikes of several times that during major live events (a final, an election night). These multipliers are assumptions.
  • With about 250 million daily active users (an assumption that fits the request count), that is about 20 feed loads per user per day. Many are pull-to-refresh or "load more" during the same session, which matters for caching later.

Candidates and scoring.

  • About 1,500 candidates per request × 58,000 requests per second ≈ 87 million candidate scorings per second on average, and about 260 million at peak.
  • The heavy ranker has about 48 million parameters. A dense forward pass costs about 2 floating-point operations per parameter, so at most about 100 million operations (0.1 GFLOP) per candidate. In practice much of the model is embedding lookups, which cost memory bandwidth rather than arithmetic, so this is an upper bound.
  • Upper bound for heavy ranking: 87 million × 0.1 GFLOP ≈ 9 PFLOP/s on average (petaFLOP per second, 10¹⁵). At an effective 100 TFLOP/s per modern accelerator (well below peak, which is realistic for small batches), that is roughly 90 accelerators on average and 250 to 300 at peak, before redundancy. On CPUs the same work takes tens of thousands of cores. Either way, heavy ranking is the single largest compute cost, which is why the funnel exists.

Whole-pipeline compute. The blog says one pipeline execution needs 220 seconds of CPU time, about 150 times the latency the user sees. Taken literally, 5 billion × 220 CPU-seconds a day is about 1.1 × 10¹² CPU-seconds, or about 12.7 million cores busy around the clock. The figure probably counts every service a request touches, including the candidate sources and feature services. The lesson is the ratio, not the exact core count: a single feed request fans out into a very large amount of parallel work, so every stage needs a budget.

Feature hydration. The home-mixer README says the ranker uses about 6,000 features. Most are sparse or shared. Assume that about 1,000 non-zero values per candidate, packed compactly, take about 4 KB. Then one request moves about 1,500 × 4 KB = 6 MB of features into the ranker. At 58,000 requests per second that is about 350 GB/s of feature traffic inside the data centre. This is why features shared by many candidates (the viewer's features, an author's features) are fetched once per request, and post features are cached close to the ranker.

New posts (writes).

  • 500 million posts a day ÷ 86,400 ≈ 5,800 posts per second on average, with peaks of 15,000 to 20,000 per second and higher spikes during live events.
  • A post's metadata and text are about 1 KB, so about 500 GB of new post data a day before media.
  • Each new post must enter the in-network search index, the embedding pipelines and the real-time feature counters within about a minute.

Impressions and engagements (the feedback stream).

  • The blog says Twitter serves over 150 billion posts to devices every day. That is about 1.7 million impressions per second.
  • An impression log record (viewer, post, position, request id, model version, time, how long it was visible) is about 200 bytes, so about 30 TB a day raw, or perhaps 5 to 10 TB compressed.
  • Assume about 10 billion engagements a day (likes, replies, reposts, clicks, video views, negative feedback): about 115,000 per second on average.
  • Each impression, joined with whatever engagement followed it, is one training example. That is about 150 billion potential examples a day. Training pipelines keep all positives and a sample of negatives.

Indexes and stores. These are sized from the numbers above with stated assumptions.

StoreAssumptionSize
In-network index (recent posts)Last ~2 days, ~1 billion posts, ~1 KB each with static features~1 TB per replica, sharded
Post embeddings for ANN1 billion posts × 128 dimensions × 2 bytes (float16)~256 GB; ~64 GB with product quantization at 64 bytes per vector
User embeddings500 million monthly users × 128 dimensions × 2 bytes~128 GB
Recent engagement graph (in memory)2 days × 10 billion engagements × ~16 bytes per edge~320 GB per replica, sharded
Follow graph~400 million accounts × ~300 follows on average (assumed) × 16 bytes~2 TB
Online user features250 million daily users × ~10 KB~2.5 TB
Online post features (counters)1 billion recent posts × ~500 bytes~500 GB
Viewer-author pair scorestop 1,000 authors per user × 250 million users × 12 bytes~3 TB

Summary.

QuantityValue
Feed requests58,000 per second average, ~175,000 daily peak
Candidates scored~87 million per second average
Heavy ranker computeup to ~9 PFLOP/s average
New posts~5,800 per second, ~500 GB a day of metadata
Impressions~1.7 million per second, ~30 TB a day raw
Engagements~115,000 per second
Feature traffic into the ranker~350 GB/s
Latency targetunder ~1.5 s average for a fresh page

The takeaway: the problem is dominated by per-request work, not by storage. Storage is a few terabytes of hot data. The cost is in doing the retrieval, feature fetching and scoring for 1,500 candidates, 58,000 times a second, within about a second. Every design choice below either removes candidates early, shares work between candidates or requests, or moves work off the request path.

Core Entities#

  • User. Account id, language, country, account age, settings (sensitive-content preferences), and the follow list. Also both sides of the network: a user is a consumer of posts and a producer of posts.
  • Post. Post id (time-ordered, so the id encodes the creation time), author id, text, media, language, reply and quote links, and safety labels.
  • FollowEdge. Follower id, followee id, created time. Directed: Asha can follow Kai without Kai following Asha.
  • EngagementEvent. One action by one user on one post or author: event id, user id, post id, author id, type (like, reply, repost, click, video watch, show less, mute, block, report), time, surface and request id.
  • Impression. One post shown to one user: request id, position, time on screen, model version and the candidate source that produced it.
  • UserFeatures, PostFeatures, PairFeatures. Feature vectors keyed by user, by post and by (viewer, author). Each has an online version (latest values) and an offline history (values as of past times).
  • Embedding. A vector for a user, post, author or topic, with the model version that produced it.
  • Model. A versioned ranking model with its feature list, training data range and evaluation results.
  • SeenSet. The posts recently served to a user, used to avoid repeats.

API Design#

The client API is small. The work happens in internal services.

GET /2/timeline/for-you?count=50&cursor={bottom_cursor}
  200 OK
  {
    "request_id": "r-7f3a...",
    "entries": [
      { "type": "post", "post_id": "1866...", "social_context": "Kai liked",
        "feedback_actions": ["not_interested", "show_less_from_author"] },
      { "type": "conversation", "post_ids": ["1865...", "1866..."] },
      { "type": "ad", "ad_id": "a-91..." },
      { "type": "who_to_follow", "user_ids": ["u-12", "u-77", "u-31"] }
    ],
    "cursor": { "top": "c-top-...", "bottom": "c-bot-..." }
  }
 
POST /2/timeline/feedback
  { "request_id": "r-7f3a...", "post_id": "1866...",
    "action": "not_interested | show_less_from_author | see_more" }
  204 No Content
 
POST /1/client-events     (batched, sent every few seconds)
  { "events": [ { "type": "impression", "request_id": "r-7f3a...", "post_id": "1866...",
                  "position": 3, "visible_ms": 2400, "ts": "2026-12-04T09:12:03Z" },
                { "type": "video_view", "post_id": "1866...", "watched_pct": 55 } ] }
 
Internal RPC (Thrift or gRPC):
  HomeMixer.GetForYou(viewer_id, cursor, count, client_context)
  CandidateSource.Fetch(viewer_id, signals, max_results)   (one per source)
  FeatureService.Hydrate(viewer_id, candidate_ids, feature_set)
  Ranker.Predict(model_version, feature_batch) -> probabilities per engagement type
  VisibilityFilter.Check(viewer_id, post_ids, safety_level) -> action per post

Design notes:

  • The request id ties everything together. Every impression and engagement logged later carries the request id of the feed response that showed the post. Training jobs join on it to find the exact model version, candidate source and features that produced the decision.
  • Log features at serving time. The feature service writes the feature values it served for each (request, candidate) to a log. Training on these logged values, rather than recomputing features later, is the most reliable cure for training-serving skew (deep dive 6).
  • Two cursors. The top cursor asks "anything new since this page?" for pull-to-refresh. The bottom cursor asks "more, older or lower-ranked" for infinite scroll. Cursors are opaque to clients. Internally, the bottom cursor points at a cached, already-ranked list (deep dive 8), so scrolling does not re-run the whole pipeline.
  • Client-side impressions. The server knows what it sent, not what the user saw. A post that the user scrolled past in 50 milliseconds is not a meaningful negative. Clients report impressions with time on screen, and training uses a minimum visible time.
  • Feedback is idempotent and immediate. Repeated "not interested" taps are harmless. The feedback is written to the user's real-time signals so that the next request already applies it (deep dive 7).
  • Scores are never exposed. The response says "Kai liked" as social context, but not the model's probabilities. Scores are internal and change with every model version.
  • Internal calls are binary RPCs with deadlines. A feed request fans out into dozens of internal calls. Each carries a deadline (the remaining time budget), so a slow dependency is cut off rather than holding up the whole request. See API Styles: REST, gRPC, GraphQL and More.

High-Level Design#

We build the design one requirement at a time, starting with the simplest version that works, then put the pieces together. The overall shape is the funnel from the problem statement:

1) Show recent, relevant posts from accounts the viewer follows#

The simplest feed is reverse-chronological: fetch the latest posts of everyone the viewer follows, newest first. There are two classic ways to build it, both covered in the news feed case study:

  • Fan-out on write. When Kai posts, push the post id into a cached timeline list of each of Kai's followers. Reads are a single list lookup. Writes are expensive for accounts with millions of followers.
  • Fan-out on read. At request time, look up the viewer's follows and fetch their recent posts. Writes are cheap. Reads must merge many lists.

Twitter ran a fan-out service for about 12 years. The 2023 blog says it stopped using that Fanout Service and now gets in-network posts from its real-time search index (Earlybird). That is fan-out on read with a twist. The index is partitioned by time and by post, holds the recent posts of all users, and can answer "recent posts by any of these 1,000 authors" while ranking them inside the index with a light model.

A ranked in-network source needs a relevance signal per author. The blog names Real Graph as the most important one: a model that predicts how likely the viewer is to engage with each account. The higher the Real Graph score between the viewer and an author, the more of that author's posts are kept. The in-network source then scores candidate posts with a logistic regression light ranker and returns the top few hundred. The released code fetches up to 600 in-network candidates per request by default.

2) Find good posts from accounts the viewer does not follow#

Out-of-network posts are about half of the feed. The blog describes two families of methods.

Graph-based sources. Walk the graph of follows and engagements to answer two questions: "which posts did the people I follow recently engage with?" and "who likes the same posts as me, and what else did they like recently?". Twitter built GraphJet, an in-memory engine that keeps a real-time bipartite graph of users and posts, to run these traversals. The open-source User Tweet Entity Graph (UTEG) service is built on it and holds the engagements of the last 24 to 48 hours in memory. It produces the posts shown with social context such as "Kai liked". The blog says these graph methods serve about 15% of Home Timeline posts.

Embedding-based sources. Represent users and posts as vectors so that "posts similar to my interests" becomes a nearest-neighbour search. The blog calls embedding approaches the larger source of out-of-network posts. Its main example is SimClusters: about 145,000 communities found from the follow graph and recomputed every three weeks, with users and posts represented by how strongly they belong to each community. Dense embeddings from TwHIN (a knowledge-graph embedding of users, posts and other entities) are used for retrieval and as model features.

A coordination layer (in the open-source code, a service that fans out to the out-of-network sources) calls the graph and embedding sources in parallel, merges and deduplicates their results, and returns a few hundred candidates. Deep dives 3 and 4 explain each source.

3) Rank all candidates with one heavy model#

At this point we have about 1,500 candidates from several sources, each source with its own light score. Those scores are not comparable. So the next stage treats all candidates equally and scores them with one model. The blog describes it as a neural network of about 48 million parameters, trained continuously on engagements, that takes thousands of features and predicts ten engagement probabilities per post.

Two services do this work:

  1. Feature hydration. Fetch about 6,000 features for each (viewer, candidate) pair from feature services: viewer features (fetched once), author features (fetched once per author), post features (engagement counts, media, language, safety scores) and pair features (Real Graph score, "how many of the viewer's follows liked this").
  2. Scoring. Send the batch of feature vectors to a model server. In Twitter's open-source stack this is Navi, a model server written in Rust with a TensorFlow Serving compatible gRPC API. The model returns, per candidate, probabilities such as P(like), P(reply), P(repost) and P(negative feedback). A weighted sum turns them into one score (deep dive 5).

4) Filter, diversify and assemble the page#

The best-scored list is not yet a good page. The blog and the home-mixer README list the heuristics and filters applied after ranking:

  • Visibility filtering: remove posts from blocked or muted accounts, posts that break the viewer's sensitive-content settings, and posts restricted for legal reasons. This uses a central rule engine.
  • Author diversity: avoid several consecutive posts from one author.
  • Content balance: keep a fair mix of in-network and out-of-network posts.
  • Feedback-based fatigue: lower the score of posts related to things the viewer gave negative feedback on.
  • Social proof: drop out-of-network posts that have no second-degree connection to the viewer (nobody they follow engaged with the post or follows its author), as a quality safeguard.
  • Deduplication: remove posts already seen.
  • Conversations: thread a reply together with its parent post.

Then the mixing step blends posts with non-post content (ads, who-to-follow, prompts) and the page is returned. Deep dive 7 covers the filters and the diversity maths.

5) Keep signals fresh#

Feeds go stale fast, so features must move at the speed of the network:

  • Every user action goes onto one real-time stream of user actions (the open-source unified-user-actions component). A user signal service serves each user's recent explicit signals (likes, replies) and implicit ones (profile visits, post clicks) to candidate sources and rankers.
  • Stream jobs keep counters per post (likes and replies in the last minutes and hours), update post embeddings as engagements arrive, and feed the in-memory engagement graph.
  • Batch jobs recompute slower signals: Real Graph scores (daily), SimClusters communities (every three weeks), dense embeddings, author reputation.

6) Learn from what users do#

Every impression and engagement is logged with its request id. A training pipeline joins impressions with the engagements that followed them (within a time window) to make labelled examples, attaches the features logged at serving time, and trains new versions of the heavy ranker continuously. A model registry keeps versions; each new model goes through offline evaluation, a shadow run and an online A/B test before it takes traffic. Deep dives 10 and 12 cover evaluation, feedback loops and the training pipeline.

7) Never return an empty feed#

The ML path has many dependencies. If scoring fails, the home-mixer README describes a backup reverse-chronological pipeline that still returns posts from followed accounts. Ranked results are also cached for a few minutes per viewer (the released code's default for cached scored posts is 3 minutes), so "load more" and quick refreshes do not re-run the full pipeline. Deep dive 8 covers the latency budget and degradation.

The full high-level design#

Components:

ComponentResponsibilityTechnology choices
Home MixerOrchestrates a feed request: candidate pipelines, hydration, scoring, filters, mixing, cursors, loggingStateless Scala service on a pipeline framework (Product Mixer in Twitter's code); any JVM or Go service works
In-network sourceRecent posts by followed authors, ranked by a light model inside the indexEarlybird (Lucene-based real-time search); Elasticsearch or a custom inverted index
Real GraphPredicts viewer-to-author engagement; picks and weights followed authorsDaily batch job with a gradient-boosted tree model; scores in a key-value store
Engagement graph (UTEG)Collaborative filtering over the last 24 to 48 hours of engagements, in memoryGraphJet; or a sharded in-memory graph service
SimClusters ANNCommunity-based sparse embeddings; community to top posts lookupsBatch jobs (Scalding, BigQuery) plus a streaming post-embedding job
Dense ANN indexNearest-neighbour search over learned user and post vectorsHNSW or IVF-PQ via FAISS, ScaNN, Milvus, Vespa or Elasticsearch kNN
Follow recommendationsAccounts the viewer may like, and their recent postsSeparate service with its own candidate and ranking stages
Feature hydration and storesServe ~6,000 features per candidate with low latencyKey-value stores (Manhattan at Twitter; Redis, Cassandra, DynamoDB, Aerospike elsewhere) with in-process caches
Model serversBatched inference for the heavy rankerNavi (Rust); TensorFlow Serving, Triton, TorchServe; CPU or GPU
Visibility filteringHard filters, labels and down-ranking for safety, legal and user settingsCentral rule engine library; fails closed
Unified user actionsOne real-time stream of all user actionsKafka (Twitter also used its own systems over the years)
Real-time feature jobsPer-post counters, aggregates, embedding updatesFlink, Kafka Streams, Heron or Storm
Data lake and trainingImpressions, engagements and logged features; continuous trainingObject store or HDFS, Spark or BigQuery, TensorFlow or PyTorch training
Backup pipelineReverse-chronological feed when ranking failsSame search index without the heavy ranker

Key Flows#

Flow 1: Asha opens the app and gets a fresh For You page#

  1. The client calls GET /2/timeline/for-you without a cursor. The gateway authenticates Asha and forwards the request to Home Mixer with a deadline of about 1.5 seconds.
  2. Home Mixer loads Asha's context in parallel: recent signals from the user signal service (likes, replies, follows, negative feedback in the last few days), the seen-posts set, and the experiment buckets that decide which model and parameters apply.
  3. It calls the candidate sources in parallel, each with a candidate budget and a timeout: the in-network search index (about 600), the out-of-network coordinator (about 400 from embeddings and similar sources), the engagement graph (about 300) and follow recommendations (about 100). The released code uses these as default fetch limits.
  4. It merges the results, removes duplicates and posts in the seen set, and drops obviously ineligible posts (too old, deleted, from blocked authors) before paying for features.
  5. Feature hydration fetches features for the remaining ~1,500 candidates: viewer features once, author features once per author, post features per post, pair features per (Asha, author).
  6. The heavy ranker scores the batch on the model servers, returning ten probabilities per candidate. Home Mixer computes the weighted score.
  7. Filters and heuristics run: visibility filtering, author diversity, in-network and out-of-network balance, fatigue from negative feedback, social proof for out-of-network posts.
  8. Mixing inserts ads and a who-to-follow module, threads replies into conversation modules and adds social context ("Kai liked").
  9. Home Mixer caches the full ranked list for Asha for a few minutes, logs the request (candidates, sources, features served, scores, model version) and returns the first ~50 entries with top and bottom cursors.

Flow 2: Asha scrolls for more, then pulls to refresh#

  1. Near the end of the page, the client calls the API with the bottom cursor. The cursor points at Asha's cached ranked list from Flow 1.
  2. If the cache entry is still valid (a few minutes old at most), Home Mixer takes the next slice of the cached list, re-applies cheap filters (newly blocked accounts, posts seen since) and returns it. No candidate retrieval or heavy ranking is needed, so the response takes tens of milliseconds.
  3. If the cache has expired, or Asha has scrolled past what was ranked, Home Mixer runs a new pipeline with the already-served posts excluded.
  4. Pull-to-refresh sends the top cursor. Home Mixer runs the full pipeline, but the seen set now contains everything already served, so the new page contains new posts. If little new exists (Asha refreshed ten seconds ago), the response can be small or empty, and the client keeps the current page.

Flow 3: Kai posts, and the post reaches Asha out of network#

Asha does not follow Kai. Kai writes a post about bread baking.

  1. The post service stores the post and publishes a post-created event. The search index ingests it within seconds, so Kai's followers can get it as an in-network candidate.
  2. Some of Kai's followers like the post. Each like goes onto the user actions stream.
  3. The engagement graph adds the like edges. Three accounts Asha follows liked the post, so a traversal from Asha's follows now reaches it, and the graph source can return it with social context.
  4. The post-embedding job adds the InterestedIn vector of each user who liked the post to the post's SimClusters embedding. Kai's post now has weight in the "home baking" community, and the community-to-top-posts index lists it.
  5. On Asha's next request, the post can arrive from both sources. Home Mixer deduplicates it, the heavy ranker scores it (Asha often likes baking posts), it passes the social proof check (people Asha follows liked it), and it is shown with "liked by people you follow".

Flow 4: Asha taps "show less from this author"#

  1. The client sends POST /2/timeline/feedback. The feedback service writes the event to the user actions stream and to Asha's negative-feedback list in the user signal service.
  2. The client hides the post immediately.
  3. On the next request, Home Mixer reads Asha's recent negative feedback. The fatigue heuristic lowers or removes posts from that author, and posts very similar to the one Asha rejected.
  4. Later, the event also becomes a training label: the heavy ranker learns a higher P(negative feedback) for similar (viewer, post) pairs.

Flow 5: one day of learning#

  1. Clients send impressions and engagements. They land in the data lake, partitioned by hour.
  2. A label-join job waits a fixed attribution window (for example a few hours) after each impression, then joins it with any engagements on the same (viewer, post) pair, producing one example with ten labels.
  3. The job attaches the features logged at serving time and samples negatives.
  4. The trainer continues training the current model on the new examples (warm start) and publishes a candidate model.
  5. The candidate is evaluated offline, run in shadow against live traffic, then tested on a small percentage of users. If it wins on the target metrics and does not hurt the guardrails, it is rolled out.

Data Model#

Each entity lives in the store that fits its access pattern; there is no single database.

DataAccess patternStore
PostsGet by id, by the million per secondSharded key-value store (Manhattan at Twitter; Cassandra or DynamoDB elsewhere), plus caches
Recent posts by author"Recent posts by these 1,000 authors", rankedReal-time search index partitioned by time
Follow graphWho does X follow; who follows XSharded graph or key-value store with both edge directions
Recent engagement graphTraversals over the last 24 to 48 hoursIn-memory graph service (GraphJet)
Online featuresMulti-get thousands of keys in a few msKey-value store with in-process caches
Embeddings and ANN indexesNearest neighbours of a vectorANN service; vectors also in the key-value store
Impressions, engagements, logged featuresAppend-only; scanned by training jobsKafka, then Parquet in an object store or HDFS, partitioned by hour
Seen set"Has this viewer seen this post?" per requestPer-user list or Bloom filter in Redis with a TTL of days
Scored-posts cacheRanked list per viewer for minutesRedis or Memcached keyed by viewer

Feature store keys. Online features are stored as one value per entity, so that a request needs few round trips:

uf:{user_id}            -> UserFeatures blob (lang, account age, aggregates of
                           likes and replies per topic over 1d / 7d / 30d, ...)
pc:{post_id}            -> PostCounters (likes, replies, reposts, video views in
                           the last 5 min, 1 h, 24 h; updated by stream jobs)
af:{author_id}          -> AuthorFeatures (follower count, reputation, recent
                           engagement rate, safety scores)
rg:{viewer_id}          -> top ~1,000 (author_id, real_graph_score) pairs
emb:{space}:{entity_id} -> vector (for example emb:simclusters:user:42)

Building training examples. The label join attaches engagements to impressions inside an attribution window, so that each example records what the model predicted and what happened next:

-- One training example per impression, with ten binary labels.
SELECT
  i.request_id, i.post_id, i.viewer_id, i.position, i.source,
  f.feature_blob,                            -- logged at serving time
  MAX(e.type = 'like')           AS label_like,
  MAX(e.type = 'repost')         AS label_repost,
  MAX(e.type = 'reply')          AS label_reply,
  MAX(e.type = 'good_click')     AS label_good_click,
  MAX(e.type = 'video_50pct')    AS label_video_50,
  MAX(e.type IN ('show_less', 'mute', 'block')) AS label_negative,
  MAX(e.type = 'report')         AS label_report
FROM impressions i
JOIN logged_features f
  ON f.request_id = i.request_id AND f.post_id = i.post_id
LEFT JOIN engagements e
  ON e.user_id = i.viewer_id AND e.post_id = i.post_id
 AND e.ts BETWEEN i.ts AND i.ts + INTERVAL 6 HOUR
WHERE i.hour = '2026-12-04T09'
  AND i.visible_ms >= 500                    -- ignore posts scrolled past instantly
GROUP BY i.request_id, i.post_id, i.viewer_id, i.position, i.source, f.feature_blob;

Three details matter. Only impressions visible for a minimum time count as examples. The attribution window (here 6 hours) decides how long we wait before calling an impression a negative, a trade-off between label completeness and freshness. And the position is kept, so that training can correct for the fact that posts near the top get more engagement simply because they are near the top (deep dive 10).

Deep Dives#

1. The funnel: why recommendation happens in stages#

The single most important idea in a large recommender is that each stage spends more per item on fewer items. Look at what would happen without stages.

Suppose the heavy ranker costs about 1 millisecond of CPU per candidate (a plausible order of magnitude for a model of tens of millions of parameters on a CPU, less on an accelerator). Scoring every post from the last two days, about 1 billion of them, would take 1 billion milliseconds: about 11.5 days of CPU per request. Even a trivially cheap score of 1 microsecond per post would take 1,000 CPU-seconds per request. Neither is possible at 58,000 requests per second.

So the work is split:

StageItems inItems outCost per itemGoal
Candidate sources (retrieval)hundreds of millions~1,500microseconds or less, often amortised through an indexRecall: do not miss posts the viewer would love
Light ranking (inside sources)thousands to tens of thousands per sourcehundreds per sourceabout a microsecond (logistic regression, small trees)Order a source's candidates so that its top few hundred are good
Heavy ranking~1,500~1,500 scoredabout a millisecond of CPU, or a fraction on acceleratorsPrecision at the top: order candidates accurately
Filters, heuristics, mixing~1,500~50negligibleSafety, diversity, balance, product rules

Recall upstream, precision downstream. A post that no candidate source returns can never be shown, no matter how good the heavy ranker is. So retrieval is judged by recall: of the posts the viewer would have engaged with, what share made it into the 1,500? Ranking is judged by how well it orders the top: of the 50 posts shown, how many were good, and were the best ones first? Mixing up these goals is a common interview mistake. Making retrieval "smarter" at the cost of recall usually makes the feed worse.

Why several candidate sources? Each source sees a different slice of relevance:

  • the in-network index finds what the viewer's own network is posting;
  • the engagement graph finds what the viewer's network is enjoying;
  • embedding sources find content that matches the viewer's interests even when nobody they know is involved;
  • follow recommendations find accounts the viewer might want to follow, and their posts.

Each source alone has blind spots. Together they give high recall. The released code fetches up to about 600 posts from the in-network source, 400 from the out-of-network coordinator, 300 from the engagement graph and 100 from follow recommendations by default, which adds up to the ~1,500 the blog describes. These caps are budgets: they bound the cost of the next stage no matter how many matches each source finds.

The stages must agree. If the light ranker inside a source prefers different posts than the heavy ranker would, the source wastes its budget on posts the heavy ranker will place low. Two common fixes:

  1. Train light rankers on the same labels as the heavy ranker, with a subset of its features.
  2. Distil the heavy ranker into the light one: train the light model to predict the heavy model's score. This aligns the stages directly.

The Earlybird light ranker README says the current model was last trained several years ago and is being replaced. That is exactly the kind of drift between stages that slowly degrades a feed without any single failure.

Selection bias between stages. Each stage only sees what the previous stage passed. The heavy ranker is trained on impressions, which are posts that previous versions of the whole funnel chose to show. It has almost no training data about the kind of posts the funnel never shows. This is the root of the feedback-loop problems in deep dive 10.

Pre-filters before hydration. Some filters are cheap and certain: the post was deleted, the author is blocked by the viewer, the post was already served in this session. Running them before feature hydration saves the cost of hydrating and scoring posts that can never be shown. Filters that need model outputs (diversity, fatigue based on predicted similarity) must run after scoring. Safety filters run late as well, close to serving, so that a label applied a second ago still takes effect.

2. In-network candidates: the search index, Real Graph and the light ranker#

Why not a precomputed timeline cache? The classic fan-out-on-write design keeps, for each user, a list of recent post ids from accounts they follow. Its costs at this scale:

  • Write amplification. If the average post reaches 300 followers' timelines, 5,800 posts per second become about 1.7 million timeline inserts per second. An account with 100 million followers turns one post into 100 million inserts.
  • Memory. 400 million timelines × 800 post ids × 8 bytes ≈ 2.5 TB of cached lists, plus replicas, most of which are never read because most users are not active on a given day.
  • It still needs ranking. A cached list is ordered by time. A ranked feed must score those posts anyway.

Twitter's blog says it stopped using its 12-year-old Fanout Service for In-Network posts. The in-network source now queries the real-time search index directly.

The search index. Twitter's real-time search engine, Earlybird, was described by Michael Busch, Krishna Gade, Brian Larson, Patrick Lok, Samuel Luckenbill and Jimmy Lin in "Earlybird: Real-Time Search at Twitter" (ICDE 2012). In outline:

  • It is an inverted index (a map from each term to the list of documents that contain it), built for posts. Author id is one of the indexed fields, so "posts by author X" is just another posting list.
  • The index is partitioned by time: recent posts live in in-memory segments that are written continuously, and older segments are sealed. Within a time range, posts are spread across partitions.
  • Posting lists are kept so that the newest posts come first. A query for "recent posts by these authors" can stop early once it has enough good results.
  • Each index server computes a light ranking score while it scans, so it returns only its best candidates rather than every match.

A query from the in-network source looks like "posts from any of these ~1,000 authors in the last 24 hours, excluding replies to people the viewer does not follow, best 600 by light score". It goes to every partition in parallel, and a root node merges the per-partition results.

Real Graph: which followed accounts matter? A user who follows 1,000 accounts does not care about them equally. Real Graph predicts, for each (viewer, author) pair, how likely the viewer is to interact with the author. The open-source README describes two parts:

  • Daily aggregation. Batch jobs count interactions between pairs of users every day: public ones (likes, reposts, follows) and private ones (profile views, post clicks, and whether the author is in the viewer's address book, if the viewer opted in to share it). A rollup job combines yesterday's totals with today's into decayed sums, so recent interactions weigh more.
  • Prediction. A gradient-boosted tree classifier is trained on pairs that were active in a period, labelled by whether they interacted on the following day. It outputs a probability of interaction.

The in-network source uses the scores twice: to choose and weight which authors to query, and as a feature for ranking. The blog says that the higher the Real Graph score between viewer and author, the more of the author's posts are included.

The light ranker. The Earlybird light ranker README describes it as a logistic regression model that predicts the likelihood of engagement, a simplified version of the heavy ranker that can run on many more posts. There are two models: one for in-network posts and one for out-of-network posts from the engagement graph, differing mainly in their features. Its features come from four places:

  • Static post features, computed when the post is indexed: is it a repost, does it contain a link, does it contain trending words, is it a reply, a text-quality score (based on offensiveness, content entropy, "shouting", length and readability), and the author's reputation score.
  • Real-time post features, which change after indexing: like, reply and repost counts, and health-model scores such as the probability of toxicity and of being blocked. These are updated by a stream topology.
  • User table features, per author, looked up when scoring their posts.
  • Search context features, about the viewer: UI language, the languages they read and write, and the current time.

The author reputation score (tweepcred) is computed with a PageRank-style algorithm over the user graph: an account is reputable if reputable accounts interact with it. PageRank was introduced by Sergey Brin and Lawrence Page in "The Anatomy of a Large-Scale Hypertextual Web Search Engine" (WWW 1998).

Logistic regression is a good choice here. Its score is a weighted sum passed through a sigmoid:

p(engage) = 1 / (1 + exp(-(w0 + w1*x1 + w2*x2 + ... + wn*xn)))

With a few dozen features, that is tens of multiply-adds per post: well under a microsecond. An index server can score tens of thousands of matching posts per query inside its share of the latency budget. It is also easy to compute inside the index scan, next to the data, which is where light ranking belongs.

A worked example. Asha follows 900 accounts. Real Graph gives 120 of them a score above 0.05 and the rest much lower. The in-network query asks for posts from the top 500 authors by score in the last 24 hours. Those authors posted about 4,000 posts. Each index partition scores its share with the light ranker, the root merges them, and the source returns the top 600 with their light scores and author weights. Posts from Asha's most-engaged authors are strongly favoured, but a great post from a rarely-engaged author can still make the cut through its real-time engagement counts.

3. Out-of-network candidates from the engagement graph#

The first way to find out-of-network posts is collaborative filtering on a graph. The blog phrases it as two questions:

  • What posts did the people I follow recently engage with?
  • Who likes the same posts as me, and what else have they recently liked?

The data structure. GraphJet was described by Aneesh Sharma, Jerry Jiang, Praveen Bommannavar, Brian Larson and Jimmy Lin in "GraphJet: Real-Time Content Recommendations at Twitter" (VLDB 2016). It keeps a bipartite graph in memory:

  • the left side is users, the right side is posts;
  • an edge means "this user engaged with this post", labelled by the kind of engagement;
  • adjacency lists are kept in both directions (user to posts, post to users), so a traversal can go either way;
  • the graph is split into time segments. New edges go into the newest segment, and the oldest segment is dropped as a unit. That gives a moving window without deleting edges one by one.

The UTEG README says the service is stateful, ingests engagements from a Kafka stream and keeps the last 24 to 48 hours in memory, dropping older events. Recent engagement is the point: this source exists to find posts that are taking off right now among people related to the viewer.

The traversal. UTEG's README describes the core: take the viewer's weighted follow list (for example the top followed accounts with Real Graph weights), traverse to the posts those accounts engaged with, and aggregate. Each post's score combines how many of the viewer's weighted follows engaged with it and their weights. The output includes the social proof: which follows engaged, used later for the "Kai liked" label and for the social proof filter.

function graph_candidates(viewer, max_results):
    seeds = top_followed_accounts(viewer, n=200)          # (account, real_graph_weight)
    score = map()                                          # post_id -> weighted score
    proof = map()                                          # post_id -> list of accounts
    for (account, w) in seeds:
        for (post, engagement_type) in graph.recent_engagements(account, limit=100):
            if post.author in viewer.follows: continue     # in-network, skip
            score[post] += w * type_weight(engagement_type)
            proof[post].append(account)
    candidates = [p for p in score if len(proof[p]) >= 2]  # minimum social proof
    return top_k(candidates, key=score, k=max_results), proof

Two details keep this cheap and safe:

  • Bounded fan-out. Each seed contributes at most a fixed number of recent edges (here 100). Without that cap, a seed who liked 5,000 posts today would dominate the cost.
  • Social proof threshold. Requiring two or more of the viewer's follows to have engaged filters out noise from one person's odd taste.

Random walks. The second question ("who likes what I like, and what else do they like?") is a two-hop traversal: viewer → posts the viewer liked → other users who liked them → other posts those users liked. The number of paths explodes quickly, so engines use random walks. Start at the viewer, repeatedly step to a random neighbour (user to post, post to user), and count how often each post is visited. Frequently visited posts are strongly connected to the viewer. Restarting at the viewer with some probability at each step keeps the walk local. This is personalised PageRank estimated by Monte Carlo sampling.

Twitter's earlier "who to follow" system used a related algorithm, SALSA, over a bipartite graph of a user's "circle of trust" and the accounts they follow, as described by Pankaj Gupta, Ashish Goel, Jimmy Lin, Aneesh Sharma, Dong Wang and Reza Zadeh in "WTF: The Who to Follow Service at Twitter" (WWW 2013). SALSA itself comes from Ronny Lempel and Shlomo Moran ("SALSA: The Stochastic Approach for Link-Structure Analysis", ACM TOIS 2001). The same ideas carry over to posts.

Hot nodes. A viral post may have millions of engagement edges. A walk that reaches it would then step to a random one of millions of users, which is harmless, but iterating all of its edges is not. Engines sample neighbours of high-degree nodes instead of scanning them, and normalise scores by degree so that popular posts do not crowd out niche posts that are a better match.

Strengths and limits. Graph sources are fresh (seconds after a like), explainable ("because Kai liked it") and need no trained model. But they only reach posts that someone near the viewer has already engaged with. For a viewer with a small or quiet network, they return little. The blog notes that graph heuristics serve about 15% of Home Timeline posts, while embedding approaches have become the larger out-of-network source.

4. Out-of-network candidates from embedding spaces#

Graph traversals need someone near the viewer to have engaged first. Embeddings answer a more general question, as the blog puts it: which posts and users are similar to my interests? If users and posts live in the same vector space, retrieval becomes "find the post vectors closest to the viewer's vector".

SimClusters: sparse, interpretable community embeddings

SimClusters was described by Venu Satuluri and colleagues in "SimClusters: Community-Based Representations for Heterogeneous Recommendations at Twitter" (KDD 2020). The open-source README explains the pipeline in four steps.

Step 1: view follows as a bipartite graph. Split the directed follow graph into producers (accounts being followed) and consumers (accounts doing the following). Write it as a matrix A with one row per consumer and one column per producer; A[u][v] = 1 if consumer u follows producer v.

Step 2: find communities of producers ("Known For"). Two producers are similar if they are followed by similar sets of people. Compute the cosine similarity of their follower columns, build a producer-producer similarity graph, and delete weak edges (below a threshold) to remove noise. Then run a community detection algorithm (the README says it is based on Metropolis-Hastings sampling) with a target number of communities k. The result is the KnownFor matrix V with one row per producer and one column per community. It is maximally sparse: each producer belongs to at most one community. In production, KnownFor covers the top 20 million producers with k ≈ 145,000 communities.

Step 3: consumer interests ("InterestedIn"). Multiply: U = A × V. Row u of U counts, for each community, how many of that community's producers consumer u follows. After normalisation and noise removal, U[u] is consumer u's InterestedIn vector: a sparse vector of community weights describing long-term interests.

A toy example makes it concrete. Three producers: p1 and p2 (two baking accounts) are known for community C1 ("home baking"), and p3 (a football account) is known for C2 ("football").

ConsumerFollowsU = A × V (C1, C2)Reading
Ashap1, p2(2, 0)Interested only in baking
Kaip2(1, 0)Interested only in baking
Samp1, p2, p3(2, 1)Mostly baking, some football

Step 4: embed everything else in the same space.

  • Producer embeddings. KnownFor allows one community per producer, but real accounts post about several topics. A richer producer vector is computed from the cosine similarity between the producer's followers and each community's InterestedIn vectors. It powers "similar posts to accounts you just followed".
  • Post embeddings. A new post starts with an empty vector. Every time someone likes it, that user's InterestedIn vector is added to the post's vector. A streaming job updates these vectors in real time, so a post's embedding describes who is enjoying it right now. The blog says it the simple way: the more users from a community like a post, the more the post is associated with that community.
  • Topic embeddings come from aggregating the favourites of users interested in each community on posts annotated with a topic, with time decay.

Retrieval with SimClusters. Because vectors are sparse and indexed by community, the index is simple: for each community, keep the top posts by their weight in that community (the README calls the online service SimClusters ANN, and describes batch-built cluster-to-top-posts indexes for other surfaces too). A request takes the viewer's top communities from InterestedIn, fetches each community's top posts, and scores each post by the dot product of the viewer's and the post's sparse vectors.

Why sparse communities rather than dense vectors? Three reasons. They are interpretable: a community can be inspected by looking at its top producers. They are cheap to update: adding a liker's vector to a post touches only that liker's few non-zero communities. And they support inverted-index retrieval (community → posts), which is fast and easy to shard. The blog says communities range from a few thousand users (friend groups) to hundreds of millions (news, pop culture), and are recomputed every three weeks.

TwHIN and two-tower models: dense embeddings

Dense embeddings put every entity in a space of, say, 64 to 256 dimensions, where every coordinate is used.

TwHIN was described by Ahmed El-Kishky and colleagues in "TwHIN: Embedding the Twitter Heterogeneous Information Network for Personalized Recommendation" (KDD 2022). The open-source README describes training dense embeddings from several graph relations at once ("User follows User", "User favorites Tweet", "User clicks Advertisement"), with each edge stored as (left node, relation, right node). Such knowledge-graph embeddings learn one vector per node and per relation, so that a scoring function of (left vector, relation, right vector) is high for edges that exist and low for random pairs (negative sampling). The README says TwHIN embeddings are used both for candidate retrieval and as features in ranking models.

The other common approach is a two-tower model, used widely across industry:

  • a user tower (a neural network) turns user features and recent history into a vector u;
  • a post tower turns post features (text, media, author) into a vector v;
  • the model is trained so that the dot product u · v is high for (user, post) pairs with engagement.

Paul Covington, Jay Adams and Emre Sargin described this style of retrieval for YouTube in "Deep Neural Networks for YouTube Recommendations" (RecSys 2016), treating candidate generation as classification over a huge set of videos. Xinyang Yi and colleagues described training two-tower models with in-batch negatives and a correction for sampling bias in "Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations" (RecSys 2019).

The towers must stay separate (no feature crosses between user and post) so that post vectors can be computed ahead of time and indexed. Only the user vector is computed at request time. That is the price of retrieval speed: the model cannot use interactions between user and post features, which is the heavy ranker's job.

In-batch negatives and the popularity correction. With in-batch negatives, the other posts in a training batch act as negatives for each user. Popular posts appear in many batches, so they are used as negatives too often and the model learns to under-rate them. The fix subtracts log(probability that the post appears in a batch) from the logit during training, the "logQ correction". Without it, two-tower retrieval tends to return niche posts. With too strong a correction, it returns only popular ones.

Given a user vector, we need the top few hundred post vectors by dot product among hundreds of millions. A brute-force scan of 500 million 128-dimensional vectors costs 64 billion multiply-adds, about tens of milliseconds on a fast accelerator but far too much on CPUs at 58,000 requests per second. ANN indexes avoid the full scan:

  • HNSW (Hierarchical Navigable Small World), introduced by Yury Malkov and Dmitry Yashunin (arXiv 2016, later in IEEE TPAMI), builds a layered proximity graph. Upper layers are sparse long-range "highways", the bottom layer contains every vector. A search starts at the top, greedily moves to closer nodes, and descends layer by layer. Search visits a few thousand nodes instead of millions. Its memory overhead is the graph links (tens of bytes per vector per layer), and it handles inserts well.
  • IVF-PQ combines an inverted file (cluster vectors with k-means into, say, 65,536 lists; search only the few dozen lists nearest to the query) with product quantization (split each vector into sub-vectors and replace each with the id of its nearest centroid, compressing a 512-byte vector to 32 or 64 bytes). Product quantization was introduced by Hervé Jégou, Matthijs Douze and Cordelia Schmid in "Product Quantization for Nearest Neighbor Search" (IEEE TPAMI 2011). It is the basis of many FAISS indexes.
  • ScaNN, from Ruiqi Guo and colleagues at Google ("Accelerating Large-Scale Inference with Anisotropic Vector Quantization", ICML 2020), improves quantization for dot-product search.

The main dial is recall versus latency. With HNSW, a larger search list (often called ef_search) visits more nodes: recall@100 might go from 90% to 98% while latency doubles. For retrieval, 90% to 95% recall is usually enough, because several sources overlap and the heavy ranker re-scores everything anyway.

Freshness in a vector index. Posts are created at 5,800 per second and matter most in their first hours. Three patterns keep indexes fresh:

  1. Time-partitioned indexes. Keep one index per hour (or few hours). New posts go into the current, small, mutable index. Older indexes are sealed and optimised. Queries go to all of the last 48 or so, and the oldest is dropped each hour.
  2. Embedding updates. Engagement-based embeddings (like SimClusters post vectors) change as likes arrive. Community-to-top-posts indexes are simple to update: change the post's weight in a few communities.
  3. Periodic re-embedding. When the post tower model changes, every indexed post must be re-embedded with the new model. User and post vectors from different model versions are not comparable. Versioned indexes are built side by side and switched together with the user tower.

Filtering inside retrieval. Some constraints are best applied in the index: language, sensitive-media settings, "not older than 48 hours". Filtering after ANN search can leave too few results when the filter is selective, so indexes are often partitioned by the most selective attributes (for example language) or support filtered search natively.

5. Light and heavy ranking: from probabilities to one score#

After retrieval, about 1,500 candidates arrive from different sources with incomparable scores. The heavy ranker scores them all with one model. The blog stresses that, at this stage, all candidates are treated equally regardless of their source.

The model. The heavy ranker README describes:

  • inputs: features describing the post and the viewer (the home-mixer README says about 6,000 features are hydrated for ranking);
  • architecture: a parallel MaskNet, a neural architecture for click-through-rate prediction introduced by Zhiqiang Wang, Qingyun She and Junlin Zhang in "MaskNet: Introducing Feature-Wise Multiplication to CTR Ranking Models by Instance-Guided Mask" (arXiv 2021);
  • outputs: a set of numbers between 0 and 1, each the probability of one kind of engagement. The blog describes about 48 million parameters and ten labels, trained continuously on engagement data.

Why multi-task? A single "will engage" label hides important differences. A like is cheap. A reply means much more. A report means the post was harmful to this viewer. One shared network with one output head per engagement type learns all of them from the same features, and the rare labels (replies, reports) benefit from what the frequent labels teach the shared layers.

The ten predicted engagements and their weights. The README lists the outputs and the weights used to combine them as of 5 April 2023:

Predicted engagementWeight
Like (favourite)0.5
Repost (retweet)1.0
Reply13.5
Opens the author's profile and likes or replies to a post12.0
Watches at least half of a video0.005
Replies, and the author engages with that reply75.0
Clicks into the conversation and replies or likes11.0
Clicks into the conversation and stays at least 2 minutes10.0
Negative feedback (show less, block or mute the author)−74.0
Reports the post−369.0

The final score is a weighted sum:

score = Σ over engagement types i of  weight_i × P(engagement_i)

The README explains the logic of the weights. Each engagement has a very different average probability (likes are common, replies to which the author responds are rare). The weights were originally set so that, on average, each weighted probability contributes about equally to the score, and they have since been adjusted periodically to optimise platform metrics. The weights live in configuration, so they can be changed without retraining.

A worked example. Two candidates for Asha:

Post A (meme)Post B (question from a baker Asha follows)
P(like)0.200.08
P(repost)0.040.01
P(reply)0.0020.020
P(reply engaged by author)0.00010.006
P(good click)0.010.03
P(negative feedback)0.0030.0005
P(report)0.00010.00001

Ignoring the other labels for brevity:

  • A: 0.5×0.20 + 1.0×0.04 + 13.5×0.002 + 75×0.0001 + 11×0.01 − 74×0.003 − 369×0.0001 = 0.100 + 0.040 + 0.027 + 0.0075 + 0.110 − 0.222 − 0.037 ≈ 0.026
  • B: 0.5×0.08 + 1.0×0.01 + 13.5×0.020 + 75×0.006 + 11×0.03 − 74×0.0005 − 369×0.00001 = 0.040 + 0.010 + 0.270 + 0.450 + 0.330 − 0.037 − 0.004 ≈ 1.059

Post A is far more likely to be liked, but Post B wins by a factor of 40. The weights make conversations, not quick likes, the main currency of the feed, and a small chance of negative feedback costs as much as a large chance of a like. This is the most important lesson of the weighted-sum design: the weights are the product's values, written as numbers.

Calibration matters. A weighted sum of probabilities only makes sense if the probabilities are calibrated: when the model says 2%, about 2% of such impressions should get that engagement. If a new model's P(reply) is systematically 30% too high, replies get 30% more weight in the feed without anyone deciding so. Calibration is checked per label and per segment (new users, languages, in-network versus out-of-network), and corrected with a final calibration layer (for example isotonic regression or Platt scaling) when needed.

Post-scoring adjustments. Scores are then adjusted by rules. The current public code includes, for example, a scale factor for out-of-network posts (default 0.75) and for replies (default 0.75), so that an out-of-network post must score about a third higher than an in-network one to be placed above it. Defaults in the code change over time; the point is that business rules adjust model scores multiplicatively after scoring, and the adjustments are configuration under experiment control.

Serving the heavy ranker. Scoring 1,500 candidates in about 100 to 200 milliseconds requires:

  • Batching. All candidates of a request go to the model server in one or a few batches. Accelerators are efficient only with large batches.
  • Shared computation. Viewer features are identical across the 1,500 rows. Some architectures compute the viewer part once and broadcast it.
  • A fast server. Twitter's open-source Navi is a model server written in Rust, compatible with the TensorFlow Serving gRPC API, with runtimes for TensorFlow and ONNX (PyTorch experimental). Alternatives are NVIDIA Triton, TensorFlow Serving and TorchServe.
  • Model versions side by side. Several model versions run at once for experiments. Requests name the version chosen by their experiment bucket.

Why not just use the heavy ranker in the sources? Because the light rankers run inside the indexes over tens of thousands of matches per query, where the heavy ranker would be 1,000 times too expensive. The heavy ranker sees only the 1,500 the light stages chose.

6. The feature store and real-time signals#

The heavy ranker is only as good as its features, and features are where most production bugs in recommenders live. This deep dive covers what the features are, how they are computed and served, and how to keep training and serving consistent. The general concepts are covered in ML System Design and Feature Stores; here we apply them to a feed.

Five families of features.

FamilyExamplesChangesFetched
Viewerlanguage, country, account age, follow count, engagement rates by content type over 1, 7 and 30 dayshours to daysonce per request
Authorfollower count, reputation, recent engagement rate, posting frequency, safety scoreshoursonce per author
Posthas media, has link, language, text quality, age, like/reply/repost counts in the last 5 minutes, hour and daysecondsper candidate, heavily cached
Viewer × authorReal Graph score, past likes and replies to this author, mutual follow, address book matchdailyper (viewer, author)
Viewer × posthow many of the viewer's follows engaged with the post, embedding similarity (SimClusters, TwHIN), topic matchper requestcomputed at request time

The cross features at the bottom are often the most predictive. "Three people you follow replied to this" says more than any single post or viewer feature. They are also the most expensive, because they cannot be precomputed per post or per viewer alone. The open-source graph feature service exists for this: it serves features for a directed pair of users, such as how many of user A's follows liked posts from user B.

Aggregate features: one definition, two pipelines. Many features are aggregates: "count of the viewer's likes on video posts in the last 30 days", "the author's reply rate over 7 days". Twitter's open-source code includes a timelines aggregation framework for generating aggregate features in batch or in real time from the same definitions. That is the right pattern: define an aggregate once (keys, filter, window, function) and let the framework compute it both offline (for training and for long windows) and in a stream (for short windows), so the two can never disagree about what the feature means.

# One aggregate feature definition, compiled to batch and streaming jobs.
aggregate: viewer_likes_by_media_type
keys: [viewer_id, media_type]          # media_type: none | image | video
source: unified_user_actions
filter: action == "like"
windows: [1h, 1d, 7d, 30d]
function: count
decay: none
outputs:
  online_store: uf:{viewer_id}          # merged into the viewer feature blob
  offline_store: features.viewer_likes_by_media_type   # hourly snapshots
streaming:
  engine: flink
  windows: [1h, 1d]                     # short windows updated in real time
batch:
  engine: spark
  windows: [7d, 30d]                    # long windows recomputed daily
  schedule: "0 2 * * *"

Real-time post counters. Post features change fastest. A post that went from 10 to 10,000 likes in ten minutes is a different candidate. A stream job keeps, per post, counts of each engagement type in small time buckets (for example 1-minute buckets for the last hour, then hourly buckets), and derives windowed counts and velocity ("likes in the last 5 minutes compared with the previous hour").

Hot posts make this hard: a viral post may get tens of thousands of engagements per second, all keyed on one post id. The fixes are standard:

  • Pre-aggregate in the stream processor (sum per key for a second, then write once).
  • Split hot keys across several sub-keys and sum on read.
  • Write counters to the online store at most once per second per post, not per event.

See Apache Flink and Stream Processing and Cache Failure Modes: Stampedes, Hot Keys and Penetration.

User signals. The open-source user signal service is a central place to get a user's explicit signals (likes, replies) and implicit ones (profile visits, post clicks). Candidate sources use these as seeds ("posts similar to the five posts Asha liked in the last hour"), and the ranker uses them as features. Real-time signals let the feed react within a session. If Asha likes three football posts in a row during a match, the next refresh should show more football, long before any batch job runs.

Serving features fast. A request needs features for about 1,500 posts, perhaps 800 distinct authors and one viewer:

  • Batch everything. One multi-get per store per request, not one call per candidate. A multi-get of 1,500 keys against a sharded key-value store fans out to many shards in parallel and returns in a few milliseconds.
  • Deduplicate by entity. Fetch author features once per author and viewer features once per request.
  • Cache post features in process. The same popular posts are candidates for millions of viewers. A small in-process cache with a TTL of seconds on the hydration servers absorbs most post lookups.
  • Pack values compactly. Store a whole feature group as one binary blob per entity. Reading one 4 KB blob is far cheaper than reading 1,000 small keys.
  • Default missing values. If a store times out, the feature is marked missing and the model uses its trained default. The model must have seen missing values during training, or a store outage silently becomes a model failure.

Point-in-time correctness. For training, every feature must have the value it had at the moment of the impression, not its value today. Suppose the training job attaches the post's current like count. A post shown to Asha at 09:00 with 10 likes went viral at 10:00 and now has 50,000. The training example would say "posts with 50,000 likes get liked", but at serving time no post has its final like count. That is label leakage, and it produces models that look excellent offline and disappoint in production.

Two ways to get point-in-time features:

  1. Log at serving time. The feature service writes the exact values it served for each (request, candidate) to the log. Training uses those. This is the most reliable method and the one our design uses for the main model.
  2. As-of joins. The offline store keeps timestamped feature values, and the training job joins each impression to the latest value before the impression time. This is needed to train with a new feature that was never logged (backfilling), and must be implemented carefully.

Training-serving skew is any difference between the features a model saw in training and the ones it sees in production: a different code path computes "account age" in days in one place and in hours in the other, a default differs, a stream lags. Logged features remove most of it. Monitoring catches the rest: compare each feature's distribution in live traffic with its distribution in the latest training data, and alert on drift.

Freshness tiers. Not every feature needs to be real time, and real time is expensive:

TierLatencyExamplesHow
Request time0viewer × post similarity, time since postcomputed in hydration
Secondsunder 1 minutepost engagement counters, recent user actionsstream jobs into the online store
Hours1 to 24 hoursviewer and author aggregates over dayshourly or daily batch
Days to weeks1 day to 3 weeksReal Graph (daily), SimClusters communities (every three weeks), reputationbatch

7. Filtering, heuristics and diversity#

The heavy ranker scores each post independently. A page is a set, and a good set is not just the top 50 individual scores. This stage turns a ranked list into a good page.

Visibility filtering. The open-source visibility filtering library is a central rule engine. Its concepts are a useful template for any platform:

  • Safety level: the product context of the request (home timeline, profile, search). Each has its own policy.
  • Features: safety labels on the post or author, flags on users (including the viewer), relationships (block, mute, follow), the viewer's settings, and relationships between users and content (for example "reported for spam").
  • Conditions: boolean checks over features, combined into rules.
  • Policy: an ordered list of rules per safety level. The first matching rule decides.
  • Action: what the client should do: drop the post (hard filter), show it behind a label or interstitial (soft filter), or apply a ranking hint (down-rank).

Visibility filtering fails closed. If labels for a post cannot be fetched within the deadline, the post is dropped from this page rather than shown unchecked. It runs late, after ranking, so that a block, mute or safety label applied seconds ago still takes effect, and again on cached pages, because a cached list may be minutes old.

Author diversity. Without a rule, a prolific author with several high-scoring posts can fill the top of the page. The current public code has author-diversity parameters with a decay factor of 0.5 and a floor of 0.25 by default (with separate values for in-network and out-of-network posts). One simple form consistent with those parameters: the k-th post from the same author on the page (k = 0 for the first) has its score multiplied by

multiplier(k) = (1 - floor) × decay^k + floor
              = 0.75 × 0.5^k + 0.25         → 1.0, 0.625, 0.4375, 0.34, ...

An author's second post needs a raw score 1.6 times higher than a competing post to take the next slot, and the third post 2.3 times higher. Strong posts still appear, but no author dominates. The rescoring is applied in order: walk the sorted list, adjust each post's score by how many posts from its author are already above it, and re-sort.

In-network and out-of-network balance. The blog says the feed is about half in-network and half out-of-network on average. The scale factor on out-of-network scores (deep dive 5) is the main lever, and some systems also enforce a minimum share of in-network posts on each page so that a user's friends never disappear entirely.

Feedback-based fatigue. When a viewer taps "show less" on a post, the heuristic lowers the score of related posts: the same author, posts with very similar embeddings, posts liked by the same people (for graph-based candidates). The penalty decays over days. The current public code also has "show less" and "show more" controls applied with an embedding-similarity threshold, which is the natural way to generalise feedback from one post to "posts like this".

Social proof for out-of-network posts. The blog describes a quality safeguard: out-of-network posts without a second-degree connection are excluded. In other words, someone the viewer follows engaged with the post or follows its author. It trades a little discovery for a lot of protection against spam and engagement farming from strangers.

Already seen. Posts the viewer already saw are removed. The seen set holds post ids served in the last few days. A per-user Bloom filter keeps it small: a viewer who sees 1,000 posts a day for 7 days has 7,000 ids, and a Bloom filter with a 1% false-positive rate needs about 9.6 bits per item, about 8.4 KB per user. The cost of a false positive is only that one unseen post is skipped. See Probabilistic Data Structures for Big Data.

Diversity beyond authors. Author caps are the minimum. Feeds also diversify by topic, media type and source. Two principled methods:

  • Maximal marginal relevance (MMR), from Jaime Carbonell and Jade Goldstein ("The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries", SIGIR 1998). Build the page one item at a time. At each step pick the candidate with the best balance of its own score and its dissimilarity to what is already on the page: λ × score(item) − (1 − λ) × max similarity(item, page).
  • Determinantal point processes (DPPs) score a whole set by the determinant of a kernel matrix built from item quality and pairwise similarity, which naturally favours sets of good, mutually different items. Mark Wilhelm and colleagues described using them at YouTube in "Practical Diversified Recommendations on YouTube with Determinantal Point Processes" (CIKM 2018).

Calibrated mixes. Harald Steck ("Calibrated Recommendations", RecSys 2018) argued that a list should reflect the proportions of a user's interests. If Asha's engagement is 70% baking and 30% football, a page that is 100% baking is over-specialised even if every post scores well. Calibration keeps minority interests alive and is a direct counter to narrowing.

Filter bubbles. Eli Pariser's book "The Filter Bubble" (2011), as Wikipedia's article on the term describes, argued that personalisation could isolate people from differing views. Wikipedia also notes that other researchers consider the effect small and addressable. For the designer, the practical response is the same either way: diversity and calibration in the page, exploration in retrieval (deep dive 10), and metrics that track narrowing over time, not only engagement.

Mixing. Finally the page is assembled. Ads come from a separate ad system and are placed at allowed positions (for example never first, at least a few posts apart). Who-to-follow modules and prompts take a few slots. Replies are threaded with their parents into conversation modules, so a reply is not shown without its context. Social context ("Kai liked", "Sam follows") is attached from the social proof the sources returned.

8. The serving latency budget#

The blog says the whole pipeline completes in under 1.5 seconds on average. Hitting that, at 58,000 requests per second with dozens of dependencies, is a budgeting exercise.

The budget. A realistic split for a fresh page (our design targets, not published figures):

StepTypical timeRuns
Gateway, authentication, routing10–20 msfirst
Load viewer context: signals, seen set, experiments20–40 msparallel
Candidate sources150–300 msall sources in parallel
Merge, dedupe, pre-filters5–10 msafter sources
Feature hydration100–200 msparallel multi-gets
Heavy ranker inference100–250 msbatched
Heuristics, visibility filtering, rescoring30–60 msafter scoring
Mixing: ads, modules, conversations50–100 msads fetched in parallel with ranking
Hydrate post content and marshal response30–50 mslast
Total on the critical path~500 ms to ~1 s typical, ~1.5 s at p99

Parallelism is the main tool. The critical path is the sum of the slowest branch at each step, not the sum of all work. All candidate sources run in parallel. Ads are fetched while ranking runs. The 220 CPU-seconds the blog mentions fit into about a second of wall-clock time only because the work is spread over hundreds of machines.

Deadlines, not just timeouts. Each request carries an absolute deadline. Every call receives the remaining budget, so a source that starts late gets less time. When a candidate source misses its deadline, Home Mixer proceeds without it: the feed has fewer candidates from that source, but it is not late. Ranking with 1,200 candidates instead of 1,500 is invisible to users. A page that takes 4 seconds is not. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

Tail latency compounds. If a request fans out to 100 index partitions and each has a 1% chance of taking more than 200 ms, then 1 − 0.99¹⁰⁰ ≈ 63% of requests wait for at least one slow partition. Jeffrey Dean and Luiz André Barroso described the remedies in "The Tail at Scale" (Communications of the ACM, 2013):

  • Hedged requests: after waiting for the 95th-percentile latency, send the same request to another replica and use whichever answers first. This costs a few percent more load and cuts the tail sharply.
  • Partial results: return when 98% of partitions have answered, because the missing 2% changes very little.
  • Micro-partitioning: many small partitions per machine, so a slow machine's work can be moved quickly.

Cache the expensive part. Full ranked lists are cached per viewer for a few minutes (the current public code's default for cached scored posts is 3 minutes). Scrolling and quick refreshes reuse them. If half of all requests are "load more" within a session, the cache roughly halves heavy-ranking cost.

Degrade in steps. Under overload or partial failure, the service steps down a ladder rather than failing:

  1. Drop optional candidate sources (keep in-network and the largest out-of-network source).
  2. Reduce the candidate budget (1,500 → 800) so hydration and ranking are cheaper.
  3. Serve cached ranked lists longer (stale but personalised).
  4. Fall back to light-ranker scores only.
  5. Serve the reverse-chronological backup pipeline (the home-mixer README describes one, used when scored posts fail).

Each step is triggered automatically by load or error rates, and each is visible on dashboards. See Observability: Logs, Metrics and Traces.

9. Cold start: new users, new posts and new authors#

Every learned signal in this design comes from history: Real Graph needs past interactions, InterestedIn needs follows, post embeddings need likes, the heavy ranker's best features are engagement counts. Cold start is what happens when that history is missing. Wikipedia's article on cold start distinguishes three cases: a new community (a new system with almost no users), a new item and a new user. We add a fourth that matters on a social network: a new author.

New users

A brand-new user follows nobody, so there are no in-network candidates, no Real Graph scores, an empty InterestedIn vector and no engagement history. What still works:

  1. Onboarding signals. Ask for a few topics of interest and suggest accounts to follow (follow recommendations are a separate recommender with its own candidates and ranking). Even five follows give the system InterestedIn communities through U = A × V, because the followed accounts' communities are already known.
  2. Context. Language, country, device and sign-up source give a rough prior. "Popular in your country and language in the last few hours" is the classic fallback feed and is reasonable for anyone.
  3. A higher share of out-of-network posts. With no network, the 50/50 balance makes no sense. New users get mostly out-of-network posts from popular, high-quality, broadly appealing sources, and the share shifts towards in-network as they follow accounts.
  4. Fast learning in the session. Real-time user signals are most valuable here. Three likes in the first minutes say a great deal. Candidate sources seeded on "posts similar to what this user just liked" adapt the feed during the very first session.
  5. Different heuristics. The current public code has separate author-diversity parameters for viewers with a small follow graph, a sign that rules tuned for established users do not fit new ones.

Exploration as a bandit problem. For a new user, each topic is like a slot machine with an unknown payout: we can show posts from it and observe engagement. The multi-armed bandit framing (Wikipedia's article covers the classic formulation) makes the explore-exploit trade-off explicit. Thompson sampling, first proposed by William R. Thompson in 1933, is simple and works well:

  • keep a Beta(α, β) distribution per topic for this user's engagement rate, starting at Beta(1, 1) (uniform);
  • on each request, draw one sample from each topic's distribution and favour the topics with the highest draws;
  • after each impression, add 1 to α on engagement and 1 to β otherwise.

A worked example. After the first session, Asha's counts are: baking 6 engagements in 20 impressions, Beta(7, 15), mean 0.32; football 1 in 10, Beta(2, 10), mean 0.17; science 0 in 2, Beta(1, 3), mean 0.25. The science posterior is wide because it has only two observations, so its draw beats baking's about a third of the time, and science keeps getting some exposure until the evidence settles. Football, with ten observations and a low rate, fades. Topics are never ruled out by bad luck in two impressions, and strong topics are exploited quickly. For contextual versions that share learning across users, see the LinUCB approach of Lihong Li, Wei Chu, John Langford and Robert Schapire ("A Contextual-Bandit Approach to Personalized News Article Recommendation", WWW 2010).

New posts

A post created a second ago has no likes, so:

  • its SimClusters post vector is empty (it is built from the InterestedIn vectors of the people who like it);
  • its engagement counters are zero;
  • the engagement graph has no edges to it.

How a new post gets its first impressions:

  1. In-network first. The search index makes the post retrievable by the author's followers within seconds. Followers are the natural first audience, and their engagement bootstraps everything else: the first likes create graph edges and fill the post's community vector.
  2. Content-based embeddings. A text and media encoder can embed a post at creation time from its content alone, so embedding retrieval can find it before anyone engages. This is the standard cure for item cold start.
  3. The author as a prior. The author's producer embedding and historical engagement rates are good priors for a new post by that author. The heavy ranker's author features carry this prior automatically.
  4. Time-aware features. The model sees "age of post" and "likes per minute since posting". A post with 50 likes in its first 3 minutes is extremely promising, while the same 50 likes after 3 days are not. Velocity, not totals, is the signal for new posts.
  5. Exploration traffic. A small, controlled share of impressions goes to new posts that the model is uncertain about, so the system learns their quality. The current public code includes parameters for content exploration candidate pipelines and for cold-start category candidates (off by default in the version we read). Treating exploration as an explicit candidate pipeline with its own budget makes its cost visible and tunable.

New authors

A new account with no followers is the hardest case: no in-network audience to bootstrap its posts. Without help, it can post forever and never be seen, so the network stops growing new voices. Remedies:

  • content-based embeddings for its posts, so they can be retrieved by interest;
  • exploration quotas reserved for posts by new or small authors;
  • follow recommendations that include new accounts with good early signals;
  • protection against abuse: new accounts are also where spam starts, so exploration traffic for new authors goes through stricter quality and safety checks.

The short-video case study covers cold start for a feed where nearly every candidate is out-of-network, and real-time training that learns from new items within minutes.

10. Feedback loops, bias and evaluation#

A recommender learns from engagement with what it chose to show. That loop is the source of its power and of its subtlest failures.

Biases created by the loop

  • Selection bias. The model is trained only on posts that the previous model chose to show. It has almost no data about posts it never shows, so it cannot learn that some of them are good. Over time, recommendations narrow towards what the system already believes.
  • Position bias. A post at position 1 gets more engagement than the same post at position 20, simply because more people see it and the top of the screen gets more attention. If training ignores position, the model learns "posts the old model ranked first are good", which reinforces the old model.
  • Popularity bias. Popular posts get more impressions, more engagement and more training data, so the model gets more confident about them and shows them more. The rich get richer, and niche content starves.
  • Degenerate feedback loops. Ray Jiang, Silvia Chiappa, Tor Lattimore, András György and Pushmeet Kohli studied when such loops make a user's recommendations collapse onto a narrow set of items ("Degenerate Feedback Loops in Recommender Systems", AIES 2019), and showed that exploration and a growing candidate pool slow the collapse.

Corrections

  1. Exploration. Reserve a small share of slots (for example 1% to 5%) for candidates chosen with randomness, logging the probability with which each was chosen (the propensity). This produces training data outside the model's comfort zone and enables unbiased offline evaluation.
  2. Position as a feature. Train with the position the post was shown at as a feature, then at serving time set it to a fixed value (for example position 1) for every candidate. The model learns how much engagement is due to position and factors it out.
  3. Inverse propensity weighting. Weight each training example by 1 / P(examined at that position). Thorsten Joachims, Adith Swaminathan and Tobias Schnabel formalised this for ranking in "Unbiased Learning-to-Rank with Biased Feedback" (WSDM 2017). Examination probabilities can be estimated from randomised experiments that swap positions.
  4. Popularity correction in retrieval. The logQ correction for two-tower models (deep dive 4) and degree normalisation in graph walks (deep dive 3).
  5. Diversity and calibration in the page (deep dive 7), so that minority interests keep generating data.

Offline evaluation

Offline metrics are cheap and fast, and they are the first gate for a new model:

  • Log loss (cross-entropy) per label, often normalised by the log loss of always predicting the average rate. Xinran He and colleagues used this "normalised entropy" in "Practical Lessons from Predicting Clicks on Ads at Facebook" (ADKDD 2014). Lower is better, and it rewards calibrated probabilities.
  • AUC per label: the probability that a random positive example is scored above a random negative one. It measures ordering, not calibration.
  • Calibration: the ratio of the average predicted probability to the observed rate, overall and per segment. It should be close to 1.
  • Ranking metrics per request: NDCG@k (normalised discounted cumulative gain, from Kalervo Järvelin and Jaana Kekäläinen, "Cumulated Gain-Based Evaluation of IR Techniques", ACM TOIS 2002) rewards placing the most valuable posts at the top.
  • Retrieval recall@K: of the posts the viewer engaged with, the share that a candidate source would have returned in its top K. This is how candidate sources are compared.

NDCG in one example. Suppose a page shows five posts with gains (for example 3 for a reply, 1 for a like, 0 for nothing) of [3, 0, 1, 0, 1]. DCG = Σ gain_i / log₂(i + 1) = 3/1 + 0/1.585 + 1/2 + 0/2.322 + 1/2.585 = 3 + 0 + 0.5 + 0 + 0.387 = 3.887. The ideal order [3, 1, 1, 0, 0] gives 3 + 1/1.585 + 1/2 = 3 + 0.631 + 0.5 = 4.131. NDCG = 3.887 / 4.131 ≈ 0.94. Swapping the reply with the post at position 3 gives [1, 0, 3, 0, 1], a DCG of 1 + 1.5 + 0.387 = 2.887, and NDCG drops to about 0.70.

Off-policy evaluation. Logged data only tells us what users did with what the old policy showed. To estimate how a new policy would do without deploying it, the inverse propensity score estimator re-weights logged outcomes: for each logged impression where the new policy would have made the same choice, count its reward divided by the probability that the old policy made that choice. Lihong Li, Wei Chu, John Langford and Xuanhui Wang showed this "replay" approach on Yahoo! news data in "Unbiased Offline Evaluation of Contextual-Bandit-Based News Article Recommendation Algorithms" (WSDM 2011). It needs logged propensities, which is one more reason for explicit exploration.

Online evaluation

Offline gains often do not transfer, because offline data comes from the old policy. Every change ships through an online experiment. The experimentation platform case study covers the machinery; here are the parts specific to feeds:

  • Primary metrics: engagement per user (weighted like the score), time spent, sessions per user, and the long-run one: retention (are users coming back next week?).
  • Guardrail metrics: negative feedback rate, reports, blocks, unfollows, latency, error rate, and the in-network share. A model that raises likes but also raises reports is not shipped.
  • Interleaving. For comparing two rankers quickly, merge their lists into one page (alternating picks, as in team-draft interleaving) and see which ranker's items get more engagement. Olivier Chapelle, Thorsten Joachims, Filip Radlinski and Yisong Yue showed that interleaving detects differences with far fewer users than A/B tests ("Large-Scale Validation and Analysis of Interleaved Search Evaluation", ACM TOIS 2012).
  • Holdouts. Keep a small group of users on an older system for months to measure long-term effects that short tests miss: novelty that wears off, slow narrowing, effects on creators.
  • Network effects. A social feed breaks the "users are independent" assumption. If treatment users reply more, authors in the control group get more replies too. Cluster-randomised designs (randomise by groups of connected users) reduce this interference.

Goodhart's law in a feed. Any metric that becomes a target can be gamed, by the model as much as by people. Optimising raw engagement favours outrage and engagement bait. That is why the score has large negative weights for negative feedback and reports, why "good click" labels require dwell time or further engagement, and why long-term retention, not daily engagement, is the metric that decides launches.

11. Integrity: spam, manipulation and engagement bait#

A recommender that rewards engagement invites people to manufacture engagement. Every signal in this design can be attacked:

SignalAttackEffect
Like and repost countsBot networks or paid engagementInflated real-time features; post looks viral
SimClusters post vectors (sum of likers' interests)Coordinated likes from accounts in a target communityPost is pushed into that community's top list
Engagement graphFake accounts that follow real users and like spamSpam reaches real users with "liked by" social proof
Replies (weighted 13.5, or 75 when the author engages)Reply rings and "reply to win" baitBait outranks genuine conversation
Negative feedbackMass reporting of a rivalLegitimate posts are suppressed

Defences, layer by layer.

  1. Weight engagement by trust. A like from an account with a long history and good reputation counts more than a like from a day-old account. Reputation scores (the open-source code's tweepcred is PageRank-based) and account-level spam scores feed directly into counters and embeddings.
  2. Detect coordination. Many accounts created together, engaging with the same posts within seconds, are a pattern. Stream jobs watch for bursts of engagement from low-trust or tightly clustered accounts, and hold suspicious counts out of features until reviewed.
  3. Model health signals. The light ranker already uses health-model outputs such as the probability of toxicity and of being blocked. The open-source repository includes trust-and-safety models for detecting NSFW and abusive content. Their outputs are features for ranking and inputs to visibility filtering.
  4. Social proof requirements. Requiring a second-degree connection for out-of-network posts limits what a stranger's bot network can push to a given viewer.
  5. Large negative weights. The −74 weight for predicted negative feedback and −369 for predicted reports mean that content likely to be reported is heavily demoted even before any report is filed.
  6. Rate limits on actions. Caps on likes, follows and replies per account per hour limit what automated accounts can do. See Rate Limiting and Throttling.
  7. Robust reporting. Reports are weighted by reporter reliability, and mass reports from a coordinated group trigger review rather than automatic suppression.

Privacy of signals. Some of the strongest features are private: profile visits, post clicks, address book matches (for users who opted in). They are used only as aggregates inside models and are never exposed, and the response never reveals why a private signal mattered. Social context shown to users ("Kai liked") comes only from public actions.

Transparency. Twitter's 2023 blog listed planned work on showing users why a post appears in their timeline and which safety labels apply to their own posts. Explaining recommendations ("because you follow Sam", "popular in baking") is cheap when the candidate source and social proof are carried through the pipeline, which is one more reason to log them with every impression.

12. Training, rollout and running it globally#

Continuous training. The blog says the heavy ranker is continuously trained on post interactions. In practice:

  • Label delay. An impression cannot become a negative example until its attribution window has passed (a few hours in our design). So the freshest usable training data is always a few hours old. Short windows give fresher models but miss late engagements; long windows give complete labels but staler models.
  • Warm start. Each training run starts from the previous model's weights and trains on the newest data, rather than training from scratch. A new model version can be produced every few hours.
  • Negative downsampling. About 150 billion impressions a day is more than training needs. Keep all positives and a sample of negatives, for example 5%. A model trained on downsampled data predicts inflated probabilities, so its outputs must be corrected. He and colleagues (ADKDD 2014) gave the correction: if negatives were kept at rate w and the model predicts p′, the true probability is p = p′ / (p′ + (1 − p′) / w). With w = 0.1 and p′ = 0.2: p = 0.2 / (0.2 + 8) ≈ 0.024. Skipping this step silently breaks the weighted-sum score, because each label's calibration shifts by a different amount.
  • Volume. With a 5% positive rate and 5% of negatives kept, a day yields about 7.5 billion positives and 7 billion negatives: roughly 15 billion examples, about 170,000 per second for a trainer that keeps up in real time.

Large sparse features. User ids, author ids and post ids can be features through learned embedding tables (one vector per id). These tables can hold billions of rows and dominate model size and memory, while the dense part of the network stays small. Hashing ids into a fixed number of rows bounds memory at the cost of collisions. The short-video case study covers a training system built to avoid collisions and update embeddings in near real time.

From trained model to production.

  1. Offline evaluation on a held-out recent day: log loss, AUC and calibration for every label and key segment, compared with the production model.
  2. Shadow scoring. The new model scores live requests in parallel without affecting what is shown. This checks latency, memory, prediction distributions and feature availability on real traffic.
  3. Canary. A small share of traffic is served by the new model to catch errors.
  4. A/B test against the production model on primary and guardrail metrics.
  5. Rollout and rollback. The registry records which version is live. Rollback is a configuration change, because the old version keeps running until the new one is fully proven.

The feature schema is versioned with the model. A model that expects a feature the hydration service does not yet provide must fail validation in shadow, not in production.

Model monitoring. In production, watch per model version:

  • the distribution of each predicted probability (sudden shifts mean a feature or data problem);
  • calibration against observed outcomes, with a lag equal to the attribution window;
  • the rate of missing values per feature;
  • latency and timeouts at the model servers.

Running in several regions. The feed is served from several data centres:

  • Posts and actions are replicated between regions within seconds, so a post is retrievable everywhere almost immediately.
  • Indexes and online stores are maintained in every serving region from the replicated streams, so a feed request never crosses regions.
  • Batch jobs and training run centrally (or in one region per job) on the data lake, and their outputs (models, embeddings, Real Graph scores, community indexes) are shipped to every region with versions, much like a software release.
  • Failover. Each region keeps enough headroom to absorb a failed region's traffic, at least for the degraded modes from deep dive 8. See Multi-Region and Global Data.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Heavy ranker overloaded at peakLatency spikes or timeoutsBatching, autoscaling, smaller candidate budget under load, cached ranked lists, light-ranker fallback
Slow candidate source or index partitionTail latency for every requestDeadlines, partial results, hedged requests, drop the source for that request
Feature store timeoutsMissing features, worse rankingDefaults learned in training, in-process caches, one multi-get per store, alert on missing rate
Viral post creates a hot keyOne counter shard overloadedPre-aggregate in the stream, split hot keys, write counters at most once per second
Training-serving skewModel great offline, poor onlineTrain on features logged at serving time, shared feature definitions, drift monitoring
Uncalibrated new modelWeighted score shifts without anyone decidingCalibration checks per label, calibration layer, correction for negative downsampling
Feedback loop narrows the feedUsers see less variety, long-term retention fallsExploration slots with logged propensities, diversity and calibration, position-bias correction, long-term holdouts
Visibility filter unavailableRisk of showing blocked or unsafe contentFail closed (drop unchecked posts), re-check on cached pages
Engagement manipulationSpam and bait reach many feedsTrust-weighted counts, coordination detection, social proof rule, negative weights, rate limits
Stale embeddings or community indexesOut-of-network relevance dropsReal-time post vector updates, time-partitioned indexes, versioned rebuilds switched with the user tower
Cold start for new users and authorsEmpty or generic feeds, creators never seenOnboarding signals, popular-in-context fallback, exploration quotas, content-based embeddings
Whole ML path downNo ranked feedReverse-chronological backup pipeline from the search index, served without the heavy ranker

What Interviewers Expect#

Mid-level. Clarify the goal (a personalised feed mixing followed accounts and recommendations) and the scale (hundreds of millions of users, billions of requests a day, about 500 million new posts a day). Describe the two-stage funnel: candidate generation from followed accounts and from similar users' engagement, then ranking with a model that predicts engagement. Explain why the model cannot score every post. Store posts in a key-value store, use a cache for timelines, log impressions and engagements for training, filter blocked and already-seen posts, and paginate with cursors.

Senior. Name several candidate sources and why each exists: an in-network index ranked by a light model and an author-affinity score; graph traversals over recent engagement for collaborative filtering; embedding retrieval with an ANN index. Explain multi-task heavy ranking with a weighted sum of probabilities, and why the weights matter more than any single model change. Design the feature store: viewer, author, post and pair features; real-time counters from a stream; point-in-time correctness and logged features against skew. Give a latency budget with parallel sources, deadlines and partial results, and a cached ranked list for scrolling. Cover filters (visibility fails closed), author diversity, in-network balance and cold start for new users and new posts.

Staff and above. Treat the system as a learning loop with business values built in. Discuss selection, position and popularity bias, degenerate feedback loops, exploration with logged propensities and off-policy evaluation. Explain how offline metrics (log loss, AUC, calibration, NDCG, retrieval recall) gate online tests, why interleaving and long-term holdouts exist, and how network effects complicate experiments. Show the compute economics: per-stage budgets, why the funnel's shape is a cost decision, and how caching ranked lists and sharing per-request work cut cost. Cover integrity (manipulation of engagement-based features, trust weighting), privacy of implicit signals, model lifecycle (continuous training, label delay, downsampling correction, shadow and canary), graceful degradation to a reverse-chronological feed, and multi-region operation.

Deep Dive: sizing the system, tier by tierShow

The capacity section gave totals. Here we turn them into rough machine counts to show where the money goes. Every per-machine throughput below is an assumption of a plausible order of magnitude, not a published figure.

Home Mixer (orchestration). Each request is mostly waiting on dependencies, so an asynchronous service handles many requests at once. Assume one instance sustains about 200 feed requests per second, including merging, heuristics and marshalling. At the daily peak of 175,000 requests per second that is about 900 instances, or about 1,300 with headroom for a lost zone.

In-network search index. About 1 billion recent posts at about 1 KB each is about 1 TB of index and static features. Assume each index server holds 25 GB in memory, so about 40 partitions hold one full copy. Every in-network query goes to every partition. At 175,000 queries per second, that is 7 million partition-queries per second. If one server answers about 5,000 such queries per second (each scans posting lists for hundreds of authors and runs the light ranker), we need about 1,400 servers, which is about 35 replicas of the 40 partitions. Search clusters are large because every query touches every partition, not because the data is large.

Engagement graph (GraphJet-style). About 320 GB per replica for 48 hours of engagements. On servers with 512 GB of memory, one or two servers hold a replica. If each server answers about 10,000 traversals per second, peak traffic needs about 18 servers' worth of capacity, so a few dozen servers with replicas. The defining constraint is memory per replica, not throughput.

Embedding retrieval.

  • SimClusters ANN: each request reads the top posts of the viewer's top 20 or so communities (say 200 posts each, 4,000 entries) from a community-to-posts index of a few GB. This is cheap: an in-memory key-value service with modest replicas.
  • Dense ANN: about 64 GB of product-quantized vectors plus the coarse index per replica. Assume about 2,000 queries per second per server at 95% recall: about 90 servers at peak, plus replicas, per region.

Feature hydration and stores.

  • About 350 GB/s of feature traffic into the ranker at the average load (capacity section).
  • If in-process caches on the hydration servers absorb about 80% of post and author lookups (popular posts are candidates for millions of viewers), the stores serve about 70 GB/s.
  • At about 1 GB/s of useful value traffic per storage server, that is about 70 servers at average load and about 200 at peak (three times the average), plus replicas.
  • The hydration tier itself (assembling feature vectors, deduplicating entities) is CPU-heavy: likely several hundred to a thousand instances.

Model servers. From the capacity section, up to about 9 PFLOP/s on average. At an effective 100 TFLOP/s per accelerator that is about 90 accelerators, and about 270 at peak. With headroom for a lost zone, shadow models and A/B variants running side by side, perhaps 400 to 600 accelerators, or the CPU equivalent (tens of thousands of cores). This is the largest single line item in the hardware budget.

Streams.

  • Impressions: 1.7 million per second × 200 bytes ≈ 340 MB/s.
  • Engagements, post creations and other actions add perhaps 100 MB/s.
  • With a replication factor of 3, the Kafka clusters write about 1.3 GB/s, a moderate cluster of a few dozen brokers.

Data lake and training.

  • About 30 TB a day of raw impressions, 5 to 10 TB compressed.
  • About 15 billion training examples a day after negative downsampling (deep dive 12), each with a few KB of logged features: tens of TB a day of training data, kept for weeks.
  • A continuous trainer must process about 170,000 examples per second to keep up: a training cluster of tens of accelerators per model, more for experiments.

Summary.

TierRough size at peak (one region set)
Home Mixer~900 to 1,300 instances
In-network search index~40 partitions × ~35 replicas
Engagement grapha few dozen large-memory servers
Dense ANN~90 servers plus replicas
Feature stores~200 storage servers plus replicas, plus in-process caches
Model servers~400 to 600 accelerators, or tens of thousands of CPU cores
Kafkaa few dozen brokers
Data lake~5 to 10 TB a day compressed, weeks of retention

The lesson: ranking and retrieval fan-out, not storage, set the cost. Halving the candidate budget roughly halves the model servers and much of the feature traffic. Caching ranked lists for scrolling and refreshes removes whole requests. These levers matter far more than any choice of database.

Deep Dive: the maths of funnels, scores and filtersShow

How many candidates should we rank? Ranking cost grows linearly with the number of candidates N. Quality grows much more slowly. Suppose the probability that the viewer's best possible post is among the top N retrieved grows roughly like recall(N) ≈ a + b × log N. Then each doubling of N adds the same small amount of recall (b × log 2) while doubling the ranking cost. With illustrative numbers recall(1,500) = 0.80 and recall(3,000) = 0.83, going from 1,500 to 3,000 candidates doubles hydration and model cost for 3 points of recall, and less than that in engagement, because the extra candidates are the ones the sources rated lowest. The budget is set where the marginal gain per extra dollar falls below that of other improvements, which in practice is a few thousand candidates.

What the published weights imply. The heavy ranker README says the weights were first set so that each weighted probability contributes about equally to the score on average: w_i × mean(p_i) ≈ constant. Then w_i is proportional to 1 / mean(p_i), and the ratio of two weights is the inverse ratio of their average probabilities:

  • w_reply / w_like = 13.5 / 0.5 = 27, so replies were about 27 times rarer than likes when the weights were set;
  • w_reply_engaged_by_author / w_like = 75 / 0.5 = 150, so a reply that the author engages with was about 150 times rarer than a like.

The README also says the weights have since been adjusted to optimise platform metrics, so these ratios are a historical starting point, not a measurement. The method is still useful in any design: start with inverse-frequency weights so that no label dominates by accident, then move the weights deliberately.

Negative weights as a risk budget. A post with P(report) = 0.001 loses 0.369 points. To compensate, it needs about 0.74 more in P(like) (impossible, since probabilities are at most 1) or about 0.027 more in P(reply). So a one-in-a-thousand chance of a report outweighs a typical post's entire like contribution. The score encodes "avoid harm first" without any separate rule.

Embedding similarity. For unit-length vectors, cosine similarity equals the dot product, and squared Euclidean distance is ‖u − v‖² = 2 − 2 u·v. So for normalised vectors, "nearest neighbours by L2 distance" and "highest dot product" give the same ranking. For unnormalised vectors they differ: the dot product favours long vectors, which often correspond to popular posts. Two-tower models usually either normalise or deliberately keep vector length as a popularity signal.

Sparse retrieval cost. A SimClusters InterestedIn vector with 20 non-zero communities, and an index storing 200 top posts per community, gives at most 4,000 candidate posts to score. Each sparse dot product costs a few multiplies (the overlap of two short sparse vectors), so scoring 4,000 posts is microseconds of work. Sparse community embeddings trade some accuracy for extremely cheap retrieval and updates.

HNSW in one line. Search cost grows roughly with the logarithm of the number of vectors (the layers act like a skip list), times the search width. Going from 100 million to 1 billion vectors adds about one layer's worth of hops. This is why ANN search scales well in size, and why the real dials are search width (recall) and memory (links per node).

Tail latency of fan-out. If each of n partitions independently exceeds a latency threshold with probability q, the chance that a request waits for at least one slow partition is 1 − (1 − q)ⁿ:

Partitions nq = 1%q = 0.1%
109.6%1.0%
4033%3.9%
10063%9.5%

With 40 index partitions, a 1% slow rate per partition makes a third of requests slow. Hedged requests turn q into roughly q² for the hedged part (both copies must be slow), which is why they are so effective.

Bloom filter for the seen set. For n items and a target false-positive rate p, the optimal size is m = −n × ln p / (ln 2)² bits, with k = (m / n) × ln 2 hash functions. For p = 1%: m / n = 4.605 / 0.4805 ≈ 9.6 bits per item and k ≈ 7. For p = 0.1%: about 14.4 bits per item and k = 10. A false positive only hides one unseen post, so 1% is fine.

Inverse propensity scoring. Let a logged policy show item a with probability π₀(a | x) in context x, and observe reward r. For a new deterministic policy π, an unbiased estimate of its average reward is

V(π) ≈ (1 / n) × Σ over logged events i of  r_i × 1[π(x_i) = a_i] / π₀(a_i | x_i)

Events where the old policy made a rare choice (small π₀) get large weights, so the estimate has high variance when propensities are tiny. In practice weights are capped (clipped) at some maximum, trading a little bias for much lower variance. This is why exploration traffic should choose items with probabilities that are not too small.

The cost of exploration. If a share ε of slots is used for exploration and an exploratory post is worth, on average, a fraction f of an exploited one, the immediate cost is ε × (1 − f) of total engagement. With ε = 2% and f = 0.5, that is 1% of engagement, paid every day for better training data, unbiased evaluation and a feed that keeps discovering new authors. Holdout experiments are how a team checks that the long-term gain exceeds this cost.

Deep Dive: one request end to end, with real numbersShow

Follow one request through the whole system. Asha follows 300 accounts, mostly bakers plus a few football accounts. Kai is a baker Asha follows closely. Sam is a pastry chef Asha does not follow, but many of Asha's follows engage with Sam's posts. At 08:00 Asha opens the app.

08:00:00.000. Request arrives. The client sends GET /2/timeline/for-you?count=50 with no cursor (a fresh page). The gateway authenticates, assigns request id r-81f2 and sets a deadline of 08:00:01.200. Home Mixer looks up Asha's experiment buckets: heavy-ranker version v412, out-of-network scale factor 0.75.

08:00:00.020. Viewer context, in parallel.

  • The user signal service returns Asha's last 50 actions: 3 likes on sourdough posts last night, one profile visit to Sam.
  • The seen-set Bloom filter (8.4 KB) loads from the cache.
  • The InterestedIn vector loads: home baking 0.61, pastry 0.22, football 0.11, and a few small communities.
  • Real Graph scores for Asha's 300 follows load as one blob (Kai: 0.92, the highest).

08:00:00.050. Candidate sources, in parallel, each with a deadline.

SourceWhat it does for AshaReturnedTime
In-network indexSearches posts from 300 follows in the last 48 hours (about 2,400 matches across 40 partitions), light-ranks them, keeps the top750140 ms
Engagement graphStarts from Asha's top 100 Real Graph follows, finds posts they engaged with in the last 48 hours, ranks by weighted count40090 ms
SimClustersTop posts in Asha's top 20 communities, scored by sparse dot product30040 ms
Dense ANNUser tower vector, HNSW search over the last 48 hours of posts30070 ms
Follow-recommendation postsRecent posts from accounts suggested to Asha8060 ms

Sam's new croissant post appears in three sources: the engagement graph (because 14 of Asha's follows liked it), SimClusters (it is strong in "pastry") and dense ANN. Kai's post from 07:40 ("What flour do you use for rye?") comes from the in-network index with a high light-ranker score, helped by Kai's Real Graph score.

08:00:00.200. Merge and pre-filter. 1,830 candidates. Deduplication by post id leaves 1,610, keeping every source and the best source score per post. Removing posts in the seen set (Bloom filter) leaves 1,540. Removing posts from muted authors and posts older than 48 hours leaves 1,500. Each candidate keeps its sources and social proof ("liked by 14 of your follows" for Sam's post).

08:00:00.210. Feature hydration. One multi-get per store:

  • post features for 1,500 posts, about 80% of them from the in-process cache;
  • author features for 810 distinct authors;
  • viewer × author features for the in-network authors;
  • real-time counters: Sam's croissant post has 2,300 likes, 180 replies, 410 likes in the last 5 minutes.

Viewer × post similarity features are computed in process. About 6,000 features per candidate. Two store shards are slow, so 0.4% of feature values come back missing and are marked as missing. The step takes 160 ms.

08:00:00.380. Heavy ranker. The 1,500 rows go to Navi in 3 batches of 500. Model v412 returns ten probabilities per candidate in 140 ms. The weighted sum gives:

  • Kai's rye question: P(reply) 0.031, P(reply engaged by author) 0.011, giving a score of about 1.9.
  • Sam's croissant post: P(like) 0.24, P(good click) 0.05, P(reply) 0.004, giving about 0.84. The out-of-network factor of 0.75 makes it 0.63.
  • A viral meme from a football account: P(like) 0.30 but P(negative feedback) 0.004, giving about 0.07.

08:00:00.530. Heuristics and filters.

  • Author diversity: Kai has four candidates in the top 100. They are multiplied by 1.0, 0.625, 0.44 and 0.34 in order.
  • Balance: after scaling, the top 50 are 27 in-network and 23 out-of-network.
  • Visibility filtering: two posts are dropped (an author who blocked Asha yesterday, a post labelled minutes ago). One post gets a sensitive-media interstitial.
  • Fatigue: last week Asha tapped "show less" on a hot-take football account, and posts similar to it are down-ranked.

This step takes 40 ms.

08:00:00.570. Mixing.

  • The ad system, called in parallel at 08:00:00.380, returns 5 ads, placed at positions 3, 9, 16, 24 and 33.
  • A who-to-follow module suggesting Sam goes at position 12. Sam's croissant post is at position 7 with "liked by Kai and 13 others".
  • Two replies are threaded under their parent posts.
  • The ranked list of the top 300 posts is cached for 3 minutes under r-81f2.

08:00:00.640. Response. Post content is hydrated (text, media URLs, counts), and the response is marshalled with the cursors. Total time: 640 ms, within the 1.2-second deadline. The log record for r-81f2 is written: 50 served posts with positions, sources, model version, the 6,000 logged features for each served post, and the experiment buckets.

08:00 to 08:04. Asha reads. The client reports impressions as posts become at least half visible for at least 500 ms. Asha:

  • replies to Kai's rye question at 08:01, and Kai likes the reply at 08:09 (a positive for "reply engaged by author");
  • likes Sam's croissant post, then opens Sam's profile and follows them;
  • scrolls past the football meme in 300 ms (no impression is recorded, because 300 ms is under the visibility threshold).

08:03. Scrolling. Asha scrolls to the bottom. The client sends the bottom cursor, Home Mixer finds the cached ranked list, removes the 50 already served and the posts Asha has just seen, re-runs the cheap filters and returns the next 50 in 90 ms without calling the heavy ranker.

Overnight. Learning.

  • The label join (6-hour attribution window) turns Asha's impressions into training examples: the rye-question impression gets labels "reply" and "reply engaged by author", Sam's post gets "like" and "profile click and engage".
  • The new follow updates Asha's follow edges at once. Real Graph will include Sam at the next daily run, and InterestedIn at the next recomputation.
  • The continuous trainer warm-starts v413 from v412, trains on the new day, and sends it to offline evaluation.

Every stage of the design appeared in this one request: the funnel narrowed about a billion posts from the last 48 hours to 1,500 candidates and then to 50 slots, the weights made a conversation outrank a viral meme, the filters applied a block from yesterday, and the logs turned the morning's behaviour into tomorrow's model.

Deep Dive: running this in a 45-minute interviewShow

A plan for the time.

MinutesWhat to doWhat to say or draw
0–5ClarifyGoal (engagement with guardrails, not raw clicks), scale (hundreds of millions of daily users, ~5 billion requests a day), latency (under 1.5 s), mix of followed and recommended posts
5–8Estimate~58k req/s average, ~175k peak; 500M new posts a day; ~1,500 candidates per request means ~87M model scorings per second
8–12API and entitiesGET /for-you with cursors, feedback endpoint, batched client events with impressions; users, posts, follows, engagements, impressions
12–22High-level designThe funnel: candidate sources in parallel, merge, feature hydration, heavy ranker, filters and heuristics, mixing; logging and training loop
22–37Deep dives (pick 2 or 3)Candidate sources (index, graph, embeddings and ANN); multi-task ranking and weights; feature store and skew; latency budget; cold start; feedback loops and evaluation
37–42Failure and scaleDegradation ladder, backup reverse-chronological feed, hot keys, multi-region
42–45Wrap upMetrics, experiments, what you would build next

Twelve follow-up questions, with short answers.

  1. "Why not score every post with the best model?" 500 million posts × 58,000 requests per second is about 3 × 10¹³ scorings per second, far beyond any budget. The funnel keeps the cost per request proportional to a few thousand candidates.

  2. "Do you push followed posts into timelines on write, or pull them at read time?" For ranking we pull: the in-network index is searched at request time with the viewer's follow list. It avoids writing every post to millions of timelines, handles celebrity accounts naturally and always sees the latest posts. Fan-out on write suits a reverse-chronological timeline. The news feed case study compares the two.

  3. "How do you pick the candidate budget per source?" Measure each source's recall@K against what users engage with, and how much it adds beyond the other sources. Give the budget to sources with the highest unique contribution, then tune by experiment. Budgets are configuration, so they can be different per user segment (more out-of-network for new users).

  4. "How do the heavy-ranker weights get chosen?" Start with inverse-frequency weights so each label contributes about equally, then adjust by experiment against long-term metrics (retention, sessions) with guardrails on negative feedback. The weights are a product decision expressed in numbers, so they live in configuration and changes are reviewed like a product launch.

  5. "How do you avoid training-serving skew?" Log the exact feature values used at serving time and train on them. Share one feature definition between batch and streaming. Monitor feature distributions in production against training data, and alert on missing-value rates.

  6. "A post is going viral right now. How quickly does the system notice?" Engagement events reach the stream within seconds. Counters with 1-minute buckets update the post's velocity features at most once per second. SimClusters post vectors grow with each like, and the engagement graph gets new edges in real time. So within a minute the post is retrievable by graph and community sources, and ranked with fresh counts.

  7. "What happens for a brand-new user?" No follows, so no in-network candidates. Use onboarding topics and suggested follows, popular posts in their language and country, a higher share of out-of-network posts, and bandit-style exploration across topics. Real-time signals from the first session matter most.

  8. "How do you evaluate a new ranking model?" Offline: log loss, AUC and calibration per label on a recent held-out day, plus NDCG. Then shadow scoring on live traffic, a small canary and an A/B test on engagement, retention and guardrails. Long-term holdouts catch slow effects.

  9. "How do you stop the feed from becoming an echo chamber?" Diversity (author caps, MMR or DPP), calibration to the user's interest proportions, exploration slots with logged propensities, a mix of candidate sources, and metrics that track narrowing over time.

  10. "The heavy ranker is down. What do users see?" The degradation ladder: cached ranked lists, then light-ranker scores from the sources, then the reverse-chronological backup pipeline. The feed gets worse but never empty, and visibility filters still apply at every level.

  11. "How do you serve a model with 48 million parameters at this rate?" Batch all candidates of a request, compute viewer features once, use a fast model server (Navi, Triton or TensorFlow Serving) on accelerators or optimised CPUs, run model versions side by side for experiments, and cache ranked lists so scrolling does not re-rank.

  12. "How do bad actors exploit this, and how do you defend?" They fake engagement to inflate counters and embeddings, run reply rings, and mass-report rivals. Defences: trust-weighted engagement, coordination detection, social proof requirements for out-of-network posts, large negative weights for predicted reports, rate limits and reporter reliability.

Common mistakes to avoid.

  • Jumping into model architecture before establishing the funnel and the latency budget.
  • One candidate source only (usually "embeddings and ANN"), which misses follows and social proof.
  • Predicting a single "click" label, which rewards bait.
  • Ignoring logging, labels and feedback loops: a recommender without a training pipeline is half a design.
  • Forgetting filters that must fail closed, and the fallback when ML is unavailable.
Deep Dive: variants of the same designShow

The funnel of candidate sources, ranking, filters, mixing and a feedback loop is the skeleton of nearly every recommender. What changes between products is the item, the signal and the budget.

Short-video feed. Almost every candidate is out-of-network, and the main signal is implicit: watch time, rewatches, skips in the first second. The ranker predicts completion and watch time, not likes. Each swipe is a strong, immediate label, so models are updated within minutes and user interest drifts quickly within a session. Prefetching the next few videos sets a different latency budget: ranking can run ahead of the user. The short-video case study goes deeper.

Notifications ("you might like this post"). The budget is the user's attention, not screen space. A bad push costs an uninstall or a disabled permission, so the decision is "send or not", with a high bar and a per-user daily cap. The model predicts open probability and the probability of disabling notifications, and a separate system decides timing (quiet hours, time zones). Batch candidate generation is fine, because a notification can wait minutes.

Search ranking. The query defines relevance, so candidate generation is retrieval by text and embeddings for the query, and personalisation is a smaller re-ranking signal. Freshness matters for news queries. Offline metrics rely on relevance judgements as well as clicks.

Ads. Ads add an auction: each candidate ad's score is roughly bid × predicted engagement probability × quality, and the price depends on the runner-up. Calibration is not optional, because probabilities become money. Pacing spreads each advertiser's budget over the day. The ad system runs alongside the organic ranker and the mixer places its results.

E-commerce ("customers also bought"). Items are products with stock and price, sessions are short and intent-driven, and the strongest signals are co-purchases and co-views. Item-to-item collaborative filtering, which Greg Linden, Brent Smith and Jeremy York described for Amazon ("Amazon.com Recommendations: Item-to-Item Collaborative Filtering", IEEE Internet Computing, 2003), precomputes similar-item lists offline and serves them by lookup. Constraints such as "in stock" and "ships to this address" are hard filters.

Small scale (a startup with 100,000 users). Skip most of the machinery:

  • one candidate source (recent posts from follows plus popular posts), or a full scan of the last day's posts, because 100,000 posts can be scored directly;
  • a single gradient-boosted tree model, or a logistic regression, on a few dozen features, retrained daily;
  • features computed in the main database and a cache, no separate feature store;
  • reverse-chronological as the fallback and as the baseline to beat in an A/B test.

At this size the funnel is two stages at most, and the right investment is logging impressions and labels correctly from day one, because that data is what every later version will need.

Deep Dive: how the design evolves, v1 to v3Show

v1: rules and a simple model.

  • Candidates: posts from follows in the last 24 hours, plus the most popular posts in the user's language.
  • Ranking: a logistic regression or gradient-boosted trees on a few dozen features (post age, author affinity from past likes, post engagement counts), predicting one label: engagement.
  • Serving: a single service scores a few hundred candidates per request. Ranked lists are cached for scrolling.
  • Data: impressions and engagements logged to a data lake, daily training.
  • Limits: popular posts dominate, one label rewards bait, out-of-network discovery is weak, the daily model is slow to react.

v2: multiple sources, multi-task ranking, a feature store.

  • Candidates: an in-network search index with a light ranker, graph-based collaborative filtering, and community or dense embeddings with an ANN index. Each source has a budget.
  • Ranking: a neural multi-task model predicting several engagement types, combined by configurable weights with large negative weights for negative feedback and reports.
  • Features: an online store fed by stream jobs for real-time counters and by batch jobs for long-window aggregates. Features logged at serving time for training.
  • Page: author diversity, in-network balance, visibility filtering that fails closed, social proof rules.
  • Learning: continuous training with warm starts, offline evaluation gates, shadow and A/B rollouts.
  • Limits: feedback loops narrow the feed, the cost of ranking grows with every new feature, cold start remains weak.

v3: a learning system with explicit values.

  • Exploration as a first-class candidate pipeline, with logged propensities for off-policy evaluation and unbiased training.
  • Bias corrections: position features, inverse propensity weighting, popularity correction in retrieval.
  • Page-level optimisation: calibrated interest mixes and set-based diversity (MMR or DPP), not only per-post scores.
  • Cost control: cascades of rankers, distilled models, shared per-request computation, adaptive candidate budgets under load.
  • Long-term metrics: holdouts, cluster-randomised experiments for network effects, retention as the launch criterion.
  • Integrity woven in: trust-weighted engagement, coordination detection and transparency about why a post appears.

Twitter's 2023 description and open-source code sit at about the v2-to-v3 boundary. They have several candidate sources, a multi-task heavy ranker with published weights, a feature and aggregation framework, a rule engine for visibility and explicit exploration parameters, which are the building blocks of v3.

Key Takeaways#

  • A recommender is a funnel. Cheap candidate sources narrow hundreds of millions of posts to about 1,500, an expensive model ranks those, and rules turn the ranked list into a page. Each stage's budget is a cost decision.
  • Use several candidate sources. A search index over followed accounts, graph traversals over recent engagement, and embedding retrieval with ANN indexes each find posts the others miss. Social proof from the graph also protects quality.
  • Predict many engagements and combine them with weights. The weights are the product's values in numbers. A reply the author answers is worth far more than a like, and a predicted report costs more than almost anything can earn.
  • Calibration and point-in-time features are prerequisites. A weighted sum of probabilities only works if the probabilities are calibrated, and a model only works in production if it trained on the features it will see at serving time. Log served features.
  • Freshness is a pipeline, not a database. Streams feed counters, post embeddings and graph edges within seconds. Batch jobs compute long-window aggregates and communities. Each feature sits in the cheapest tier that is fresh enough.
  • Budget latency with parallelism, deadlines and partial results. Tail latency compounds with fan-out. Hedge, cache ranked lists, and degrade in steps down to a reverse-chronological feed that never goes empty.
  • The feedback loop is the hardest part. Selection, position and popularity bias shape the training data. Exploration with logged propensities, diversity, calibration and long-term holdouts keep the system honest.
  • Engagement can be manufactured. Trust weighting, coordination detection, negative weights and visibility rules that fail closed are part of the design, not an afterthought.