Design the backend of a news feed (like X or Instagram)
Design the backend of a news feed like X (Twitter) or Instagram: users follow other users, post content, and open a home timeline showing recent posts from the people they follow, newest or most relevant first.
A typical framing: "300 million daily active users, each opening their feed about 10 times a day. Users post a few times a day on average, but some accounts have 100 million followers. The feed should load in under 200 ms."
TL;DR
The core decision is when to assemble the feed:
- Fan-out on write (push): when someone posts, insert the post id into each follower's precomputed timeline (a list in Redis). Reads are a single fast lookup, but a post by an account with 100M followers means 100M writes.
- Fan-out on read (pull): when a user opens the feed, fetch recent posts from everyone they follow and merge them. No write amplification, but reads are slow and expensive.
- Hybrid (the standard answer): push for normal accounts, pull for celebrities, and merge both at read time.
Timelines store post ids only; post bodies, authors and counters are hydrated from caches. Ranking (if not purely chronological) runs on a candidate set at read time. Pagination uses cursors. Everything heavy (fan-out, counters, ranking features) happens asynchronously through queues.
1. Requirements and estimates
Functional
- Post (text, images), follow and unfollow.
- Home timeline: posts from followed accounts, newest first (optionally ranked).
- Like and comment counts on each post.
Non-functional
- Feed load p99 under ~200 ms; highly available (a slightly stale feed is fine).
- New posts appear in followers' feeds within a few seconds.
Estimates
- Reads: 300M × 10 = 3B feed loads / day ≈ 35,000 per second, peaks ~100,000.
- Writes: 300M × 2 = 600M posts / day ≈ 7,000 per second.
- Fan-out with an average of 200 followers: 600M × 200 = 120B timeline inserts / day (≈1.4M per second). This number is why the celebrity problem and the hybrid matter.
- Timeline cache: keep the last 800 ids per active user, 8 bytes each: 300M × 800 × 8 ≈ 2 TB of Redis, spread over a cluster.
2. API
POST /v1/posts { text, mediaIds } -> 201 { postId }
GET /v1/feed?cursor=&limit=20 -> { posts: [...], nextCursor }
POST /v1/users/{id}/follow
DELETE /v1/users/{id}/follow
POST /v1/posts/{id}/likes3. Data model
users (id, handle, name, follower_count, is_celebrity)
follows (follower_id, followee_id, created_at) -- two indexes: by follower and by followee
posts (id, author_id, text, media, created_at) -- id is time-sortable (Snowflake)
post_stats (post_id, likes, comments, reposts) -- counters, updated asynchronously
timeline Redis list per user: [postId, postId, ...] -- newest first, capped lengthSnowflake-style ids (timestamp + machine + sequence) are unique without coordination and sort by time, so "newer than cursor" is a simple comparison.
4. High-level architecture
- Post service stores the post and emits an event.
- Fan-out workers read the author's followers in batches and prepend the post id to each follower's timeline (only for followers active recently, to avoid wasting cache on dormant users).
- Feed service reads the user's timeline ids, merges recent posts from followed celebrities, ranks, hydrates and paginates.
5. Deep dives and scaling
The hybrid in practice
- Mark accounts above a threshold (e.g. 100k followers) as celebrities; don't fan out their posts.
- At read time:
ids = timeline(user) ∪ recentPosts(celebritiesFollowedBy(user)), then sort or rank. Celebrity posts are hot and heavily cached, so pulling them is cheap. - For inactive users, skip fan-out entirely; build their timeline with a pull when they come back.
Hydration
A page of 20 ids becomes 20 posts plus authors plus counters. Use batch gets (MGET) from post and user caches, and fall back to the database only for misses. Counters are cached separately because they change constantly.
Ranking
Chronological is simple and predictable. Ranked feeds take a few hundred candidates (from the timeline), compute features (author affinity, engagement, freshness, media type), score them with a model, and return the top items. The ranker must have a strict latency budget and fall back to chronological if it's slow.
Pagination
Cursor = the last seen post id (or rank position plus a snapshot id for ranked feeds). Offsets break because new posts constantly shift positions.
Consistency and edge cases
- Unfollow: remove the followee's posts from the timeline lazily (filter at read time) instead of rewriting it.
- Deleted posts: hydration drops them; a background job cleans timelines.
- Your own post must appear in your feed immediately: insert into the author's timeline synchronously ("read your own writes").
- Thundering herd when a celebrity posts: millions of readers request the same post; request coalescing and a short-lived local cache handle it.
Storage choices
Posts in a horizontally scalable store (Cassandra, or sharded MySQL by post id); the follow graph sharded by user id with both directions indexed; timelines in a Redis cluster, rebuilt from the database if lost.
Common follow-ups
- "Why not pure fan-out on read?" Each feed load would query hundreds of authors' recent posts and merge them: at 35k reads per second that's millions of queries per second, with poor latency.
- "How do you handle a user following 5,000 accounts?" Fan-out on write still works for them (they only receive). On read, the timeline is already built; only their celebrity list is merged.
- "How fast does a new post propagate?" Fan-out is asynchronous: seconds for normal accounts, and celebrity posts are visible immediately via pull.
What interviewers look for
- A clear comparison of fan-out on write vs. read, and the hybrid for celebrities.
- Estimates that expose the write amplification.
- Timelines of ids plus hydration from caches.
- Cursor pagination, time-sortable ids and asynchronous processing.
- Handling edge cases: unfollows, deletes, inactive users and ranking with a latency budget.