All posts
System Design Mastermind · Part 35
  • System design
  • Interview prep
  • AI/ML systems
  • Recommendations
  • Ranking

Recommendation system design (TikTok-style For You feed): candidates, ranking, freshness and A/B tests

How to design a recommendation system and feed ranker in real interview order: requests per second, heavy-ranked candidates per second and events per second as the numbers that matter, a feed API with a request_id on every event, an explainer on two-tower retrieval and approximate nearest-neighbour indexes, candidate sources, a light and a heavy multi-task ranker, a value model and final re-rank built in passes, one request walked from tap to page, a like, the next page reacting, the training join and a new ranker shipping, a lab on the funnel (recall against GPUs and milliseconds), a lab on freshness (when the model learns a new item and how fast the feed reacts), offline evals, interleaving, A/B test sizing, LLM judges and their limits, cost per request, guardrails, and what happens when each part fails.

5 Nov 2026 · 34 min read · interactive

Share

The 1-minute answer

A recommender is a funnel that spends the most compute on the fewest items. For each feed request a mixer reads fresh user features, asks several candidate sources in parallel (a two-tower embedding search in an approximate nearest-neighbour index, items like your recent likes, trending, a fresh pool for new items) for a few thousand candidates out of hundreds of millions, filters what's ineligible or already seen, scores them with a light ranker, and sends the best few hundred to a heavy multi-task ranker that predicts several actions (finish, like, share, skip, not interested). A value model weighs those predictions and a final re-rank adds diversity and exploration, all within ~200 ms. Every view streams back as an event: one copy updates real-time features in seconds, another is joined with the exact features served to train the models incrementally every few minutes. New models go offline replay → shadow → interleaving → A/B with guardrails → holdback, because offline gains often don't survive contact with users.

How this page follows the interview

Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.

✅ Seen: said publicly (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

Following-based feeds and fan-out are Part 29 (news feed); search and feed building blocks are F16; data pipelines F17; GPU inference F18 and Part 22; moderation, which decides what's eligible, Part 34. Designed from public material only: no employer's internal systems.

Requirements and numbers

Agree what's shown, what "good" means and how fresh it must be, then size feed requests per second, candidates the heavy ranker scores per second, and events per second. Change any input: each number comes with the decision it forces.

Functional

  • A personalised, endless feed of items (short videos) for each user
  • React to what the user does within the session
  • New items reach the right people within minutes of upload
  • Users can say "not interested", hide creators and sounds
  • Never show ineligible, removed or already-seen items

Non-functional

  • A page within ~200 ms p99; never an empty feed
  • Optimise watch time and satisfaction, with guardrails (retention, "not interested", reports)
  • Learn new items and trends in minutes, not days
  • Every change measured online before everyone gets it
  • In the EU, very large platforms must also offer a feed not based on profiling

Out of scope (say it)

Ads ranking and auctions, search, the moderation pipeline itself (Part 34), creator tools, and training the content-understanding models; we use their embeddings.

Capacity calculator

Every input is an assumption 🔶: say it out loud. Volumes and prices are round teaching numbers, not any company's ❓. For scale: Twitter said in 2023 that its recommendation pipeline runs about 5 billion times a day, ranking ~1,500 candidates each time ✅ Twitter Mar 2023

Three rules for this estimate
  1. Requests, not users: views ÷ items per page ÷ 86,400 s × peak.
  2. Multiply by candidates: every heavy-ranked candidate is a GPU forward pass.
  3. Every view is a training example: events and logged features size the learning loop.
They'll push on thisAnswer out loud, then open.

Core entities and the API

A request is what we served and why; events are what the user did with it. What they listen for: a session cursor, a request_id on every event, positions, and predictions per action.

EntityKey fieldsNote
Request
Response

How a two-tower model finds candidates

The user tower turns fresh user features into a vector at request time; the item tower turns every item into a vector offline. "Relevant" means a high dot product, so retrieval is a nearest-neighbour search. Scanning every item is exact but far too slow; an index trades a little recall for a lot of speed. Pick an index and change the sizes.

What the sources say

  • Two towers: each tower only sees its own side's features, so item vectors can be computed offline daily and cached; the catch is no user × item features. ✅ Meta Aug 2023
  • Fresh user vector: computed at request time from the freshest user features, then used to query the ANN service (FAISS, HNSW). ✅ Meta Aug 2023
  • Approximate is fine: YouTube found its A/B results "not particularly sensitive" to the nearest-neighbour algorithm. ✅ YouTube 2016
  • Memory: HNSW stores d × 4 + M × 2 × 4 bytes per vector; for 100 M–1 B vectors FAISS suggests IVF with ~1 M lists over an HNSW quantiser. ✅ FAISS wiki

Work per query and core counts use a round 20 billion multiply-adds per core per second and HNSW visiting ~128 × 32 vectors: teaching estimates, not benchmarks 🔶. Index recall depends on efSearch and nprobe; measure it against exact search on a sample.

They'll push on thisAnswer out loud, then open.

High-level design

Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch.

They'll push on thisAnswer out loud, then open.

Walk one request, box by box

At 21:40 Priya, in Hyderabad, opens the app. She watched a lot of cooking and some cricket last week. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes, through her first page, a like, the next page reacting, the training join and a new ranker shipping.

On the wire

Arrows show who calls whom, and the numbers give the order. Replies go back along the same line.

What keeps it fast and cheap

A demo scores every item with one model. These six details are what turns it into a feed that answers 100,000 requests a second in 200 ms.

    Data and database choices

    Train on what you served, not on what you'd compute later. Vectors live in an ANN index, features in a key-value store with an offline twin, events in a log, and training examples are the served features joined with what happened next.

    DataPickConsideredWhy not those

    The one thing to know: log, then join

    # Serve: log the exact features the model used.
    def rank(req, cands):
        f = features.get(req.user, cands)  # values now
        p = ranker.predict(f)              # ranker@v57
        log("served", req.id, cands, f, ranker.version)
        return p
    
    # Train: join labels to what was SERVED.
    # Recomputing features later leaks the future.
    examples = join(served, events,
                    on=("request_id", "item_id"),
                    window="24h")  # late watches count

    Illustrative; names made up. Monolith joins a feature stream and an action stream on a unique request key in Flink ✅ Monolith 2022

    Why the join matters

    1. No leakage: a recomputed "likes in the last hour" includes likes that came after the impression. ✅ Feast docs
    2. No skew: training sees exactly the values serving saw, including defaults for missing ones. 🔶
    3. Late labels: a watch can arrive minutes later; Monolith keeps waiting features in a disk-backed store. ✅ Monolith 2022
    4. Replays: the same logs are the offline evaluation set for the next model. 🧭

    More database questions

    They'll push on thisAnswer out loud, then open.

    Deep dive: the funnel, recall against GPUs and milliseconds

    Retrieval decides what can be shown at all; the heavy ranker decides the order, and it's the bill. How many candidates to fetch, how many to heavy-rank, and how good retrieval must be is the core trade-off. "Recall" here is the share of the 100 items the heavy ranker would pick from the whole corpus that actually reach it. Pick a preset, then change the numbers.

    Teaching model: each item's heavy-ranker score u ~ N(0, 1); retrieval sees ρ₁·u + noise, the light ranker ρ₂·u + independent noise; each stage keeps its top share. Correlations are assumptions, not any company's numbers 🔶. Computed exactly under that model (numerical integration).

    The rules this lab teaches

    1. Retrieval quality beats retrieval size: 0.75 → 0.85 correlation adds ~24 points; 4× the candidates adds ~14. 🔶
    2. A distilled light ranker is nearly free: it loses ~1 point and cuts heavy GPUs 10×. 🔶
    3. Exact search doesn't fit a request: use ANN and run sources in parallel. ✅ YouTube 2016
    4. A bigger corpus needs better retrieval, not more ranking GPUs. 🔶

    Real numbers to quote

    Instagram Explore (Aug 2023): retrieval, first-stage ranking, second-stage ranking and final reranking; the funnel starts "with thousands of candidates" and narrows to hundreds; the heavy model "operates on the 100 best candidates from the first stage". ✅ Meta Aug 2023

    YouTube (2016): candidate generation narrows the corpus to hundreds, ranking to dozens, "under a strict serving latency of tens of milliseconds" for retrieval. ✅ YouTube 2016

    Twitter (Mar 2023): ~1,500 candidates per request, ranked by a ~48M-parameter neural network. ✅ Twitter Mar 2023

    They'll push on thisAnswer out loud, then open.

    Deep dive: freshness, how fast the feed learns

    Two clocks matter. The model clock: how long until a new item (or a new trend) is learned. The feature clock: how long until what the user just did reaches the next page. Short videos get most of their views in hours, so a model retrained daily learns them too late. The chart shows one item's views piling up after upload against when the model learns it. Pick a preset, then change the switches and numbers.

    Swipes after a like until a page ranked with it

    Views follow a half-life after upload; an item uploaded at a random moment waits publish time + a random share of the cycle. Cold items earn ~75% of a learned item's engagement with a content embedding and ~20% on exploration alone: rounded teaching values 🔶. The server ranks once per page.

    Three rules, in order

    1. Match the model clock to the content: hours-long content needs minute-level syncs; months-long content is fine with daily. 🔶
    2. Don't retrain from scratch for freshness: train incrementally on the stream and sync what changed. ✅ Monolith 2022
    3. Stream user features: seconds, not a 5-minute batch, or the feed can't react within a session. 🧭

    Numbers to quote

    Monolith (ByteDance, 2022): on Criteo, online training synced every 5 h, 1 h and 30 min averaged 79.66, 79.78 and 79.80 AUC vs ~79.4 for batch; production syncs sparse parameters at minute level and dense ones daily. ✅ Monolith 2022

    Sync cost: 100,000 updated IDs × 1,024 dims × 4 bytes ≈ 400 MB a minute, light enough because only touched embeddings move. ✅ Monolith 2022

    Instagram: item embeddings from the item tower can be generated "on a daily basis using an offline pipeline", while the user embedding is computed online from the freshest features. ✅ Meta Aug 2023

    They'll push on thisAnswer out loud, then open.

    Deep dive: evals, A/B tests, rollouts, cost and guardrails

    A recommender fails quietly: a worse model returns fast, healthy pages that people watch a little less. Offline metrics rank ideas; online tests decide; a holdback catches slow damage.

    The release ladder

      How long must the A/B test run?

      n per arm = 2(z₀.₉₇₅ + z₀.₈)²σ²/Δ² for 5% significance and 80% power, which is Kohavi's 16σ²/Δ² rule. Days assume each day brings new users; repeat visitors make it longer. Netflix reported interleaving needs more than 100× fewer users ✅ Netflix 2017

      Offline metrics, logs and LLM judges: useful, with limits

      An LLM, a trained model, or both?

      Tick what's true for your product.

      Cost and latency per request

      1. Fewer heavy candidates: the light ranker is the biggest lever; heavy GPUs scale with candidates per request. ✅ Meta Aug 2023
      2. Batch and reuse: one batch per request on the GPU; user-side layers once, not per candidate. 🧭
      3. Cache: item vectors offline, the user vector once per request, a precomputed page for some users off-peak. ✅ Meta Aug 2023
      4. Route cheaper: logged-out or very new users get a lighter pipeline (popular + fresh) until there's signal. 🧭
      5. Compress the index: 64-byte PQ codes instead of 768-byte HNSW vectors. ✅ FAISS wiki

      Guardrails on what the ranker may do

      1. Eligibility first: under review, spam and some allowed-but-shocking content may not be recommended at all. ✅ TikTok 2020
      2. Diversity: generally no two in a row from the same creator or sound; no duplicates, nothing already seen. ✅ TikTok 2020
      3. Negative feedback costs: P(not interested) and P(see less) carry negative weights in the value model. ✅ Meta Aug 2023
      4. A feed without profiling for EU users of very large platforms, from the same pipeline. ✅ EC DSA

      Regression tests for models and rules

      1. Replay set in CI: thousands of real logged requests re-ranked by every model or config change; metrics per slice must not drop. 🧭
      2. Invariants: no seen, ineligible or hidden-creator items; no two from one creator in a row; a page always returns. 🧭
      3. Feature parity: sampled requests' features online vs recomputed offline must match. ✅ Feast docs
      4. Calibration per head and slice: mean prediction vs observed rate, so the value model's weights mean what they say. 🧭
      They'll push on thisAnswer out loud, then open.

      An item's lifecycle

      Every video moves through a small state machine, from upload to retirement. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.

      NormalSomething was wrongGreyed out: not possible from the current state.

      Edge cases interviewers love

      They'll push on thisAnswer out loud, then open.

      Failure, monitoring and recovery

      Recommenders fail loudly (empty or slow pages) and quietly (a slightly worse model, stale features, a skewed join). The quiet ones cost more. Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.

      Tracing it back: a normal page vs a hot feature shard

      Every span carries request_id, model, index and config versions. Times are from the request; illustrative. In the bad trace one item-feature shard is hot, the mixer's stage timeout fires, and the page is served in light-ranker order.

      How one failure becomes three

      What you'd alert on (SLOs)

      SignalTargetAlert

      Incident playbook

        The toolkit

        Name the technique, then say where it goes in this design.

        They'll push on thisAnswer out loud, then open.

        Making it fast, and who owns what

        The page is tens of milliseconds per stage; the learning loop is seconds for features, minutes for the model, weeks for the verdict. Bars are sizing estimates, not measured figures.

        TeamOwnsPaged when…

        Senior follow-ups beyond the happy path

        Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.

        Practice ladder

        Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.

        Sources

        Checked November 2026. The funnel is from Engineering at Meta's Instagram Explore post (Aug 2023: retrieval, first- and second-stage ranking with the heavy model on the 100 best, final reranking, two towers, the value model, off-peak precomputation), Covington, Adams and Sargin's YouTube paper (RecSys 2016: millions to hundreds to dozens, ANN choice not sensitive in A/B tests, watch time over clicks, training on all watches), Zhao et al.'s YouTube multitask ranker (RecSys 2019: MMoE, a shallow tower for position bias) and Twitter's March 2023 post (about 1,500 candidates, a ~48M-parameter ranker, ~5 billion runs a day). Freshness is from ByteDance's Monolith paper (2022: online training, minute-level sparse sync, daily dense sync, Kafka and Flink joiner, sync-interval AUC on Criteo). Index memory is from the FAISS wiki; point-in-time joins from the Feast docs; interleaving from Netflix (Nov 2017, more than 100× fewer users); sample size from Kohavi, Henne and Sommerfield (KDD 2007); judge limits from Zheng et al. (2023); generative recommenders from Zhai et al. (ICML 2024); user controls and eligibility from TikTok's 2020 newsroom post; the EU non-profiling option from the European Commission's DSA page; real-time events from Amazon Personalize's docs. The labs use rounded teaching values and a textbook score model, and say so. Hello Interview is a third-party prep site, used only to cross-check what interviewers expect. Nothing here comes from any employer's internal systems.

        System Design Mastermind · AI / ML systems

        Series home

        All of AI / ML systems

        8 published · 1 comingLLM and ML systems, where interviews are heading.

        22

        LLM serving platform system design (ChatGPT-style): tokens, GPUs and safe model changes

        Chat API (auth, token limits, history, safety, SSE with resumable event ids) → router picks model (easy turns to a small one), version (registry canary split) and a replica with the prefix cached → vLLM-style engines batch continuously up to the time-per-token target. Admit by priority because GPUs take minutes to add; ship every model change through evals, shadow and canary, with rollback by one number.

        34 min · interactive Preview
        25

        RAG assistant over company docs system design: retrieval, permissions and answers you can trust

        Ingestion (change events + full sync → parse → chunk with a context line → embed only changed chunks) fills a versioned index of keywords, vectors and allowed principals. Serving rewrites the question, runs hybrid search with the permission filter inside it, reranks 150 → 8, answers only from numbered sources, checks grounding and re-checks cited docs. A golden set gates every change.

        34 min · interactive Preview
        28

        AI agent platform system design: tools, durable runs, approvals and agents you can trust

        A durable orchestrator runs each agent as workflow code: pin the version, call the model through a caching gateway, record every step so crashes resume. The model only proposes tool calls; a tool gateway validates, authorizes with the user's own token, adds idempotency keys and parks irreversible steps for approval. Budgets stop runaways; end-state evals with k tries gate every release.

        35 min · interactive Preview
        31

        Offline GPU batch inference system design: millions of LLM calls by a deadline, on GPUs that can vanish

        Validate the file, split it into ~20-minute shards, lease them to GPU workers on spot that load the model once and run hundreds of rows at a time with the shared prompt cached. Each attempt writes its own file; one conditional commit per shard makes output exactly-once. Golden set and canary shard gate every new version.

        34 min · interactive Preview
        34

        Content moderation pipeline system design: hash matching, classifiers, LLM checks and human review at a billion items a day

        Hash at upload against known-bad lists, score every policy with small classifiers in ~50 ms, two lines per policy: remove above, allow below, and the band between goes to an LLM that reads the policy, then a review queue ordered by severity × reach × likelihood. Every decision logged with a reason, appealable, and gated by golden set → shadow → canary.

        34 min · interactive Preview
        35

        Recommendation system design (TikTok-style For You feed): candidates, ranking, freshness and A/B tests

        Several sources (two-tower ANN search, like-your-likes, trending, a fresh pool) retrieve a few thousand items; a light ranker keeps a few hundred; a heavy multi-task ranker predicts finish, like, share and skip; a value model and re-rank add diversity, in ~200 ms. Events stream back to features in seconds and to incremental training in minutes; models ship via interleaving and A/B tests.

        You're reading this Preview
        36

        LLM evaluation and guardrails platform system design: judges, guard latency, paired eval gates and safe rollouts

        Every product calls an AI gateway: versioned config, input guards (PII mask, a small injection classifier, an LLM judge only when unsure), output guards on streamed chunks, a trace per request. Off the path: sampled traces judged online, people calibrating the judges, failures turned into regression tests, and every change gated by a paired eval with error bars, then shadow, canary and A/B.

        33 min · interactive Preview
        37

        AI coding agent system design (Claude Code, Cursor, Codex): context, edits, sandboxes and evals

        Three shapes, one backend: a small self-served Tab model per keystroke; an agent loop with a context engine (grep plus an optional index), a cached prompt to a frontier model, text-anchored edits or a fast apply model, permissions and an OS sandbox; and background agents in a container per task that open a PR. An eval harness gates every change on pass^k.

        34 min · interactive Preview
        ··

        Feature store and training platform

        Coming next

        More posts