A news feed shows each user a list of recent posts from the people they follow, newest or most relevant first. Twitter/X, Facebook, Instagram and LinkedIn all have one. The design question is simple: when someone posts, do you do the work now, for every follower, or later, when each follower opens the app? The answer is "both, depending on who posted". This lesson designs Twitter/X first, then shows what changes for LinkedIn.
1. Requirements and Scope
Functional requirements:
- Create a post (short text and optional media). Follow and unfollow users.
- Home feed: posts from the people I follow, in pages, scrolling back in time.
- Profile page: all posts by one user.
Non-functional requirements:
- Fast reads: the feed loads in under 200 ms at p99. People open the feed far more often than they post.
- Fresh enough: a new post shows up in followers' feeds within a few seconds. Not instantly.
- Highly available: a feed that is a few seconds stale is fine. A feed that does not load is not. We choose availability over strict consistency (see the consistency lesson).
- Scalable: hundreds of millions of users, and a few accounts with tens of millions of followers.
Out of scope: search, direct messages, ads, trending topics, and storing media (images and video go to object storage and a CDN).
2. Estimation
- Feed reads: 300 million daily users open the feed about 10 times a day: 3 billion reads a day. 3,000,000,000 ÷ 86,400 ≈ 34,700 per second on average, and about 4 times that at peak: 139,000 per second.
- Posts: 100 million a day, about 1,160 per second, and 4,600 per second at peak. Reads outnumber writes about 30 to 1.
- Post storage: about 1 KB each with metadata: 100 GB a day, 182 TB over 5 years.
- Pull cost: a user follows about 200 accounts. Building a feed by asking each one for recent posts means 200 lookups per read. 139,000 × 200 ≈ 28 million lookups per second. Too much.
- Push cost: each post is copied to about 200 followers. Half of all accounts are inactive in a given month, and we skip them. 100,000,000 × 200 × 50% = 10 billion timeline inserts a day ≈ 116,000 per second, and 463,000 per second at peak. That is about 60 times fewer operations than pulling, because we pay once per post, not once per read.
- Timeline cache: keep the newest 300 post IDs for each of 150 million active users. A sorted-set entry costs about 48 bytes with overhead: 150,000,000 × 300 × 48 B ≈ 2.2 TB. At about 24 GB of usable memory per Redis node, that is about 90 nodes, and 180 with a replica each.
- The celebrity case: an account with 50 million followers posts once. That is 50 million inserts. Even at 500,000 inserts a second, it takes 100 seconds and delays everyone else's posts behind it.
The takeaway: precomputing feeds ("push") wins for almost everyone, and the few huge accounts need a special rule.
3. API
POST /v1/postswith text and media IDs returns201and the post ID.GET /v1/feed?cursor=&limit=20returns posts and anextCursor.GET /v1/users/{id}/posts?cursor=returns one user's posts.PUT /v1/follows/{userId}andDELETE /v1/follows/{userId}.
Pages use a cursor (the ID of the last post seen), not a page number. New posts arrive while the user scrolls, and with page numbers the list would shift and repeat items.
4. Data Model
- Posts
(post_id, author_id, text, media, created_at)in a sharded key-value or wide-column store, with a cache in front. Post IDs are time-sortable (Snowflake style, see the ID generation lesson), so sorting by ID is sorting by time. - Follows kept in two directions:
followers_of(user), used to fan out, andfollowing(user), used to build a feed on demand. Each is sharded by its own key. - Timeline cache: one Redis sorted set per user,
timeline:{userId}. The members are post IDs, and the score is the post ID, so the order is time. Only IDs are stored, not post bodies. That keeps entries tiny and avoids copying a post 200 times.
An example for user 42, whose timeline holds three posts:
key: timeline:42
value: a sorted set, "member = score"
1790233004567 = 1790233004567 (oldest)
1790233009991 = 1790233009991
1790233051122 = 1790233051122 (newest)
ZADD timeline:42 1790233051122 1790233051122 # fan-out adds a new post ID
ZREVRANGE timeline:42 0 19 # feed read: the 20 newest IDs, newest first
5. The Central Decision: Push, Pull or Both
| Approach | On a post | On a feed read | Problem |
|---|---|---|---|
| Pull (fan-out on read) | Save the post. Nothing else | Fetch recent posts of everyone I follow, merge, sort | Slow reads: about 200 lookups per read |
| Push (fan-out on write) | Insert the post ID into every follower's timeline | Read one precomputed list | Huge cost for accounts with millions of followers; wasted work for inactive followers |
| Hybrid | Push for normal accounts. No push for celebrities | Read my timeline, then add recent posts of the celebrities I follow | Two code paths; a threshold to tune |
We choose the hybrid. An account with more than about 100,000 followers is a "celebrity": its posts are not pushed. A typical user follows only a handful of celebrities, so the read adds only a few cheap lookups, and those lookups hit the cache because many people read the same celebrity posts.
6. High-Level Design
flowchart LR
C["Client"] --> PS["Post service"]
PS --> PDB[("Posts store + post cache")]
PS --> K[["Kafka: new posts"]]
K --> FO["Fan-out workers"]
FO --> G[("Social graph: followers")]
FO --> TL[("Timeline cache: Redis sorted sets")]
C --> FS["Feed service"]
FS --> TL
FS --> CP["Celebrity posts (pulled)"]
FS --> PDB
Write path: the post service saves the post and publishes an event to Kafka, then answers the user. Fan-out happens in the background (see the Kafka lesson), so posting stays fast. Read path: the feed service takes post IDs from the timeline cache, adds celebrity posts, fetches the post bodies, and returns a page.
7. Fan-Out in Detail
@KafkaListener(topics = "new-posts")
public void onNewPost(NewPost p) {
if (graph.followerCount(p.authorId()) > CELEBRITY_THRESHOLD) return; // celebrities are pulled at read time
for (List<Long> page : graph.followerPages(p.authorId(), 1000)) { // page through the follower list
redis.executePipelined((RedisCallback<Object>) conn -> { // one round trip for the whole page
for (long follower : page) {
if (!activity.isActive(follower)) continue; // skip inactive users
byte[] key = ("timeline:" + follower).getBytes();
conn.zAdd(key, p.postId(), Long.toString(p.postId()).getBytes());
conn.zRemRange(key, 0, -301); // keep only the newest 300
}
return null;
});
}
}
- Batches and pipelines turn millions of tiny calls into thousands of bigger ones.
- Retries are safe: adding the same ID to a sorted set twice changes nothing.
- Lag is the key metric: the time from "post saved" to "visible in follower feeds". Alert if p99 goes above a few seconds, and scale workers by queue lag.
- Inactive users get no push. When they return, their timeline is rebuilt by pulling from the people they follow, then cached.
8. Reading the Feed
- Take the next page of post IDs from the user's sorted set, starting below the cursor.
- Add the latest posts of the celebrities the user follows, and merge by ID.
- Hydrate: fetch post bodies, author names and like counts with a batched read from the post cache. Misses go to the posts store.
- Filter: drop deleted posts, blocked or muted authors, and accounts the user has since unfollowed.
- Return the page and the cursor, which is the ID of the last post.
The timeline is only a cache of IDs. The posts store and the graph are the truth. If a timeline is lost, we rebuild it by pulling. Deleting a post just removes it from the posts store, and the filter in step 4 hides it everywhere. We never search 200 timelines to remove it.
9. Worked Example: Asha Opens the App
Asha follows 300 accounts, including Dev (180 followers) and a cricketer (40 million followers).
- Dev posts. The post is saved and sent to Kafka. A fan-out worker sees 180 followers and inserts the post ID into 180 timelines. Asha's is one of them. About 2 seconds pass.
- The cricketer posts. The worker sees 40 million followers, which is above the threshold, and does nothing.
- Asha opens the app. The feed service reads her timeline: 20 IDs including Dev's. It also looks up the latest posts of the 3 celebrities she follows (served from cache), and merges the cricketer's post in.
- It fetches the 20 post bodies in one batch, filters out one post from an author she muted, and returns 19 posts with a cursor.
- She scrolls. The next request sends the cursor, and the service returns the next 20 older IDs.
10. Ranking and the LinkedIn Variant
Twitter/X began as a time-ordered feed, and now also offers a "For You" feed ranked by predicted interest. Ranking is a second stage after the steps above. Candidate generation gathers a few hundred posts (the timeline, celebrity posts, recommended posts). A ranking model scores each using features such as how close the user is to the author, how recent the post is, and how much engagement it has had. The top scores are shown.
| Question | Twitter/X | |
|---|---|---|
| Relationship | One-way follow | Mostly two-way connections (plus following) |
| Feed order | Time, with an optional ranked tab | Ranked by relevance by default |
| How long a post stays useful | Hours | Days, so ranking matters more than speed |
| Fan-out concern | Celebrities with tens of millions of followers | Fewer extreme cases; more work in ranking and in feed items like "X liked this" |
The skeleton is the same: posts store, social graph, candidates from cache, then rank. Only the weight shifts, from fan-out toward ranking. In an interview, say the shared design, then name the one or two differences.
11. Counters, Scaling and Failures
- Likes and counts: a hot post gets thousands of likes a second. Do not update one row each time. Count in memory or in sharded counters and write to the store in batches. The counts shown may be a few seconds old.
- Sharding: timelines by user ID with consistent hashing (see the sharding lesson). Posts by post ID, which spreads load evenly. The graph is stored in both directions.
- Timeline cache lost: rebuild by pulling from the graph and posts, in the background for active users, and on the next open for the rest. Pulls are rate limited so a rebuild does not overwhelm the stores.
- Fan-out backlog: the queue absorbs bursts. A separate lane for celebrities or very large fan-outs keeps them from delaying normal posts.
- Regions: replicate posts and timelines to each region, and serve reads locally. A new post may take a little longer to appear across oceans, which the freshness goal allows.
12. Common Pitfalls
- Pure push, with no rule for celebrities. One post floods the system.
- Pure pull. Every feed read becomes hundreds of lookups.
- Copying whole posts into every timeline. Store IDs only.
- Page numbers instead of cursors. Items repeat or are skipped as new posts arrive.
- Fan-out inside the post request. Posting becomes slow, and one failure loses the post. Use a queue.
- Pushing to inactive users, which wastes half the work.
- Rewriting timelines on delete. Filter at read time instead.
13. Interview Questions
- Fan-out on write or on read? Write for most users, because reads outnumber posts about 30 to 1 and a read becomes one lookup. Read for accounts with huge follower counts, where the push cost is too high. This hybrid is the expected answer.
- How do you handle a celebrity? Skip the push. At read time, add the latest posts of the celebrities the user follows. Those posts are hot in the cache.
- What do you store in the timeline? Only post IDs, in a Redis sorted set per user, capped at about 300. Bodies are fetched by ID, so a post is stored once, not 200 times.
- How do you paginate? With a cursor, the ID of the last post seen. Page numbers shift as new posts arrive.
- How do you handle deletes and unfollows? Delete from the posts store and filter at read time. Do not edit every timeline.
- What if the timeline cache is lost? It is only a cache. Rebuild it from the graph and the posts store, by pulling.
- How does LinkedIn differ? Two-way connections, a ranked feed by default, and posts that stay relevant for days. The same pieces are used, with more effort on ranking.