Design a News Feed
A news feed shows each user the recent posts of the people they follow, newest (or most relevant) first: the home timeline of X/Twitter, Instagram or LinkedIn. The core question is when to do the work of assembling a feed: when a post is written (fan-out on write) or when a feed is read (fan-out on read). The answer, as often, is "both, depending on the user".
1. Requirements
Functional
- Users publish posts (text, links, media URLs) and follow other users.
- The home feed shows posts from followed accounts, newest first, paginated.
Non-functional
- Feed loads in under 200 ms (p99); posts appear in followers' feeds within a few seconds.
- 300 million DAU, each opening the feed ~10 times a day; 1 in 10 users posts once a day.
- Follower counts are extremely skewed: most users have ~200 followers, a few celebrities have tens of millions.
2. Estimates
dau = 300_000_000
feed_reads_per_user = 10
posts_per_day = dau * 0.1
avg_followers = 200
read_qps = dau * feed_reads_per_user / 86_400
write_qps = posts_per_day / 86_400
fanout_writes = write_qps * avg_followers # feed-cache inserts if we push every post
print(f"feed reads: {read_qps:,.0f}/s avg")
print(f"new posts : {write_qps:,.0f}/s avg")
print(f"fan-out on write: {fanout_writes:,.0f} feed inserts/s avg")
# Cache the latest 500 post ids per user's feed (8-byte ids)
cache_gb = dau * 500 * 8 / 1e9
print(f"feed cache (500 ids x {dau:,} users): {cache_gb:,.0f} GB")feed reads: 34,722/s avg
new posts : 347/s avg
fan-out on write: 69,444 feed inserts/s avg
feed cache (500 ids x 300,000,000 users): 1,200 GB
Reads outnumber posts 100 to 1, so making reads cheap is worth doing extra work on writes. A precomputed feed of post ids for every active user fits in about 1.2 TB of memory, spread over a Redis cluster.
3. Two strategies
Fan-out on WRITE (push) Fan-out on READ (pull)
post -> for each follower: prepend post id read feed -> for each followee:
to follower's cached feed fetch recent posts, merge, sort
read feed -> one cache lookup post -> just store it| Fan-out on write | Fan-out on read | |
|---|---|---|
| Read cost | O(1): read a precomputed list | O(followees): query and merge many timelines |
| Write cost | O(followers) inserts | O(1) |
| Celebrity with 50 M followers | 50 M inserts per post: slow, expensive | No problem |
| Inactive users | Wasted work on feeds nobody reads | No waste |
4. Modelling both
from collections import defaultdict
import heapq
follows = { # follower -> followees
"ana": ["ben", "cara", "star"],
"ben": ["ana", "star"],
"cara": ["ana"],
}
followers = defaultdict(list)
for user, followees in follows.items():
for f in followees:
followers[f].append(user)
followers["star"] += [f"fan{i}" for i in range(10_000)] # a celebrity
posts = defaultdict(list) # author -> [(time, post id)]
feeds = defaultdict(list) # precomputed feed caches (push model)
work = {"push_writes": 0, "pull_reads": 0}
def publish(author, t, post_id):
posts[author].append((t, post_id))
for f in followers[author]: # push
feeds[f].insert(0, (t, post_id))
work["push_writes"] += 1
def pull_feed(user, limit=5):
timelines = []
for f in follows.get(user, []):
work["pull_reads"] += 1
timelines.append(sorted(posts[f], reverse=True)[:limit])
return [pid for _, pid in heapq.merge(*timelines, reverse=True)][:limit]
publish("ben", 1, "ben-1")
publish("star", 2, "star-1")
publish("cara", 3, "cara-1")
publish("ben", 4, "ben-2")
print("ana push feed:", [pid for _, pid in feeds["ana"][:5]])
print("ana pull feed:", pull_feed("ana"))
print(work)ana push feed: ['ben-2', 'cara-1', 'star-1', 'ben-1']
ana pull feed: ['ben-2', 'cara-1', 'star-1', 'ben-1']
{'push_writes': 10005, 'pull_reads': 3}
Both give the same feed, but the push model did over 10,000 writes, almost all of them caused by one post from star. The pull model did only three timeline reads, but it does them on every feed open.
5. The hybrid
Real systems combine them:
- Normal authors: fan-out on write into followers' cached feeds.
- Celebrities (followers above a threshold, e.g. 100,000): don't fan out. At read time, merge the user's cached feed with the recent posts of the few celebrities they follow.
- Inactive users: skip fan-out to users who haven't logged in for weeks; rebuild their feed on demand when they return.
CELEBRITY_THRESHOLD = 1_000
followers = {"ben": ["ana", "cara"], "star": ["ana"] + [f"fan{i}" for i in range(10_000)]}
follows = {"ana": ["ben", "star"]}
posts = {"ben": [], "star": []}
feed_cache = {"ana": [], "cara": []}
writes = 0
def is_celebrity(user):
return len(followers[user]) >= CELEBRITY_THRESHOLD
def publish(author, t, post_id):
global writes
posts[author].append((t, post_id))
if is_celebrity(author):
return # followers pull these at read time
for f in followers[author]:
if f in feed_cache:
feed_cache[f].insert(0, (t, post_id))
writes += 1
def read_feed(user, limit=10):
pulled = [p for f in follows[user] if is_celebrity(f) for p in posts[f]]
merged = sorted(feed_cache[user] + pulled, reverse=True)
return [pid for _, pid in merged[:limit]]
publish("ben", 1, "ben-1")
publish("star", 2, "star-1")
publish("ben", 3, "ben-2")
publish("star", 4, "star-2")
print("ana's feed:", read_feed("ana"))
print("fan-out writes:", writes)ana's feed: ['star-2', 'ben-2', 'star-1', 'ben-1']
fan-out writes: 4
Four writes instead of more than 20,000, and Ana still sees every post in order.
6. Building the page
The feed cache holds only post ids. Rendering a page then hydrates them: one batched lookup for post bodies and one for author profiles (both heavily cached), plus like counts from a counter service. Pagination uses a cursor ("posts older than id X"), never offsets.
GET /feed?cursor=... -> feed cache: 20 post ids -> post cache (multi-get) -> user cache (multi-get) -> JSONRanking (instead of pure time order) adds a scoring step: candidate posts from the feed cache are scored by a model (affinity with the author, engagement, freshness) and re-ordered. The pipeline stays the same: candidates from fan-out, then ranking, then hydration.
Trade-offs
| Decision | Choice | Reason |
|---|---|---|
| Feed assembly | Hybrid push/pull | Cheap reads for most, no write storms for celebrities |
| Feed storage | Redis lists of ids, capped at ~500 | Fast, bounded memory; older pages fall back to pull |
| Post storage | Sharded by post id, cached | Hydration by multi-get |
| Fan-out execution | Async workers via a queue | Publishing returns immediately; feeds update within seconds |
Test yourself
What is the main problem with pure fan-out on write?
- Feeds load slowly
- A celebrity's post requires millions of feed inserts
- Posts can't be deleted
- It needs a SQL database
In the hybrid model, how do celebrity posts reach followers?
- They are pushed like normal posts
- Followers' feeds merge them in at read time
- They are emailed
- They are never shown
Why store only post ids in the feed cache?
- Ids are easier to sort
- It keeps the cache small, and edits to a post or profile are visible without rewriting every feed
- Redis can't store text
- To hide content from users