A news feed is the scrolling home screen of Twitter/X, Instagram, Facebook or LinkedIn: a personalized, constantly updating list of posts from the people you follow (and, increasingly, from people you don't). Opening it must feel instant even though the content comes from hundreds of authors. The core design question is when to assemble each person's feed: at write time (push every new post into followers' timelines) or at read time (pull recent posts from everyone you follow). Real systems use a hybrid, and the reason is the celebrity problem.
Think of it like
Personal newspapers
Imagine a print shop that makes a custom newspaper for every subscriber. Option one: every time a columnist files a story, clerks immediately slip a copy into the mailbox of each of that columnist's readers, so a subscriber's paper is already assembled when they wake up (push). Option two: the subscriber walks to the newsstand each morning and collects the latest page from each of their 300 favorite columnists (pull). Push makes mornings fast, until a superstar columnist with 50 million readers files a story and the clerks spend all day stuffing mailboxes. The smart shop pushes ordinary columnists and lets readers pick up the superstars' pages themselves.
1. Requirements
Functional
- Publish a post (text, plus optional images or video)
- Follow and unfollow other users (one-directional, like Twitter or Instagram)
- Read a home feed of posts from followed accounts, newest or most relevant first
- Infinite scroll: page through the feed without duplicates or gaps
- Like and comment counts shown on each post
Non-functional
- Feed loads fast: p99 under ~200 ms for the first page
- Very read-heavy: dozens of feed reads per post written
- Highly available; a slightly stale feed is acceptable (eventual consistency)
- A new post appears in followers' feeds within seconds, not minutes
- Must handle accounts with 100M+ followers without melting down
| In scope | Out of scope (mention, then park) |
|---|---|
| Posting, following, home feed generation | Search, trends and hashtags (see Search Systems) |
| Fan-out strategy and the celebrity problem | Direct messages (see Design a Chat System) |
| Timeline cache, ranking (high level), pagination | Ads auction and insertion |
| Media upload and delivery | Content moderation pipelines and spam models |
| Engagement counters | Push notifications for new posts (see Design a Notification System) |
2. Back-of-the-envelope estimation
Assume 300 million daily active users. Each opens the feed about 10 times a day, and on average users publish 150 million posts per day in total. The average user has 200 followers, but the distribution is extremely skewed: a few thousand accounts have tens of millions. See Back-of-the-Envelope Estimation for the technique.
Feed reads
~35k /s
peaks near 100k/s
Fan-out inserts
~350k /s
200 × the post rate
Post metadata
~55 TB /yr
150M × 1 KB × 365
Media
~11 PB /yr
20% of posts × ~1 MB
3. API design
# 1. Get an upload slot for media (bytes go straight to object storage)
POST /v1/media
{ "contentType": "image/jpeg", "sizeBytes": 2483021 }
-> 201 Created { "mediaId": "m_9f2", "uploadUrl": "https://upload.example.com/...signed..." }
# 2. Publish a post
POST /v1/posts
Idempotency-Key: 5b1c-77e0
{ "text": "Launch day!", "mediaIds": ["m_9f2"] }
-> 201 Created { "postId": "1790412261185372160", "createdAt": "2026-11-06T09:12:44Z" }
# 3. Read the home feed (cursor pagination)
GET /v1/feed?limit=20
GET /v1/feed?limit=20&cursor=eyJ0cyI6MTc2MjQyMDM2NDAwMCwiaWQiOiIxNzkwNDEyMjYxMTg1MzcyMTYwIn0
-> 200 OK { "items": [ { "postId": "...", "author": {...}, "text": "...", "media": [...], "likes": 1203 } ],
"nextCursor": "eyJ0cyI6..." }
# 4. Follow graph
PUT /v1/users/me/following/u_42
DELETE /v1/users/me/following/u_42- Cursor, not page number. The feed changes while you scroll; an opaque cursor marks a position in the ordering so new posts never shift what the next page returns (deep dive in section 9).
- Idempotency-Key on writes. Mobile clients retry on flaky networks; without the key a retry creates a duplicate post. See Idempotency & Delivery Guarantees.
- Hydrated responses. The feed endpoint returns full post objects (author, text, media URLs, counts) so the app renders a page with one request. See API Design: REST, GraphQL & gRPC.
4. Data model
| Data | Key and access pattern | Store | Why |
|---|---|---|---|
| Posts | post_id (Snowflake, time-ordered); point reads in bulk | Sharded MySQL/Postgres or Cassandra | Immutable-ish rows, huge volume, lookups by ID only |
| Follow graph | (follower_id, followee_id) stored twice: followers-of and following-of | Sharded relational or a graph service | Fan-out needs 'who follows X'; reads need 'whom does Y follow' |
| Home timelines | timeline:{user_id} → newest ~800 post IDs | Redis sorted sets (in memory) | Read on every feed open; must be sub-millisecond |
| Author outboxes | outbox:{author_id} → recent post IDs | Redis sorted sets | Pull path for celebrities and timeline rebuilds |
| Engagement counts | post_id → likes, replies, reposts | Sharded counters (Redis) + periodic flush | Very hot writes on viral posts |
| Media | media_id → object key, variants, status | Object storage + metadata table, served by CDN | Large immutable blobs. See Blob & Object Storage |
CREATE TABLE posts (
post_id BIGINT PRIMARY KEY, -- Snowflake: timestamp | worker | sequence
author_id BIGINT NOT NULL,
body VARCHAR(2000),
media_ids JSON,
visibility SMALLINT NOT NULL DEFAULT 0,
deleted_at TIMESTAMP NULL, -- soft delete: filtered out at hydration
created_at TIMESTAMP NOT NULL
);
CREATE INDEX posts_by_author ON posts (author_id, post_id DESC); -- outbox rebuilds
-- The graph is written twice, partitioned differently for each direction.
CREATE TABLE followers ( -- sharded by followee_id: "who follows X?" (fan-out)
followee_id BIGINT, follower_id BIGINT, created_at TIMESTAMP,
PRIMARY KEY (followee_id, follower_id)
);
CREATE TABLE following ( -- sharded by follower_id: "whom does Y follow?" (reads)
follower_id BIGINT, followee_id BIGINT, created_at TIMESTAMP,
PRIMARY KEY (follower_id, followee_id)
);5. High-level architecture
The write path and the read path are separate services. Publishing stores the post and emits an event; fan-out workers consume that event asynchronously and insert the post ID into each follower's cached timeline. Reading the feed is then mostly a cache read plus hydration (turning IDs into full posts). Press play on a flow to follow a request.
6. Deep dive: fan-out on write vs fan-out on read
This is the heart of the interview. There are two pure strategies and a hybrid. The trade-off is where you pay: on every post (write amplification) or on every feed open (read amplification).
Fan-out on write (push)
- On publish, insert the post ID into every follower's timeline
- Feed reads are a single cache read: very fast and predictable
- Write cost is proportional to follower count (1 to 100M+)
- Wastes work on followers who never log in
- Unfollow, delete or block must be cleaned up or filtered later
Fan-out on read (pull)
- On read, fetch recent posts from every followed account and merge
- Writes are trivial: append to the author's outbox
- Read cost is proportional to how many accounts you follow
- Slow and expensive at 35k reads/s × hundreds of authors
- Always fresh; nothing to clean up after unfollow
Hybrid (what real systems do)
- Push for ordinary authors (the vast majority of posts)
- Pull for celebrities above a follower threshold
- Skip fan-out to inactive users; rebuild their timeline on login
- Reads merge a precomputed list with a handful of outboxes
- Bounded cost on both sides
The celebrity problem in numbers
Suppose fan-out workers sustain 1 million timeline inserts per second in total. A post from an account with 100 million followers would occupy the entire fleet for 100 seconds, delaying every other post in the queue behind it. If that account posts five times during a live event, ordinary users' posts arrive minutes late. Pull costs grow the other way: someone following 2,000 accounts would need 2,000 outbox reads per feed open.
| Author type | Followers | Push cost per post | Strategy |
|---|---|---|---|
| Typical user | ~200 | 200 cache writes, about 1 ms of worker time | Push |
| Popular creator | 50,000 | 50,000 writes, still fine in batches | Push |
| Celebrity | 10M–100M+ | 10–100 s of the whole fan-out fleet | Pull at read time |
| Reader following 300 accounts, 5 of them celebrities | n/a | Read: 1 timeline + 5 outboxes | Merge on read |
- 1
Classify the author
Cache each account's follower count. Above the threshold, the post goes only to the author's outbox; below it, fan-out proceeds.
- 2
Push in batches
Page through followers in chunks of ~1,000 and pipeline the cache writes. Split very large fan-outs into many Kafka messages (one per follower range) so several workers share the job.
- 3
Skip the inactive
Only users active in the last few weeks keep a cached timeline. That can cut fan-out work dramatically because many registered users rarely open the app.
- 4
Merge on read
The Feed service reads the user's precomputed timeline plus the outboxes of the celebrities they follow (a short list cached with the user's profile), then merges by time or hands the union to the ranker.
- 5
Rebuild on demand
A returning inactive user has no cached timeline. Build it once by pulling from every followed account (fan-out on read), cache it, and push to it from then on.
7. Deep dive: the timeline cache
The timeline cache is the most important component on the read path. It stores only IDs: a post ID and an author ID per entry, so a timeline of 800 entries is about 13 KB. The posts themselves live once in the post cache. This split keeps fan-out writes tiny and means an edited or deleted post needs to change in exactly one place. See Caching.
timeline:{userId} ZSET member = postId, score = created-at millis (newest 800, active users only)
outbox:{authorId} ZSET member = postId, score = created-at millis (newest 800 per author)
post:{postId} HASH author, body, media, created_at (hydration cache, LRU)
user:{userId} HASH name, avatar, celebFollowees[] (profile + who to pull)
likes:{postId} STRING counter (sharded for viral posts)
ZADD timeline:42 1762420364000 1790412261185372160
ZREMRANGEBYRANK timeline:42 0 -801 # keep the newest 800
ZRANGE timeline:42 +inf -inf BYSCORE REV LIMIT 0 20 # newest page- Partitioning: shard by
user_idwith Consistent Hashing, so each timeline lives on one node and a read is one round trip. - Replication: keep 2–3 replicas per shard. Losing a node should cost latency (rebuilds), not availability. See Database Replication.
- Memory budget: only active users are cached. At ~11.5 TB including replicas, this is a large but ordinary Redis or Memcached fleet.
- Cold start: if a timeline is missing (new user, inactive user, lost node), build it from the user's following list and the authors' outboxes, then cache it. This is fan-out on read used as a repair path.
- Hot celebrity outboxes: millions of readers hit the same keys. Replicate them widely or cache them in-process on Feed service instances for a few seconds.
8. Deep dive: ranking
Chronological feeds are simple but bury posts from people you care about under high-volume accounts. Most large feeds are now ranked: Instagram moved from chronological to ranked in 2016, and Twitter introduced a ranked home timeline the same year. Ranking runs as a multi-stage funnel so that expensive models only see a few hundred candidates.
- 1
Candidate generation
Collect a few hundred to a few thousand candidates: the pushed timeline, pulled celebrity posts, and (for 'For You' feeds) posts from accounts you don't follow found by embeddings or collaborative filtering.
- 2
Lightweight filtering
Drop blocked, muted, already-seen and policy-violating posts. A cheap model may prune the list further.
- 3
Heavy ranking
A neural network predicts the probability of each action (like, reply, repost, dwell, hide) from features such as your affinity with the author, the post's early engagement, media type and recency.
- 4
Re-ranking and rules
Combine predictions into one score, then enforce diversity (no five posts in a row from one author), freshness, and business rules such as ad slots.
9. Deep dive: pagination with cursors
Offset pagination (?page=3 → OFFSET 40 LIMIT 20) breaks on a live feed. If five new posts arrive while you read page 1, everything shifts down by five, and page 2 repeats the last five posts you already saw. A cursor encodes the position of the last item you saw, so the next query asks for 'items strictly after this one' regardless of what was inserted at the top.
Offset pagination
OFFSET n LIMIT 20- Duplicates or gaps when items are inserted or deleted
- Deep pages get slower (the store skips n rows)
- Fine for static, rarely changing lists
Cursor (keyset) pagination
WHERE (ts, id) < (cursorTs, cursorId) LIMIT 20- Stable while new posts arrive at the top
- Every page costs the same, however deep
- Cursor is opaque to clients (base64 of the position)
- Chronological feeds: the cursor is
(timestamp, post_id)of the last item. It works across merged sources (timeline and outboxes) because it is a position in one global order. - Ranked feeds: scores change between requests, so a score is a poor cursor. Instead, rank once per session, store the ordered list of IDs for a few minutes (keyed by a session ID), and make the cursor an index into that snapshot.
- New posts at the top: handled separately. The client polls with a 'newer than' cursor (or gets a push hint) and shows a 'New posts' pill rather than shifting the list under the reader's thumb.
10. Deep dive: media
Media dominates bytes (about 11 PB a year in our estimate versus 55 TB of post metadata), so it never flows through the API servers. Clients upload straight to object storage with a pre-signed URL, a processing pipeline creates resized variants, and a CDN serves them. Video gets the full transcoding treatment described in Design a Video Streaming Platform.
11. Scaling, bottlenecks and failures
| Problem | What happens | Mitigation |
|---|---|---|
| Viral post | Millions read and like one post; one cache key and one counter row get hammered | Replicate hot keys, cache in-process for seconds, shard the like counter into N sub-counters and sum on read |
| Fan-out backlog during a big event | Kafka lag grows; posts reach timelines minutes late | Autoscale workers on lag; prioritize active and recently active users; raise the celebrity threshold dynamically |
| Timeline cache node lost | Affected users get cache misses | Replicas take over; rebuild missing timelines lazily with fan-out on read |
| Deleted post or unfollow | Stale IDs remain in thousands of timelines | Filter at hydration (tombstones, block lists); clean up lazily rather than fanning out deletes |
| Graph shard for a celebrity | Paging 100M follower rows is slow | Celebrities are pull-only, so their follower list is rarely scanned in full |
| Region outage | Users in that region lose the feed | Active-active regions with replicated posts and graph; timelines are a cache and can be rebuilt per region |
- Stateless services: Post, Feed and fan-out services scale horizontally behind Load Balancing; all state is in the stores.
- Rate limiting on posting and following stops spam accounts from creating fan-out storms. See Rate Limiting.
- Graceful degradation: if the ranker is slow or down, fall back to the chronological merge rather than failing the feed. See Resilience Patterns.
- Eventual consistency is acceptable: a follower seeing a post two seconds late is fine; a missing feed is not. See Consistency Models.
Implementation
Consumes `PostCreated` events. Ordinary authors are pushed into active followers' timelines in pipelined batches; celebrities only update their outbox. Sorted-set inserts make redelivery harmless.
import Redis from "ioredis";
export interface PostCreated {
postId: string; // Snowflake ID as a decimal string
authorId: string;
createdAtMs: number; // used as the sorted-set score (exact as a double)
}
export interface SocialGraph {
followerCount(userId: string): Promise<number>;
followerPages(userId: string, pageSize: number): AsyncIterable<string[]>;
}
export interface ActivityIndex {
// Keeps only users who opened the app recently (they have a cached timeline).
filterActive(userIds: string[]): Promise<string[]>;
}
const CELEBRITY_THRESHOLD = 10_000;
const TIMELINE_LENGTH = 800;
const PAGE_SIZE = 1_000;
function addCapped(pipe: ReturnType<Redis["pipeline"]>, key: string, evt: PostCreated): void {
pipe.zadd(key, evt.createdAtMs, evt.postId); // re-adding a member is a no-op
pipe.zremrangebyrank(key, 0, -(TIMELINE_LENGTH + 1)); // keep the newest 800
}
export async function fanOut(
evt: PostCreated,
graph: SocialGraph,
activity: ActivityIndex,
redis: Redis,
): Promise<void> {
// Every author has an outbox; the author also sees their own post.
const own = redis.pipeline();
addCapped(own, `outbox:${evt.authorId}`, evt);
addCapped(own, `timeline:${evt.authorId}`, evt);
await own.exec();
if ((await graph.followerCount(evt.authorId)) >= CELEBRITY_THRESHOLD) {
return; // celebrity: followers pull the outbox at read time
}
for await (const page of graph.followerPages(evt.authorId, PAGE_SIZE)) {
const active = await activity.filterActive(page);
if (active.length === 0) continue;
const pipe = redis.pipeline();
for (const userId of active) addCapped(pipe, `timeline:${userId}`, evt);
await pipe.exec();
}
}Key takeaways
- Fan-out multiplies writes by the average follower count; estimate it first, because it decides where the work goes.
- Push (fan-out on write) makes reads cheap; pull (fan-out on read) makes writes cheap. Use push for ordinary authors and pull for celebrities.
- Cache only post IDs in timelines, capped at a few hundred per active user, and hydrate full posts from a separate cache.
- Skip fan-out to inactive users and rebuild their timelines on demand; timelines are a cache, the post store is the truth.
- Paginate with opaque cursors that mark a position (timestamp and ID, or an index into a ranked snapshot), never with offsets.
- Ranking is a funnel: candidate generation, filtering, a heavy model on a few hundred items, then diversity and business rules.
Common pitfalls
- Pure fan-out on write: one celebrity post stalls the whole fan-out fleet for minutes.
- Storing full post bodies in every follower's timeline, which multiplies memory and makes edits and deletes impossible to apply.
- Offset pagination on a live feed, which shows duplicates when new posts arrive.
- Using 64-bit Snowflake IDs as Redis sorted-set scores, which silently lose precision above 2⁵³.
- Fanning out deletes and unfollows eagerly instead of filtering at hydration time.
Interview tips
- Clarify follow vs friend graphs and chronological vs ranked before drawing anything.
- Show the arithmetic: 1,750 posts/s × 200 followers = 350k timeline inserts/s, and 100M followers × 1 post is 100 seconds of the whole fleet.
- Walk through both the publish path and the read path on the diagram, then spend most of your time on the hybrid fan-out and its threshold.
- Mention the inactive-user optimization and the rebuild path: it shows you think about cost, not just correctness.
Real-world applications
- Twitter/X: its 2012-era talks described Redis clusters holding each active user's home timeline as a list of roughly 800 tweet IDs, filled by fan-out on write, with tweets from very high-follower accounts merged in at read time. Its 2023 open-source release describes a 'For You' pipeline that gathers on the order of 1,500 candidates before a neural ranker scores them.
- Facebook: has described its News Feed backend (Multifeed) as largely pull-based, with leaf servers indexing recent activity and aggregators gathering and ranking it at read time. Its early EdgeRank formula (affinity, weight, time decay) was replaced by machine-learned ranking.
- Instagram: switched its feed from reverse-chronological to ranked in 2016, and has publicly described multi-stage ranking with separate models for feed, Stories and Explore.
- LinkedIn, Pinterest and Reddit home feeds follow the same pattern: precomputed or cached candidate lists, a ranking stage, and cursor pagination.
Practice problems
Test yourself
An account with 90 million followers publishes a post. In a hybrid feed design, what happens?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.