Skip to content

Lesson 25 of 38Case studies

Design a News Feed

Design a social feed with fan-out on write, fan-out on read, and the hybrid that handles celebrities, plus ranking and cursors.

20 min read0/4 questions

Open any social app and the first thing you see is a feed: posts from people you follow, ranked, endless, loaded in a few hundred milliseconds. Building it is one of the most asked system design questions because it forces a real tradeoff: do the work when someone posts, or when someone reads? There is no free answer, and the best systems do both.

Requirements

Functional

  • A user can publish a post (text plus optional photos or video).
  • A user sees a home feed of posts from people they follow, newest or best first.
  • The feed scrolls: load 20 posts, then the next 20, and so on.

Non-functional

  • Feed loads in under 300 ms at the 99th percentile.
  • A new post appears in followers' feeds within a few seconds (it does not need to be instant).
  • Availability over consistency: showing a slightly stale feed is fine; showing an error is not.

Out of scope: comments and likes storage (assume a separate service), ads, notifications, the follow and unfollow flow itself.

Back-of-the-envelope numbers

QuantityAssumption and mathResult
Daily active users300 million
New posts10% of users post once a day: 30M / 86,400about 350/s (peak 1,000/s)
Feed reads10 feed opens per user per day: 3B / 86,400about 35,000/s (peak 100,000/s)
Average followers300 (some have 100 million)
Fan-out writes30M posts × 300 followers / 86,400about 100,000 feed inserts/s
Feed cache500 post IDs × 8 bytes × 300M usersabout 1.2 TB of Redis

Reads outnumber posts 100 to 1. That ratio is why the classic design does extra work at post time to make reads cheap.

API

POST /v1/posts
{ "text": "Ship day!", "media_ids": ["m_19ac"] }
201 Created  { "post_id": "p_8812", "created_at": "2026-10-20T09:14:02Z" }
 
GET /v1/feed?limit=20&cursor=eyJ0cyI6IjIwMjYtMTAtMjBUMDk6MTQ6MDJaIiwiaWQiOiJwXzg4MTIifQ
200 OK
{ "posts": [ { "post_id": "p_8812", "author": {...}, "text": "Ship day!", "media": [...] }, ... ],
  "next_cursor": "eyJ0cyI6..." }

Media is uploaded first (POST /v1/media returns a presigned upload URL), so the post itself stays a tiny JSON request.

Data model

  • posts: post_id (time-sortable ID, like a Snowflake ID that starts with a timestamp), author_id, text, media_keys, created_at. Sharded by post_id. Index on (author_id, created_at) for "this author's recent posts".
  • follows: (follower_id, followee_id) with indexes both ways. This is the social graph.
  • feed cache: in Redis, one list per user: feed:{user_id} holds the newest ~500 post IDs. Only IDs, not post bodies, so a viral post edited once is fixed everywhere.
  • media: photos and videos in object storage (S3), served through a CDN.

High-level design

Step through publishing a post, then reading the feed.

News feed architecture
Write pathMediaAppAppAPI gatewayAPI gatewayPost svcPost svcPosts: DB + cachePostsDB + cacheFan-out: KafkaFan-outKafkaFan-out: workersFan-outworkersFollow graphFollow graphFeed svc: merge + rankFeed svcmerge + rankFeed cache: Redis listsFeed cacheRedis listsCDNCDNMedia: S3MediaS3HTTPSINSERTpublishfollowersLPUSHLRANGEhydrateuploadimagesorigin

Posting. The photo goes straight to S3 with a presigned URL. Our servers never handle the big bytes.

1/8

Deep dive 1: push, pull, or both?

Fan-out on write (push). When Ada posts, copy her post ID into every follower's feed list right away. Reads are trivial: just read your list. Cost: one post with 300 followers is 300 writes, and a post by an account with 100 million followers is 100 million writes. That single post would take minutes to deliver and swamp the workers.

Fan-out on read (pull). Store nothing per user. At read time, look up everyone you follow, fetch their recent posts, and merge. Posting is one write. Cost: every feed open queries hundreds of authors, 35,000 times a second. Slow and expensive.

Hybrid. Push for normal accounts, pull for celebrities (accounts above some follower threshold, say 100,000). At read time, take your pre-built list and merge in recent posts from the handful of celebrities you follow. Both sides stay cheap.

Watch the feed cache fill as Ada (300 followers) posts, and see what happens with a celebrity.

Feed cache: one list per user
  1. 0empty
  2. 1empty
  3. 2"feed:leo":"[p40, p31]"
  4. 3"feed:sam":"[p31, p12]""feed:priya":"[p12]"

Each user's feed is a Redis list of post IDs, newest first. Redis Cluster spreads the keys across nodes.

1/4
Quick check
An account with 80 million followers posts. With pure fan-out on write, what goes wrong?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/4 matched

Match the model to its tradeoff.

Choose an item, then its match on the other side.

Deep dive 2: ranking

A pure newest-first feed is simple and predictable. Most products rank instead. The feed service takes a few hundred candidate posts and scores each one using signals:

  • Affinity: how often you interact with this author.
  • Engagement: likes and comments the post has received, especially early.
  • Recency: newer is better; the score decays over time.
  • Type: you may engage more with photos than links.

Real systems learn the weights with machine learning. A hand-written version teaches the shape. Change the weights and see the order change.

Pythonrank_feed.py
import math posts = [ {"id": "p1", "author": "ada", "age_h": 1, "likes": 4, "comments": 0, "affinity": 0.9}, {"id": "p2", "author": "sam", "age_h": 6, "likes": 900, "comments": 120, "affinity": 0.1}, {"id": "p3", "author": "leo", "age_h": 30, "likes": 50, "comments": 8, "affinity": 0.7}, {"id": "p4", "author": "news", "age_h": 2, "likes": 40, "comments": 2, "affinity": 0.2},] def score(p, half_life_h=12): engagement = math.log10(1 + p["likes"] + 3 * p["comments"]) decay = 0.5 ** (p["age_h"] / half_life_h) return (1 + 2 * p["affinity"]) * (1 + engagement) * decay for p in sorted(posts, key=score, reverse=True): print(f'{p["id"]} {p["author"]:5} score={score(p):.2f}')
Output
Press Run (⌘ Enter) to see what happens.

The log10 stops a post with 10,000 likes from being 100 times more important than one with 100. The half-life means a post loses half its score every 12 hours.

Quick check
Ranking uses live like counts. Should the feed service cache the ranked feed per user?
Need a nudge? A hint rules out a wrong answer.

Deep dive 3: pagination with cursors

With offset pagination (?page=3), new posts arriving at the top shift everything down, and the user sees duplicates when loading the next page. Feeds use a cursor: an opaque token that says "continue after this exact post". The server encodes the last item's sort key, and the next request asks for items strictly after it.

TypeScriptcursor.ts
type Post = { id: string; ts: number }; // Newest first. ts ties are broken by id so the order is total.const feed: Post[] = [ { id: "p9", ts: 900 }, { id: "p8", ts: 800 }, { id: "p7", ts: 800 }, { id: "p5", ts: 500 }, { id: "p3", ts: 300 }, { id: "p1", ts: 100 },]; const encode = (p: Post) => btoa(JSON.stringify({ ts: p.ts, id: p.id }));const decode = (c: string): Post => JSON.parse(atob(c)); function page(items: Post[], limit: number, cursor?: string) { const after = cursor ? decode(cursor) : null; const rest = after ? items.filter((p) => p.ts < after.ts || (p.ts === after.ts && p.id < after.id)) : items; const posts = rest.slice(0, limit); const last = posts[posts.length - 1]; return { posts: posts.map((p) => p.id), next: posts.length === limit ? encode(last) : null };} const first = page(feed, 2);console.log(first.posts, first.next);feed.unshift({ id: "p10", ts: 1000 }); // a new post arrives while the user scrollsconst second = page(feed, 2, first.next!);console.log(second.posts, "(no duplicates, even after p10 arrived)");
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

What does this print?

const ids = [50, 40, 30, 20, 10]; // newest first
const after = 30;
console.log(ids.filter((x) => x < after).slice(0, 2).join(","));
Need a nudge? Hints walk you through it.

Bottlenecks, failures, and 10x scale

  • Feed cache loss. If a Redis shard dies, those users' feeds are rebuilt by pulling (slower for a moment, never wrong). Replicas make it rare.
  • Fan-out lag. Monitor queue depth. Prioritise fan-out for active users and process celebrity-adjacent spikes in a separate queue.
  • Hot posts. A viral post is hydrated millions of times. The post cache, plus in-process caches in the feed service, absorb it.
  • Deletes. Deleting a post does not walk 300 feeds. Hydration skips IDs whose post is marked deleted.
  • 10x (3 billion feed reads an hour): more Redis shards for the feed cache, more fan-out workers (they scale horizontally with Kafka partitions), lower the celebrity threshold so fewer pushes happen, and move ranking to a dedicated service with precomputed features.
Key terms
fan-out on write
Copy a new post's ID into every follower's feed when it is published. Fast reads, costly posts.
fan-out on read
Build the feed at read time by merging recent posts from everyone you follow. Cheap posts, costly reads.
celebrity problem
Accounts with millions of followers make push fan-out too slow, so their posts are pulled at read time.
hydration
Turning a list of IDs into full objects by batch-fetching them from a cache or database.
cursor pagination
Pages continue after an encoded sort key instead of an offset, so new items do not cause duplicates.