Design a News Feed System: Fanout-on-Write vs Fanout-on-Read & Celebrity Hybrid
The Core Challenge: Merging Timelines in < 100ms
WHERE user_id IN (...) ORDER BY created_at DESC LIMIT 20) collapses immediately under load.News Feed Hybrid Fanout Architecture
1. Fanout-on-Write (Push) vs. Fanout-on-Read (Pull)
Fanout-on-Write (Push Model)
post_id directly into every active follower's pre-computed Redis News Feed list.- Pro: Reading a home timeline is an $O(1)$ Redis lookup (
LRANGE feed:user_123 0 20)—blazingly fast! - Con (The Celebrity Problem): If a celebrity with 50 million followers posts a photo, pushing
post_idinto 50M Redis keys triggers a massive write storm and lags minutes behind! And wasting RAM for inactive users who haven't logged in for months burns budget.
Fanout-on-Read (Pull Model)
- Pro: Zero write amplification; works cleanly for celebrities and saves RAM for inactive users.
- Con: Slow feed reads when following hundreds/thousands of users.
2. The Production Answer: Hybrid Fanout
- Normal Users (
< 10Kfollowers): Use Fanout-on-Write (Push) into Redis sorted lists ofpost_ids(only for active users logged in within the last 30 days). - Celebrities / Mega-Accounts (
> 10Kfollowers): Do NOT push to follower caches. Keep their posts in their own user timeline cache. - Feed Read Time: Fetch the user's pre-computed pushed feed from Redis (
20IDs), pull recent posts from the few celebrities they follow, merge/rank them in memory, and hydrate post text/media!
3. Keeping Feed Memory Lean: Store IDs, Not Full Payloads
Redis News Feed Cache: user:42:feed ──► [(post_991, ts_1), (post_840, ts_2), ...]
│
Hydration Cache: post:991 ──► { text, media_cdn_url, author_id }
user:7 ──► { username, avatar_cdn_url }
(post_id, user_id) tuples in the feed cache and batch-hydrate post & author metadata (MGET) on read!