Course contents

17. Real-World System Design Lesson 11 of 20

Social Media Feed

Design a home feed end to end: fan-out on read vs on write, the celebrity problem and the hybrid fix, ranking, and surviving the loss of the timeline cache.

25 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Feeds are read far more than written, so precomputing timelines (fan-out on write) makes the common path one lookup.
  • Fan-out on read touches every shard per read; fan-out on write pays one insert per follower per post.
  • Celebrities make fan-out on write explode; the hybrid pulls their posts at read time and merges.
  • Ranking scores a candidate set and must have a strict time budget with an unranked fallback.
  • Precomputed timelines become critical state: replicate them, and never let a cache loss fall through to the source at full rate.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A home feed shows a user recent posts from the accounts they follow, usually ranked. The system behind it stores posts, keeps the follow graph, builds each user's timeline and serves it fast. The core design decision is when a timeline is assembled: when it is read (fan-out on read, "pull") or when a post is written (fan-out on write, "push").

Why it exists

Feeds are the canonical read-heavy, personalised workload. Every user's feed is different, so a single cached page does not help, and reads outnumber writes by orders of magnitude. Building a feed from scratch on every read means querying many shards and merging; doing it ahead of time means copying each post into many timelines. The case study is about choosing where to pay, and then handling the cases where that choice breaks.

How it works

Requirements. Functional: publish a post, follow/unfollow, read the home feed (paginated). Non-functional: feed reads well under 200 ms at the 95th percentile, new posts visible within seconds, high availability; small staleness is acceptable.

Estimates (illustrative). 300 M daily users × 10 feed opens/day ≈ 35 000 reads/s on average, a few times that at peak. If 10% post once a day, about 350 posts/s. With 200 followers on average, pure fan-out on write is about 70 000 timeline inserts/s. Timelines store post IDs (8–16 bytes each) capped at a few hundred entries, so 300 M timelines × 500 IDs × ~10 bytes ≈ 1.5 TB: memory-sized across a cache cluster.

Fan-out on read. Posts live in a store sharded by author. To build a feed, the feed service looks up who the user follows, queries every shard holding their recent posts, merges by time (or score) and returns the top N. Writes are cheap; each read costs one query per shard, so read traffic is multiplied by the shard count and the slowest shard sets the latency.

Fan-out on write. The post service stores the post once, then publishes an event to a topic. Fan-out workers look up the author's followers and insert the post ID into each follower's precomputed timeline (typically a capped list in an in-memory store, partitioned by user). In the lesson, the topic copies each post into one timeline queue per timeline-cache shard; each queue's writer handles the followers on that shard. A feed read is then one lookup, plus hydration of the IDs into posts (from a post cache).

The celebrity problem. Fan-out cost is proportional to follower count. An account with tens of millions of followers turns one post into tens of millions of inserts, which delays every other post queued behind it. The hybrid approach skips fan-out for accounts above a follower threshold; at read time the feed service fetches recent posts from the celebrities the user follows and merges them with the precomputed timeline. Inactive users are often skipped too: their timelines are rebuilt by fan-out on read when they return.

Ranking. The merged timeline is a candidate set (hundreds of posts). A ranking service fetches features (author affinity, engagement, recency, content type) from a feature store and scores candidates with a model, often in two stages (a cheap first pass, then a heavier model on the top few hundred). It runs on every feed read, so it gets a strict deadline and the feed falls back to chronological order when it misses.

Failure handling. The precomputed timelines are now critical state. If a cache node is lost, its users' reads fall back to fan-out on read, which the posts store is not sized for at full rate. Replicate timeline partitions, rebuild lost ones gradually from a replica or from the source with rate limits, and degrade (shorter, unranked feed) before the source overloads.

When to use it

Fan-out on write suits read-heavy feeds where most accounts have modest follower counts and freshness within seconds is fine. Fan-out on read suits small systems, feeds with very many sources per reader but little traffic, or rarely-read feeds. The hybrid is what large social feeds converge on.

When not to

  • Small scale: one database with a good index on (author, created_at) and a query over followed authors is simpler and fast enough.
  • Feeds that must be strictly consistent with the source (compliance, financial timelines): precomputed copies are always slightly stale.
  • Highly dynamic feeds where ranking dominates and the candidate set comes from search or recommendation retrieval rather than the follow graph; the "timeline" is then a retrieval problem.

Trade-offs

Choice You gain You pay
Fan-out on write Feed read is one lookup One insert per follower per post; storage for many copies; delayed visibility under backlog
Fan-out on read Cheap writes, always fresh Every read touches every shard; slowest shard sets latency
Hybrid threshold low Little fan-out work More pulled sources merged per read
Hybrid threshold high Simple reads Writers fall behind on big accounts
Ranking Engagement, relevance Latency and compute on every read; harder to explain and debug
Skip inactive users Large saving in fan-out work Rebuild cost and latency on their return

Alternatives

  • Pure pull with aggressive caching of per-author recent posts: reads merge from a cache rather than shards; good when the follow graph is small.
  • Retrieval-based feeds (recommendation feeds): candidates come from embeddings or interest graphs, not only follows; the follow graph is one of several sources.
  • Per-user materialised views in a database (instead of an in-memory cache): cheaper storage, slower reads.

Failure modes

  • Fan-out backlog: a burst of large accounts posting, or slow writers, delays every post; visible as growing queue depth and age of the oldest message, not as slow reads.
  • Timeline cache loss: reads for affected users fall back to the source at full rate, a thundering herd that can take the posts store down.
  • Hot partitions: a celebrity's post or profile is read by millions at once; cache it separately and replicate it widely.
  • Deleted or edited posts remain as copies in timelines until filtered at read time or cleaned by a reverse fan-out.
  • Ranking timeouts: without a fallback, a slow model turns into failed feed loads.

In production

Store IDs, not post bodies, in timelines and hydrate from a post cache. Cap timeline length. Monitor fan-out lag (age of oldest unprocessed post) per queue and alert on it. Make fan-out idempotent (a redelivered event must not insert twice). Treat follow/unfollow as events too: a new follow backfills recent posts, an unfollow filters at read time. Give ranking a deadline and a chronological fallback. Rebuild lost timeline partitions from replicas with rate limits.

Common misconceptions

  • "More shards fix slow fan-out on read." Each read still touches every shard; more shards spread data, not requests.
  • "Fan-out on write makes posts appear instantly." They appear after the queue and writers process them; under load, freshness degrades first.
  • "Celebrities are a read problem." Their followers' reads are fine; the cost is the write fan-out of each post.
  • "The cache is just an optimisation." Once timelines are precomputed, losing them is an outage unless the fallback is protected.

Interview angle

Start with requirements and the read/write ratio, then present both fan-out models with their costs in numbers. Interviewers almost always ask about celebrities: answer with the hybrid, the threshold, and how merge cost grows with followed celebrities. Expect follow-ups on ranking latency, deleted posts, inactive users, new follows (backfill), pagination (cursor by post ID or score) and what happens when the timeline cache fails.

Model assumptions

The simulation is a simplified model, not a benchmark, and it runs a small slice of the illustrative scale: 150–800 feed reads/s and 10 posts/s. Posts shards have 8 connections, ~12 ms per read and ~20 ms per write (lognormal), with a 250 ms pool timeout. With fan-out on read, the Feed Service queries all three shards at the same time and merges when the slowest has answered, so a read costs the slowest shard's time, and every read still touches every shard. Once timelines are precomputed, the Feed Service asks its dependencies in order (cache first); a miss goes to a Timeline Builder that rebuilds the timeline by querying the three shards in parallel. The topic copies each post into three timeline queues; one copy stands for the inserts into all followers on that timeline shard. The Timeline Cache is a fixed 98% hit ratio, not a model of which timelines are present. The celebrity post is modelled as 600 fan-out batches in one second. The Feature Store lookup in the ranking step is a scripted illustration; Ranking itself is simulated as a 15 ms service. Timeline Writers updating both cache replicas is described, not simulated. Network hops are 2–20 ms. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Requirements and estimates

    We are designing the home feed: open the app and see recent posts from the accounts you follow, newest or best first. Functional needs: publish a post, read your feed, follow and unfollow. Non-functional: a feed read in well under 200 ms, a new post visible to followers within seconds, and the feed must stay up even when parts of it fail. Small staleness is fine.

    Illustrative estimate: 300 M daily users opening the feed 10 times a day is about 35 000 reads/s on average and maybe 3× that at peak. If one user in ten posts once a day, that is about 350 posts/s. Reads outnumber writes by about 100 : 1, so the design should make reads cheap even if writes get more expensive.

    The scene runs a small slice of that: 150 feed reads/s and 10 posts/s. Posts are stored once, in three Posts shards keyed by author.

    Scene: Readers send 150 feed reads per second to the Feed Service; Authors send 10 posts per second through the Post Service and a Shard Router into three Posts shards. Annotations give the illustrative full-scale estimates.

    Key idea: A feed is read far more often than it is written. Optimise the read path first.

  2. 2. Fan-out on read: build the feed when it is opened

    The simplest design computes the feed at read time. The people you follow are spread over every shard, so the Feed Service asks all three shards at the same time for their recent posts and merges them once the last one has answered. A post is written once and costs nothing more.

    The price is paid on every read: one feed read becomes three shard queries, so the shards together serve three times the read traffic. The three queries overlap, so a read waits for the slowest shard rather than the sum of all three. P95 here is around 75 ms, more than half of it the round trip to the phone.

    Scene: Each feed read goes from the Feed Service to Posts shard 1, 2 and 3 at the same time and is merged when the slowest has answered. All requests succeed with a P95 latency around 75 ms.

    Key idea: Fan-out on read: cheap writes, expensive reads. Every feed read touches every shard.

  3. 3. Evening peak: the shards drown in reads

    One second in, reads climb to 800 per second. Every one of them is three shard queries, so each shard is asked for about 800 reads/s plus its share of writes. That is more than one shard can serve (about 660/s here).

    The connection pools fill, queries wait, and those that wait longer than 250 ms fail with pool timeouts. Adding more shards does not fix it: in this design a feed read touches every shard, so each new shard gets the full read rate too.

    Scene: Feed reads rise to 800 per second. All three shards saturate, queries wait for connections and some feed reads fail with pool timeouts.

    Key idea: With fan-out on read, read traffic is multiplied by the number of shards a feed has to touch.

  4. 4. Fan-out on write: precompute every timeline

    Flip the work around. When someone posts, the Post Service stores it in its shard and publishes it to the New Posts topic. The topic copies the post into one timeline queue per timeline-cache shard, and Timeline Writers insert it into the precomputed timeline of every follower on that shard.

    A feed read is now a single lookup in the Timeline Cache. 98% of timelines are there; the rest (users who have not opened the app for weeks) go to a Timeline Builder, which rebuilds them from the shards with the fan-out on read from before, all three shards in parallel. Reads stop touching the shards, the timeouts disappear, and even at 800 reads/s P95 (about 55 ms) is lower than fan-out on read managed at 150 (about 75 ms). Most of what is left is the round trip to the phone.

    The cost moved to writes: every post becomes three queue messages here, and in reality one timeline insert per follower. Writes are rare, so that trade is worth it.

    Scene: Posts are published to the New Posts topic, which copies each into three timeline queues drained by three Timeline Writers. Feed reads now look up the Timeline Cache; only 2% miss and go to the Timeline Builder, which reads the three shards in parallel. At 800 reads per second nothing fails and P95 is about 55 ms, lower than the 75 ms of fan-out on read at 150 reads per second.

    Key idea: Fan-out on write pays at post time (one insert per follower) so that a feed read is one cheap lookup.

  5. 5. A celebrity posts

    Half a second in, an account with millions of followers posts once. For fan-out on write, that one post means millions of timeline inserts. Here it arrives as 600 fan-out batches in one second, each standing for a few thousand followers.

    The Timeline Writers keep working at the same speed, so the timeline queues jump to hundreds of messages and take several seconds to drain. Every ordinary post published meanwhile waits behind the celebrity’s batches: for a while, nobody’s new posts reach their followers’ feeds. Reads are unaffected, but freshness is gone, and a few such accounts posting at once would keep the writers permanently behind.

    Scene: A celebrity posts and 600 fan-out batches flood the topic in one second. All three timeline queues grow to hundreds of messages and take several seconds to drain; ordinary posts queue behind them.

    Key idea: Fan-out on write cost grows with follower count. One celebrity post can be more work than all ordinary posts together.

  6. 6. Hybrid: push for most, pull for celebrities

    Accounts above a follower threshold are not fanned out. Their posts are written once to a small Celebrity Posts service. When you open your feed, the Feed Service first fetches recent posts from the few celebrities you follow, then reads your precomputed timeline, and merges the two.

    The celebrity posts again: this time nothing floods the timeline queues, which stay near empty, so ordinary posts stay fresh. The read path pays a little: one extra lookup, so P95 rises by about 8 ms. Most real feeds use some version of this split, with the threshold tuned to the cost of fan-out versus the cost of the read-time merge.

    Scene: The Feed Service now first asks the Celebrity Posts service, then the Timeline Cache, and merges both. Celebrity posts are no longer fanned out, the timeline queues stay near empty, and read P95 is about 8 ms higher.

    Key idea: Hybrid fan-out: push ordinary posts, pull celebrity posts at read time and merge.

  7. 7. Ranking: from candidates to a feed

    A chronological merge is only the candidate set. Most feeds rank it: a Feed API in front takes the candidates from the Feed Service and sends them to a Ranking service, which looks up features (author affinity, engagement so far, post age) in a feature store and scores each candidate with a model. The top results are returned.

    The feature lookup and scoring are a scripted illustration here; in the simulation, Ranking costs about 15 ms per feed, and with the extra hops P95 rises by about 30 ms. It sits on every read, so it gets a strict time budget: if scoring is late, a good design serves the unranked candidates rather than nothing.

    Scene: Readers now call the Feed API, which gets candidates from the Feed Service and then asks Ranking to score them. Scripted packets show the order: candidates, feature lookup, scores back. P95 rises by about 30 ms.

    Key idea: Separate candidate generation (cheap, wide) from ranking (expensive, narrow) and give ranking a strict latency budget.

  8. 8. The timeline cache node dies

    One second in, the Timeline Cache node crashes. Every lookup now misses, and the Feed Service falls back to what it does for a cold timeline: the Timeline Builder rebuilds the feed from the Posts shards.

    That is fan-out on read again, at 800 reads/s: the same overload as in the read storm. Shard pools fill and feed reads fail with timeouts. The fallback that is harmless for 2% of reads is a thundering herd for 100%.

    Scene: The Timeline Cache goes offline. All feed reads fall back to the Timeline Builder and the Posts shards, which saturate; feed reads start failing with pool timeouts.

    Key idea: A fallback path sized for misses becomes an outage when every request takes it.

  9. 9. Replicate the timelines

    Timelines are kept on two cache replicas; the Timeline Writers update both. The first node is still down, but its lookups fail fast and the Feed Service tries the replica next, which has the same 98% of timelines. The shards see only the usual 2% of misses and the errors stop.

    Other defences belong next to this: rebuild a lost cache node gradually (rate-limit rebuilds, warm it from the replica), and shed or degrade (serve a shorter, unranked feed) before the shards fall over.

    Scene: A Timeline Replica is added behind the failed Timeline Cache. Lookups to the dead node fail fast and go to the replica; the shards only see normal misses and feed reads succeed again.

    Key idea: The precomputed timelines are now critical state: replicate them, and never let a cache loss fall through to the source at full rate.

  10. 10. What this design trades

    Freshness vs read cost: fan-out on write makes reads one lookup but delays visibility by the queue time; under load, timelines lag before reads slow down. Storage: every post is copied into many timelines (store IDs, not posts, and cap each timeline at a few hundred entries). Wasted work: fanning out to inactive followers is pure cost, so many systems skip them and rebuild on their next visit.

    Consistency: a deleted or edited post must be filtered at read time, because copies already sit in timelines. Celebrity threshold: too low and reads merge many pulled sources; too high and writers fall behind. And ranking adds the most latency and the most value: keep it bounded.

    Scene: The full design runs healthy: Feed API, Feed Service merging celebrity posts and replicated timelines, Ranking, and fan-out on write through the topic, timeline queues and writers.

    Key idea: Feeds trade write amplification and storage for cheap reads, then patch the extremes (celebrities, inactive users, cache loss) explicitly.