Design: news feed

In one sentence

Precompute each user's feed by pushing new post IDs into followers' cached lists, but pull posts from high-follower accounts at read time and merge; hydrate, rank, and page with cursors.

Push for most authors, pull for the few with huge followings, and merge both lists at read time.

How it works

  • Fan-out on write pushes each new post ID into every follower's cached feed, so a read is one lookup.
  • Fan-out on read merges followees' recent posts at request time: cheap writes, expensive reads.
  • Celebrities break push: one post means millions of writes. Pull their posts at read time and merge.
  • Feeds hold only post IDs (~800 per user); bodies and counts are hydrated from caches at read time.
  • Page with a cursor (last score and ID), never an offset, so new posts don't shift pages.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your feed uses fan-out on write for every author. A creator with 40M followers posts, and post-to-feed lag jumps to 6 minutes for everyone, including users who follow only friends. Best fix?

Go deeper

Back-of-the-envelope calculator Interactive labCache hit ratio Interactive labDo this round in 45 minutes System design round
Full explanation

Requirements

Functional: publish posts, follow accounts, and load a home feed of followed accounts' posts (newest or ranked) with infinite scroll. Non-functional: feed loads in ~200 ms p99 (assumed); a new post reaches followers within seconds; reads far outnumber writes; a stale feed beats an error.

Scale (assumed): 300M DAU × 10 loads/day ≈ 35k feed reads/s; 150M posts/day × 200 followers ≈ 350k feed inserts/s if every post is pushed.

Questions I'd ask:

  1. Chronological or ranked? Ranking changes pagination.
  2. What does the follower distribution look like? A few accounts with tens of millions decide the design.
  3. How fresh must a celebrity's post be: seconds or a minute?

API and data model

POST /posts and GET /feed?cursor=…&limit=20 → {items, next_cursor}. posts(post_id, author_id, body, created_at) with time-sortable IDs; follows(follower_id, followee_id) indexed both ways; feed:{user_id} holds only the newest ~800 post IDs with scores, in Redis.

Architecture

Write: the post service stores the post and emits an event; fan-out workers page through the author's followers and push the post ID into each follower's feed list (Queues vs streams (Kafka)). Read: the feed service reads the user's list, merges recent posts from the few high-follower accounts they follow, hydrates bodies, authors and counts from caches, ranks (Design: news feed ranking) and returns a page with a cursor.

The hard parts

  1. Fan-out strategy: push makes reads cheap but writes scale with followers; pull is the reverse. The hybrid pushes for most authors and pulls for celebrities.
  2. Pagination on a feed that changes every second: cursors, never offsets.
Code Hybrid fan-out and cursor reads with Redis sorted sets
pythonHybrid fan-out and cursor reads with Redis sorted sets
import heapq
import redis

r = redis.Redis()
FEED_LEN = 800        # IDs only, newest 800 (Twitter's 2013 cap)
CELEB = 100_000       # follower threshold: pull instead of push (tunable)

def on_post(author: int, post_id: int, ts: float):        # fan-out worker
    r.zadd(f"posts:{author}", {post_id: ts})                # author timeline
    if follower_count(author) >= CELEB:
        return                                              # no fan-out
    for batch in followers_in_batches(author, 1_000):
        pipe = r.pipeline()
        for uid in batch:
            pipe.zadd(f"feed:{uid}", {post_id: ts})
            pipe.zremrangebyrank(f"feed:{uid}", 0, -FEED_LEN - 1)  # trim
        pipe.execute()

def read_feed(uid: int, cursor: float | None = None, limit: int = 20):
    # Cursor = score of the last item seen (exclusive): new posts don't
    # shift pages. Production uses (ts, post_id) to break ties.
    top = f"({cursor}" if cursor else "+inf"
    def newest(key):
        return r.zrevrangebyscore(key, top, "-inf", start=0, num=limit,
                                  withscores=True)
    pushed = newest(f"feed:{uid}")
    pulled = [newest(f"posts:{c}") for c in celebrities_followed(uid)]
    merged = heapq.merge(pushed, *pulled, key=lambda x: -x[1])
    page = [item for _, item in zip(range(limit), merged)]
    next_cursor = page[-1][1] if page else None
    return hydrate([pid for pid, _ in page]), next_cursor  # bodies, authors
Real example

Twitter in 2013 (Raffi Krikorian, Timelines at Scale): ~300k QPS of timeline reads against ~5k tweets/s on average. Home timelines lived in Redis, capped at 800 entries and replicated on 3 machines. Fan-out on write made reads cheap, but a tweet from Lady Gaga to ~31M followers could take up to 5 minutes to reach everyone. The fix they described is the hybrid: stop fanning out for the biggest accounts and merge their tweets in at read time.

Trade-offs +3 · −3

+ You gain

  • A feed read is one cached list plus a batched hydrate: the fast path serves the dominant traffic.
  • The hybrid caps write amplification at the follower threshold; a celebrity post costs one write.
  • ID-only feeds keep memory small and turn deletes and edits into a hydration-time filter.

− You pay

  • Fan-out lag: followers of large-but-not-celebrity accounts may see posts seconds to minutes late.
  • Two read paths (cached list and pulled celebrities) to merge, test and keep consistent.
  • Precomputed feeds for inactive users waste writes and memory unless you skip or expire them.

Use it when

Follow-graph products where reads far outnumber posts and a few seconds of staleness is fine: social feeds, activity streams, team updates.

Avoid it when

When the feed is mostly recommendations from unfollowed accounts: candidate retrieval and ranking dominate, not fan-out. Strictly ordered, consistent views (a ledger) don't fit either.

Numbers to know 5
  • Reads: 300M DAU × 10 loads/day (assumed) = 3B/day ≈ 35k/s average, ~70k at a 2× peak.
  • Push: 150M posts/day × 200 followers (assumed) = 30B feed inserts/day ≈ 350k/s, 10× the read rate.
  • Feed cache: 300M users × 800 IDs × 8 B ≈ 1.9 TB of raw IDs; scores, Redis overhead and replicas multiply it.
  • Twitter (2013): ~300k QPS timeline reads, ~5k tweets/s average, 800-entry Redis timelines, 3 replicas.
  • Celebrity push at Twitter (2013): one tweet to ~31M followers took up to 5 minutes.
Common pitfalls 4
  • Offset pagination (?page=3): new posts shift every page, so users see duplicates and gaps.
  • Fanning out full post bodies: every edit or delete must touch millions of copies.
  • Pushing to every follower, including users inactive for months: most writes are never read.
  • No backfill on follow: a newly followed account stays invisible until its next post.
Interview questions 3

Answer out loud first, then reveal.

A user with 50M followers posts. Walk me through what happens.Show answer

We store the post once and skip fan-out: 50M feed writes would take minutes and starve everyone else's fan-out. Twitter saw exactly that in 2013, up to 5 minutes for a ~31M-follower account. At read time, each follower's feed service pulls the recent posts of the few celebrities they follow, hot in cache because millions read them, and merges them with the precomputed list. The cost moves to one cached read per celebrity followed.

How do you paginate a ranked feed that changes every second?Show answer

Never with offsets: new posts shift every page and users see duplicates. For a chronological feed the cursor is the (timestamp, post_id) of the last item, and the next page asks for strictly older items. For a ranked feed I snapshot: the first request ranks ~500 candidates and stores the ordered IDs for the session with a short TTL; the cursor is (snapshot_id, position). New posts appear behind a "new posts" pill on refresh.

Fan-out workers fall 10 minutes behind. What do you do?Show answer

First protect the users who will look: fan out to recently active followers first and skip users inactive for weeks, who get rebuilt on login. Then cut work: lower the celebrity threshold so more big accounts switch to pull. Then add workers, partitioned so one author can't block a partition. I'd alert on post-to-feed latency, not just queue depth, because a backlog never shows up as errors.

Deep dive 3

Push, pull and the hybrid

Push (fan-out on write): a post costs one write per follower; a feed load is one list read. Followers who never open the app waste that work, so fan out only to recently active users and rebuild the rest on login. Pull (fan-out on read): a post costs one write; a feed load queries every followee and merges. Facebook's Multifeed (2015) works this way: aggregators query leaf servers that keep recent actions in memory, then rank. Hybrid: push for normal authors, pull for accounts above a follower threshold, as Twitter described in 2013. Tune the threshold on fan-out lag and read cost.

Hydration, ranking and pagination

Feeds store IDs and scores, never bodies: a delete or an edit changes one row, not millions of copies. At read time, take ~500 candidate IDs (pushed plus pulled), drop blocked, muted and deleted posts, batch-fetch bodies, authors and counts from caches, then rank. Ranking is a hook: start with recency, then plug in a model (Design: news feed ranking). Page with an opaque cursor: (ts, post_id) for chronological feeds; for ranked feeds, snapshot the ordered list per session with a short TTL and page through it, so a re-rank never duplicates or skips items.

Deletes, new follows and cold users

Deletes and unfollows: don't chase entries across millions of feeds; filter at hydration and let trimming age them out. New follow: backfill the followee's recent posts, or the account looks silent until it posts again. Cold users: their cached feed expired; rebuild it on login from the pull path and resume pushing. Monitoring: post-to-feed latency p99, fan-out queue age and feed-cache hit rate. A fan-out backlog never shows up in error rates; users just see stale feeds.