TOUGH TONGUE AI
  • Home
    LogoTOUGH TONGUE AI

    RESOURCES

    Loading...

    HomeLibrarySD Mock · Design Facebook News Feed

    SD Mock · Design Facebook News Feed

    SD Mock · Design Facebook News Feed

    Overview

    Design a social news feed like Facebook's on a live architecture board: drag components, wire them up, and defend your fan-out and feed-cache choices to an expert interviewer who watches every move.

    Your Instructions

    Design Facebook's News Feed

    A 20-minute mock system design interview. You drive the pace. Jump to the board when you are ready; skip capacity math if you want. The interviewer grades your thinking, not a template match.

    The signal concentrates in three places. Where you pay for the join between "who I follow" and "what they posted": at write time or at read time. What happens when a page with ten million followers posts. And what your per-user feed actually stores: whole posts or post IDs, a 50x memory difference. "Precompute the feed in Redis" is not a design until you can answer all three.

    Two shared surfaces (only one is on screen at a time; use the panel arrow to switch):

    • Notepad. Shared notes. Requirements, capacity math, schema, and end-of-session feedback live here. You can type in it too.
    • Architecture board. Your design canvas. Drag typed components, wire them, label edges, mark scaled tiers as distributed. If it is not on the board, it is not in your design.

    Build incrementally while you talk. Trace one post end to end through your diagram: Dave publishes "New job!" and it shows up when his friend Jane opens her feed. Argue the tradeoff, not "industry standard."

    Design choices interviewers probe

    Read this before you go in. These are the decisions, and why they matter.

    Fan-out on read, on write, or both

    Fan-out on read (pull) stores each post once under its author and assembles Jane's feed when she asks: fetch the ~500 sources she follows, merge, sort. Writes are trivial and nothing is wasted on people who never log in. It fails on reads: 17,500 feed loads a second times 500 sources is roughly 8.75M lookups a second, far outside a 2-second budget.

    Fan-out on write (push) copies the new post's ID into every follower's precomputed feed at publish time. A read becomes one cache lookup. It fails on one author: a page with 10M followers means 10M inserts for a single post, about 10 seconds even at a dedicated 1M inserts a second, against a 5-second freshness target. It also wastes work on followers who never log in.

    Hybrid is the sound default. Push for ordinary users; skip fan-out for pages and public figures above a follower threshold and merge their recent posts when the reader loads the feed. Facebook caps friendships at 5,000, so friend-to-friend push is bounded; page followers are not, and those are what you pull. Tie the threshold to the freshness budget and queue lag, not to a magic number.

    Equally defensible if you can say why: Facebook's real backend (Multifeed) leans toward read-time assembly, keeping every user's recent actions in memory on leaf servers and ranking at read. That works because every read is re-ranked anyway. If you argue for it, say what keeps the read fast.

    What the feed cache stores

    Keep 500 feed items per user for 300M users. If each item is a 1 KB post, that is 500 KB a user, 150 TB, about 1,500 servers at 100 GB each. If each item is a 20-byte reference (post ID, author ID, a few flag bits), that is 10 KB a user, 3 TB, about 30 servers. Same feed, one decision apart. Store IDs, key the list by user ID, cap it (200 to 500 entries; few people scroll past ten pages), and hydrate at read time from a shared post cache where each post lives exactly once. Edits and deletes then touch one copy instead of millions.

    Async fan-out through a queue

    The post request should not wait for fan-out. Persist the post, return success, and put (post_id, author) on a durable queue. Workers read the author's friend list from the social graph, filter it (muted the author, outside the post's audience, inactive for weeks), and prepend the ID to each remaining friend's feed. A durable log lets a crashed worker replay; inserting the same post ID twice must be a no-op. Put very large fan-outs in their own lane so one busy page does not delay everyone.

    Live updates: push to notify, pull to serve

    Jane is online when Dave posts. Holding a long poll open per user and pushing full posts is expensive at scale. Blind client polling mostly returns nothing. The pragmatic answer: send a small "new posts" signal (a WebSocket or push notification) and let the client fetch when she scrolls up or taps the banner. On mobile, where data costs money, pull-to-refresh alone is fine.

    Ranking at read time

    Reverse chronology is the simple default and a fair interview scope. A ranked feed changes where work happens: the precomputed list becomes a candidate source, not the answer. At read time, gather candidates (cached feed plus pulled page posts plus older posts bumped by new comments), score them on signals like likes, comments, shares, recency, media and your affinity with the author, and return the top 20. Meta runs this as a funnel: 1,000+ candidates, a light pass keeps about 500, neural predictors estimate like, comment and share probabilities, a weighted sum becomes the score, then diversity rules stop one friend filling the screen. If ranking goes down, fall back to reverse chronology rather than an error page.

    Inactive users, privacy and deletes

    Do not keep 300M feeds warm. Evict with LRU, skip inactive users at fan-out, and rebuild a feed by pull on the user's next login (slower once, fast after). Audience rules apply twice: filter recipients at fan-out, then re-check visibility, mutes and blocks at read, because relationships change after delivery. Deletes are two-stage: tombstone the post, let hydration drop it everywhere on the next read, purge IDs from feeds lazily.

    Reference solution

    One complete design you can study, then rebuild in your own words. Do not recite it. In the interview, draw your graph and defend the choices.

    Requirements (lock these or take the defaults)

    • Publish posts with text, images or video; see posts from friends, pages and groups you follow
    • Feed is ranked by relevance (reverse chronological is an acceptable simplification if agreed)
    • New posts reach active followers' feeds as they arrive
    • Scale: 300M DAU, feed fetched ~5 times a day; average 300 friends and 200 followed pages; friends capped at 5,000, page followers unbounded
    • Non-functional: feed renders within 2 s end to end; a new post reaches a friend's feed within 5 s; highly available, eventual consistency acceptable; read-heavy
    • Out of scope unless asked: comments UI, ads, search, stories, messaging

    Capacity

    • 300M DAU x 5 fetches = 1.5B feed requests/day, 1.5B / 86,400 s = ~17,500 feed requests/sec; each hydrates 20 posts, so ~350K post lookups/sec
    • Feed cache, whole posts: 300M x 500 items x 1 KB = 150 TB, ~1,500 servers at 100 GB. IDs only: 500 x 20 B = 10 KB/user, 300M x 10 KB = 3 TB, ~30 servers (~90 with 3 replicas). 50x smaller.
    • Fan-out, assuming 150M posts/day: 150M x 300 friends = 45B inserts/day, ~520K inserts/sec. One 10M-follower page: 10M inserts, ~10 s at 1M inserts/sec, over the 5 s budget.
    • Pure pull instead: 17,500 x 500 sources = ~8.75M source lookups/sec

    Rough numbers are fine; the method is what gets graded. The win is using them: "IDs, not posts, or the cache is 1,500 machines"; "push is fine at 520K/s but the 10M-follower page needs pull."

    Components to put on the board

    How the graph works: two paths share one cache. The publish path persists a post and hands its ID to fan-out workers, which read the social graph and prepend the ID into each friend's feed list in Redis. The read path pulls Jane's ID list from Redis, merges recent posts from the big pages she follows, ranks, hydrates from the post and user cache, and returns 20. Media never touches either path; it goes through a CDN.

    Web Client, Mobile Client
        → Load Balancer
        → Service (Post Service; mark distributed)
            → Cassandra (posts, sharded; mark distributed)
            → Cache (post + user objects, hot tier for viral posts)
            → Kafka (fan-out topic)
                → Worker (fan-out workers; mark distributed)
                    ↔ MySQL (social graph; TAO over MySQL at Facebook) + Cache
                    → Redis (feed cache: user_id → capped list of post IDs; mark distributed)
                    → Service (Notification Service) → WebSocket Server → clients ("new posts")
        → Service (Feed Service; mark distributed)
            → Redis (read Jane's ID list)
            → Cache (pull recent posts of big pages; hydrate posts and authors)
            → ML Model (ranking)
    Web Client, Mobile Client → CDN → Blob Store (images, video)
    

    Components:

    • Load Balancer. Spreads traffic over stateless Post and Feed services; web tier also enforces auth and a per-user posting rate limit against spam.
    • Service (Post Service). Validates the post, assigns a time-ordered post ID, writes Cassandra and the post cache, enqueues fan-out, and returns. The author never waits for fan-out.
    • Cassandra (posts). Durable post storage, sharded on a time-ordered post ID so "newest first" is a key-range scan. Sharded MySQL is equally fine.
    • Kafka (fan-out topic). Decouples publishing from delivery, absorbs bursts, and lets a crashed worker replay. Without it, a big fan-out blocks the post request.
    • Worker (fan-out workers). Check the author's follower count against the threshold; for ordinary authors, read friend IDs from the social graph, filter muted, inactive and out-of-audience friends, prepend the post ID into each friend's feed list and trim it to the cap.
    • MySQL + Cache (social graph). Who follows whom, indexed both directions. Facebook's TAO is exactly this: typed objects and associations cached over MySQL, a billion-plus reads a second, eventually consistent.
    • Redis (feed cache). The load-bearing box. One capped list of 20-byte entries per user, sharded by user ID with consistent hashing so a read touches one shard; replicated so a lost node does not trigger a rebuild storm.
    • Service (Feed Service). Reads the ID list, merges in big-page posts, calls ranking, hydrates the top 20, filters deleted and no-longer-visible posts, returns a cursor.
    • Cache (post and user objects). Every post and author stored once; absorbs ~350K lookups a second. A hot tier replicated widely keeps one viral post from melting a single node. Keep like and comment counters apart from post objects.
    • ML Model (ranking). Scores candidates by predicted engagement; falls back to reverse chronology if it is down.
    • Service (Notification Service) + WebSocket Server. Sends online friends a small "new posts" signal; the client pulls.
    • CDN + Blob Store. Photos and video, uploaded before the post and referenced by ID. Never on the feed's critical path.

    Walk one post: Dave posts "New job!" and Jane sees it

    1. Dave's client uploads the photo to the Blob Store, then posts through the Load Balancer to the Post Service.
    2. The Post Service assigns post ID p903, writes it to Cassandra and the post cache, and returns success to Dave.
    3. It publishes (p903, dave) to the Kafka fan-out topic.
    4. A fan-out Worker sees Dave has 340 friends, under the threshold, and reads his friend IDs from the social graph.
    5. It drops friends who muted Dave, are outside the post's audience, or have been inactive for weeks, then prepends p903:dave to each remaining friend's Redis feed list and trims to 500.
    6. The Notification Service tells online friends, including Jane, that new posts exist. Elapsed: a few seconds.
    7. Jane's client calls the Feed Service, which reads her Redis list, merges recent posts from NASA (a page above the threshold) out of the post cache, ranks the candidates, hydrates the top 20 from the cache, and returns them with a cursor.

    The 10M-follower page posts: no fan-out. The post goes to Cassandra and the post cache only. Every follower's Feed Service call pulls the page's latest few posts and merges them; most readers follow only a handful of such pages, so the merge is small.

    Jane was away for a month: her feed was evicted. The first read rebuilds it by pulling from her follows, stores it, and serves it. Rate-limit rebuilds so a mass cache loss does not flatten Cassandra.

    Dave deletes the post: tombstone p903 in Cassandra and the cache. Hydration drops it from every feed on the next read. IDs are purged lazily or age out of the cap.

    Schema

    Users(user_id PK, name, profile_pic_url, created_at, last_login)
    Entities(entity_id PK, type [page|group], name)
    UserFollow(user_id, target_id, target_type [user|entity], created_at)    MySQL, indexed both directions
    Posts(post_id PK time-ordered, author_id, entity_id?, content, media_ids, audience, created_at, deleted)    Cassandra
    feed:{user_id} → list of post_id:author_id:flags, capped at 500          Redis list
    counters:{post_id} → likes, comments, shares                            Redis hash
    actions:{user_id}:{post_id} → liked / commented                         Redis or Cache
    
    • Posts sharded by post ID (epoch-ordered, Snowflake-style), replicated x3
    • Feed cache sharded by user ID with consistent hashing; one read = one shard; replicated
    • Social graph relational (MySQL behind a cache); posts and feeds key-value

    Scaling and wrap-up

    • Post and Feed services are stateless and scale behind the Load Balancer; fan-out Workers scale with Kafka partitions
    • Redis absorbs feed reads, the post Cache absorbs hydration, the CDN absorbs bytes
    • First metrics: fan-out lag (post to last friend's feed, against 5 s), feed p99 latency, feed-cache hit rate and rebuild rate
    • If time: ranking model latency and fallback, multi-region feeds, ads insertion, live comment updates

    Equally defensible variants

    Pure read-time assembly with in-memory per-author indexes (Facebook's Multifeed) if you explain what keeps reads fast. Reverse-chronological feed if the interviewer agrees to drop ranking. Sharded MySQL instead of Cassandra for posts. SQS or RabbitMQ instead of Kafka if you address replay. Pull-to-refresh only, no WebSocket, on mobile. What matters is that you can argue the tradeoff.

    More in System Design Interview Prep: AI Coach Edition

    • SD Coach · Building Blocks
    • SD Coach · Building Blocks, One Server to Millions (Slides)
    • SD Coach · The Data Layer
    • SD Coach · Unique IDs and the URL Shortener
    • SD Mock · Design Pastebin
    • SD Coach · News Feeds and Typeahead
    • SD Mock · Design Twitter
    • SD Mock · Design Typeahead Suggestion
    • SD Mock · Design Twitter Search
    • SD Coach · Rate Limiting
    • SD Mock · Design an API Rate Limiter
    • SD Coach · Event-Driven Systems and Notifications
    View the full course (43 sessions) →