Design Problem: A News Feed, Push vs Pull, and the Celebrity Problem
System Design series · Part 9 Design problems (2 of 7)
- Design Problem: A URL Shortener, from Estimates and Code Generation to Phishing Abuse
- Design Problem: A News Feed, Push vs Pull, and the Celebrity Problem
- Design Problem: A Chat System, Where Direct Messages and a 50,000-Person Live Chat Room Are Two Different Problems
- Design Problem: Flash Sale Ticketing, and How Much Each Layer Must Turn Away When 500,000 People Chase 10,000 Seats
- Design Problem: A Notification System Where Verification Codes Cannot Wait Behind 10 Million Newsletters
- Design Problem: A Leaderboard, with Ranks for Ten Million Members, Who Comes First in a Tie, and Time Decay for Trending Talks
- Design Problem: A Distributed Scheduler, Where a Million Delayed Tasks Must Each Run Only Once, at the Right Time
System Design series Part 9-2 | Previous: URL Shortener | Next: Chat System | Series map
Scenario and problem
Members can follow speakers and organizers. The feed on the home page shows new posts from everyone they follow, in time order: a newly opened talk, a short post from a speaker, a talk recording going online.
Functional requirements
- A speaker publishes a post; followers see it in their feed, newest first
- Scrolling down keeps loading older posts
- After a speaker deletes a post or changes it to “paid members only”, people who are not allowed to see it must no longer see it
- After a member unfollows a speaker, they no longer see that speaker’s new posts
Non-functional requirements
- p99 for opening the feed under 200 milliseconds
- A new post shows up in followers’ feeds within a few seconds to a minute; real time is not required
- A few speakers have more than a million followers
Scale estimate
| Item | Estimate |
|---|---|
| Members | 10 million monthly active, 2 million daily active |
| Follow relationships | Each member follows 50 speakers on average → 500 million follow relationships |
| Speakers | 100,000 active speakers with about 5,000 followers each on average; the distribution is extremely uneven, and the most-followed has about 3 million |
| Publishing | 200,000 posts a day → 2.3 a second on average, about 20 at peak |
| Reads | Each daily active member opens the feed 10 times a day → 20 million a day, about 230 a second on average, about 1,200 at peak |
- Publish a postA speaker publishes a post, and followers see it in their feed, newest first. 200,000 posts a day, 2.3 a second on average; a speaker has about 5,000 followers on average.
- Open the feedEach daily active member opens the feed 10 times a day, about 1,200 times a second at peak, and p99 has to stay under 200 milliseconds.
- 3 million followersFollowers are extremely unevenly distributed, and the most-followed speaker has about 3 million. Reads outnumber posts 100 to 1, but what matters is how many people each post has to notify.
- Deleted or made paid-onlyAfter a speaker deletes a post or changes it to "paid members only", a post already delivered to feeds must no longer be shown to people who are not allowed to see it.
Reads outnumber posts 100 to 1, but the number of people each post has to notify is what matters.
The simplest approach and its limits
Query directly at read time:
SELECT p.* FROM post p
JOIN follow f ON f.followee_id = p.author_id
WHERE f.follower_id = :me
ORDER BY p.created_at DESC
LIMIT 20;When you follow 50 people, this query has to merge and sort the posts of 50 speakers. Once the post table grows to hundreds of millions of rows and gets sharded (Sharding post), the 50 speakers’ data is spread over different shards, and every time you open the feed you query across shards and merge the results. 1,200 reads a second times 50 speakers is 60,000 queries a second against the post table.
Core mechanism
Fan-out on write and fan-out on read
| Strategy | How | Read cost | Write cost |
|---|---|---|---|
| Fan-out on write (push) | On publish, write the post ID into every follower’s timeline | Read one precomputed list, which is cheap | One post is written “number of followers” times |
| Fan-out on read (pull) | At read time, fetch the latest posts from each account you follow and merge them | Every read queries “number of accounts followed” times and merges | Publishing writes once |
Estimate the cost of push with the talk platform’s numbers: 200,000 posts a day × 5,000 followers on average = 1 billion timeline writes a day, about 12,000 a second on average. That is manageable, but the problem is the tail of the distribution: one post from a speaker with 3 million followers means 3 million writes. At 50,000 writes a second, the fan-out takes a minute to finish. During that minute the fan-out work takes up all the resources, and other speakers’ posts are delayed along with it.
Hybrid strategy: push for regular speakers, pull for celebrities
- Regular speakers (fewer than 10,000 followers): fan out to followers’ timelines on publish
- Celebrity speakers (more than 10,000 followers): no fan-out, write only to their own post list. When reading the feed, pull the latest posts of “the celebrities I follow” and merge them with the precomputed timeline
A member usually follows only a few celebrities, so a few extra queries at read time are acceptable, and the few most expensive fan-outs disappear completely.
Add one simple optimization: fan out only to active members. If only half of the 10 million monthly active members have logged in within the last 7 days, fan-out writes drop by half. When an inactive member comes back, rebuild their timeline with fan-out on read.
What the timeline stores, and how much
A timeline stores only post IDs and times, not content. The content is fetched in batches at read time (hydration), because:
- When a post is edited or deleted, only one place changes
- Visibility has to be rechecked at read time (explained below)
- The timeline uses far less memory
Each timeline keeps only the latest 120 posts: members rarely scroll past a few dozen, and older posts come from fan-out on read. The cap is deliberately below Redis’s zset-max-listpack-entries (default 128): up to that count, a sorted set uses the compact listpack encoding; past it, it switches to a skiplist, and each member takes several times more memory. 2 million active members with 120 posts each comes to roughly 10 GB (depending on the Redis version and member length), so a small Redis Cluster is enough. The timeline is a cache you can rebuild: if it is lost, regenerate it from the post table and the follow relationships.
Paginate with a cursor, not page numbers
New posts keep arriving at the top of the feed. With page-number pagination (OFFSET 20), if 5 new posts come in while the user is reading the first page, the second page repeats the last 5 posts of the first page (keyset pagination in the Indexes and B+Trees post).
The cursor records “the time and ID of the last post on the previous page”, and the next page continues after it. There is an implementation trap here: a Redis sorted set score is a 64-bit floating-point number, which can only represent integers up to 2⁵³ exactly. 64-bit IDs such as Snowflake IDs go beyond that range (Distributed IDs post), so using them directly as scores loses precision, and neighboring IDs end up with the same score. So the score is a millisecond timestamp, the member is the post ID, and the cursor carries both.
Check visibility at read time
Fan-out writes the posts that “could be seen at that moment”, and things can change afterwards:
- The speaker deletes the post, or changes it to “paid members only”
- The member unfollows, or is blocked by the speaker
- The speaker’s account is suspended
If the feed shows every ID in the timeline as is, these posts that should no longer be visible still appear. So hydration must recheck the status and visibility of every post. This is the feed’s version of “every read path needs the same conditions” from the Authorization post. When too many posts are filtered out (for example after you unfollow a speaker who posts a lot), fetch more to fill the page.
The fan-out flow
flowchart LR
W[Speaker publishes] --> DB[(Post table)]
DB -->|outbox| K[[Kafka<br/>post-created]]
K --> F[Fan-out worker]
F -->|read active followers in batches| G[(Follow relationships)]
F -->|pipelined writes| T[(Redis<br/>per-member timelines)]
R[Feed API] --> T
R -->|celebrity posts| C[(Celebrity post lists)]
R -->|fetch content in batches and check visibility| P[(Post cache / post table)]
- Publishing and fan-out are separate: publishing only writes the post table and the outbox (Sagas and the Outbox Pattern post), and fan-out runs in the background
- Fan-out is idempotent by nature: adding the same ID to a sorted set twice gives the same result, so at-least-once delivery needs no extra deduplication (Idempotency post)
- The fan-out of one post is split into batches (1,000 followers each), so fan-outs for different speakers can interleave and a celebrity’s large batches do not keep one consumer busy
Comparing options
| Decision | Choice | Rejected alternatives and why |
|---|---|---|
| Fan-out strategy | Push for regular speakers, pull for celebrities, push only to active members | Push for everyone: celebrities cause write spikes; pull for everyone: read cost and latency are too high |
| Timeline | Redis sorted set, IDs and times only, capped at 120 posts | Store the full content: a lot of memory, and edits and deletes are hard to keep in sync |
| Pagination | Cursor of timestamp plus ID | Page numbers: newly inserted posts cause duplicates and gaps |
| Visibility | Recheck at read time | Decide at fan-out: later deletes, blocks, and permission changes are never reflected |
| Ordering | By time | Ranking by predicted engagement: needs candidate generation and a scoring model, not needed in the first version |
Tune the celebrity threshold (10,000) to the actual fan-out delay: the lower the threshold, the more celebrities to merge at read time; the higher the threshold, the bigger the fan-out spikes.
In Java
1. The fan-out worker
@Component
public class FanOutWorker {
private static final int CELEBRITY_THRESHOLD = 10_000;
private static final int BATCH = 1_000;
private static final int TIMELINE_CAP = 120;
private final JdbcClient jdbc;
private final StringRedisTemplate redis;
public FanOutWorker(JdbcClient jdbc, StringRedisTemplate redis) {
this.jdbc = jdbc;
this.redis = redis;
}
@KafkaListener(topics = "post-created", groupId = "feed-fanout")
public void onPostCreated(PostCreated event) {
if (event.authorFollowerCount() >= CELEBRITY_THRESHOLD) {
return; // celebrity: merged at read time
}
long lastFollowerId = 0;
while (true) {
List<Long> followers = jdbc.sql("""
SELECT f.follower_id FROM follow f
JOIN member_activity a ON a.member_id = f.follower_id
WHERE f.followee_id = :author AND f.follower_id > :last
AND a.last_seen_at > NOW() - INTERVAL 7 DAY
ORDER BY f.follower_id
LIMIT :batch
""")
.param("author", event.authorId())
.param("last", lastFollowerId)
.param("batch", BATCH)
.query(Long.class)
.list();
if (followers.isEmpty()) {
return;
}
pushToTimelines(followers, event.postId(), event.createdAtMillis());
lastFollowerId = followers.getLast();
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
private void pushToTimelines(List<Long> followers, long postId, long createdAtMillis) {
String member = Long.toString(postId);
redis.executePipelined(new SessionCallback<Object>() {
@Override
public Object execute(RedisOperations operations) {
for (Long follower : followers) {
String key = "timeline:" + follower;
operations.opsForZSet().add(key, member, createdAtMillis); // adding it again gives the same result
operations.opsForZSet().removeRange(key, 0, -(TIMELINE_CAP + 1)); // keep only the latest 120
}
return null;
}
});
}
}- Followers are read with keyset pagination (
follower_id > :last), which needs an index on(followee_id, follower_id) - The celebrity check uses the follower count carried in the event, so it is not computed every time
- If writing one batch fails, the whole event is redelivered; writing again to timelines that already have the post does no harm
2. Reading the feed
public record FeedCursor(long millis, long postId) {
}
@Service
public class FeedService {
private static final int PAGE = 20;
private final StringRedisTemplate redis;
private final CelebrityPosts celebrityPosts;
private final PostHydrator hydrator;
public FeedService(StringRedisTemplate redis, CelebrityPosts celebrityPosts, PostHydrator hydrator) {
this.redis = redis;
this.celebrityPosts = celebrityPosts;
this.hydrator = hydrator;
}
public FeedPage read(long memberId, FeedCursor cursor) {
double max = cursor == null ? Double.POSITIVE_INFINITY : cursor.millis();
// Fetch extra: posts in the same millisecond, and posts the visibility check filters out
Set<ZSetOperations.TypedTuple<String>> pushed = redis.opsForZSet()
.reverseRangeByScoreWithScores("timeline:" + memberId, Double.NEGATIVE_INFINITY, max, 0, PAGE * 2);
List<FeedEntry> candidates = new ArrayList<>();
for (ZSetOperations.TypedTuple<String> t : pushed) {
candidates.add(new FeedEntry(Long.parseLong(t.getValue()), t.getScore().longValue()));
}
candidates.addAll(celebrityPosts.latestOfFollowedCelebrities(memberId, cursor, PAGE * 2));
List<FeedEntry> page = candidates.stream()
.filter(e -> cursor == null || e.isBefore(cursor)) // drop what was already seen before the cursor
.distinct()
.sorted(Comparator.comparingLong(FeedEntry::millis).thenComparingLong(FeedEntry::postId).reversed())
.toList();
// Fetch the content in a batch and recheck: deleted? still visible? still followed? blocked?
List<PostView> visible = hydrator.hydrateVisible(memberId, page, PAGE);
FeedCursor next = visible.isEmpty() ? null
: new FeedCursor(visible.getLast().createdAtMillis(), visible.getLast().postId());
return new FeedPage(visible, next);
}
}FeedEntry.isBefore(cursor)compares the (time, ID) pair, so posts in the same millisecond are neither duplicated nor missed- When the timeline does not exist (an inactive member, Redis data lost), rebuild it with fan-out on read before calling
PostHydrator - Before returning the cursor to the client, you can sign or encrypt it so a client cannot tamper with it and cause strange queries; the cursor itself must never contain any authorization information
The code above is written from the official documentation for Spring Boot 4.1, Spring Data Redis 4.1, and Spring for Apache Kafka, and has not been compiled or run.
CelebrityPostsandPostHydratorare illustrative components.
Pitfalls and gotchas
- Snowflake IDs as sorted set scores: past 2⁵³ they lose precision, and ordering and pagination go wrong
- Page-number pagination: duplicates or gaps when new posts are inserted
- Deciding visibility at fan-out time: deletes and permission changes are never reflected
- A celebrity’s fan-out blocks the whole queue: one post is written 3 million times, and every speaker’s post behind it waits in line. Exclude celebrities with a threshold, and split fan-out into small batches
- Fanning out to everyone: most of the writes go to members who will never come back
- A popular celebrity’s post list becomes a hot spot: every follower reads the same key at read time. Cache this key in application memory for a few seconds, or keep several copies of it (hot keys in the Caching post)
- Leftovers after unfollowing: the timeline still holds old post IDs. Filter them at read time, or clean them up asynchronously when the member unfollows
Threat model
| STRIDE | Threat | On the talk platform | Defense |
|---|---|---|---|
| Spoofing | Posting as a speaker | The posting API uses the authorId from the request |
Always take the author from the verified identity (8-2) |
| Tampering | Editing someone else’s posts | The edit API only checks that you are logged in | Object-level authorization; keep an edit history |
| Repudiation | A speaker denies having published some content | Disputed content cannot be traced after it is edited or deleted | Keep post versions and deletion records for a period |
| Information disclosure | Seeing deleted or paid-members-only posts; seeing someone else’s feed | Old IDs in the timeline are not rechecked; GET /feed?memberId=123 |
Check visibility at read time; the feed reads only your own, with memberId taken from the token |
| Denial of service | Fan-out storms; mass following | Fake accounts post in bulk to trigger fan-out; one account follows hundreds of thousands of speakers, and the merge cost at read time explodes | Rate and count limits on posting and following; the celebrity threshold (8-5) |
| Elevation of privilege | Stored XSS; SSRF through link previews | A script in a post runs in every follower’s browser and takes over their sessions | Context-aware escaping on output; CSP; SSRF protection for previews |
A feed puts one piece of content in front of thousands of people, so the blast radius of stored XSS grows with the follower count. With a BFF the token is not in the browser (8-1), but the attacker’s script can still send requests as the victim, for example making everyone who sees the post follow some account automatically.
When to use it, and when not to
- Fan-out on read only: few users and few follows, or all the data in one database with queries that are fast enough. This is the simplest starting point
- Add fan-out on write: heavy reads, strict read latency requirements, and most authors have a moderate number of followers
- Hybrid strategy: when follower counts are extremely uneven and the celebrity problem shows up
- Ranking by engagement: only when there are so many posts that ordering by time buries the important content is a ranking model worth bringing in, along with the complexity it adds
References
- Martin Kleppmann, Designing Data-Intensive Applications, O’Reilly, 2017, Chapter 1 “Describing Load” (uses Twitter’s timeline to explain the fan-out trade-off)
- Raffi Krikorian, “Timelines at Scale”, QCon San Francisco, 2012
- Redis Documentation — Sorted sets: https://redis.io/docs/latest/develop/data-types/sorted-sets/
- Spring Data Redis Reference — Pipelining: https://docs.spring.io/spring-data/redis/reference/redis/pipelining.html
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments