Design a News Feed: Fan-out, Ranking and the Celebrity Problem


System Design Phase 15: Put It All Together
Advanced Lesson 84 of 86 20 min read Updated Nov 30, 2026

A footballer with 120 million followers posts a photo at 21:03, a minute after scoring. With a naive design, the system now has to write that post ID into 120 million feed lists. At a healthy 1 million feed writes per second across the whole cluster, that alone takes two minutes and crowds out everyone else’s posts. Meanwhile 8 million of those followers open the app in the next 60 seconds, each one reading the same post object, the same author profile and the same like counter, all from a single cache shard.

A news feed looks like a simple list: “show me recent posts from people I follow”. The scale and the skew make it one of the most instructive designs in the course. It touches cache patterns, hot keys, sharding, queues, cursor pagination and ranking, and every one of them has a celebrity-shaped edge case.

This walkthrough follows the system design framework: requirements, estimation, API, data model, high-level design, deep dives, then trade-offs.

Requirements

Functional

  • Users publish posts (text, optional images or video).
  • Users follow other users (asymmetric, like Instagram or X, not mutual friendship).
  • Users open a home feed of posts from accounts they follow, newest or best first, and scroll through it with infinite pagination.
  • Users like posts and see like counts.
  • Out of scope for the core design but worth naming: comments, recommendations from accounts you do not follow, ads, notifications, search.

Non-functional

  • Feed load latency: p99 under 300 ms for the first page at the API.
  • Availability: feed reads 99.95%; a stale feed is far better than an error page.
  • Freshness: a post should appear in followers’ feeds within a few seconds for normal accounts; under a minute is acceptable at peaks.
  • Consistency: eventual for feeds; read-your-writes for your own posts (you must see your post immediately); deletes and privacy changes must take effect on read, even if a stale copy sits in a cache.
  • Scale: 500 million daily active users, heavy skew in follower counts.

Estimation

Assume 500 million DAU. Each user opens the feed 10 times a day and each open loads one page of 20 posts. One in two users posts per day, so 250 million posts per day. Average follower count is 200, but a few thousand accounts have more than 10 million.

Try the numbers in the estimator: set DAU to 500M, one write per user per day as an upper bound, a read ratio around 20, and a 1 KB object for post metadata. Then compare what dominates: QPS, storage or bandwidth.

Back of the envelope estimator

Change DAU or object size and see which number becomes your real constraint.

Traffic

Storage

Bandwidth

Decimal units (1 KB = 1,000 bytes) and 86,400 seconds per day, the usual interview convention. Storage counts writes only and includes every replica; bandwidth counts payload only.

The takeaway from the numbers: reads outnumber posts 20 to 1, so precomputing feeds is attractive, but fan-out multiplies writes by the follower count, and the follower distribution is extremely skewed. Every design decision below is about that tension.

API

POST /v1/posts
  body: text, media_ids[], visibility
  returns: post_id, created_at

GET /v1/feed?limit=20&cursor=eyJzIjoxNzM...signed
  returns: items[ post_id, author, text, media_urls, like_count, liked_by_me ],
           next_cursor

POST   /v1/posts/:post_id/likes      (idempotent per user)
DELETE /v1/posts/:post_id/likes

POST   /v1/users/:user_id/follow
DELETE /v1/users/:user_id/follow

Two details matter. The feed cursor is opaque and signed, because it will encode ranking state the client must not edit. Likes are idempotent per user (a repeated POST is a no-op), so client retries are safe, a property explained in idempotency.

Data model

Store Key and shape Sharded by Why
Posts post_id (time-ordered ID), author_id, text, media refs, created_at, visibility, deleted post_id Point lookups by ID; time-ordered IDs make “recent” cheap
Author timeline author_id, created_at desc, post_id author_id “Latest posts by this author”, used for pull and for celebrities
Follows (forward) follower_id, followee_id follower_id “Who do I follow” at read time
Follows (reverse) followee_id, follower_id followee_id “Who follows me” for fan-out
Feed cache feed:user_id as a sorted set of post_id with score user_id Precomputed home feed
Likes (post_id, user_id) unique post_id Dedupe and “liked by me”
Like counters post_id, N counter shards post_id High write rate on hot posts

Post IDs come from a Snowflake-style or UUIDv7 generator so that IDs sort by time without a coordinator, covered in distributed ID generation. The follow graph is stored twice, once per direction, because each direction is a hot access path and a single table can only be partitioned one way; that is deliberate denormalization.

Posts and timelines fit a wide-column or key-value store (Cassandra, ScyllaDB, DynamoDB) or sharded Postgres or MySQL. The feed cache is Redis or Valkey; since Redis 8 moved to a licence set that includes the AGPL, many teams choose Valkey, the Linux Foundation fork, for self-hosting.

High-level design

flowchart LR
C["Mobile and web clients"] --> GW["API gateway"]
GW --> PS["Post service"]
GW --> FS["Feed service"]
PS --> PDB["Post store<br/>sharded by post_id"]
PS --> MQ["Event log<br/>post_created"]
MQ --> FO["Fan-out workers"]
FO --> G["Follow graph<br/>reverse index"]
FO --> FC["Feed cache<br/>Redis or Valkey"]
FS --> FC
FS --> CEL["Celebrity timelines<br/>hot, replicated"]
FS --> RK["Ranking service"]
FS --> HY["Hydration<br/>posts, authors, counts"]
C --> CDN["CDN for media"]
style FS fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style FO fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style FC fill:#E1F5EE,stroke:#0F6E56,color:#085041
style CEL fill:#FAEEDA,stroke:#854F0B,color:#633806
style MQ fill:#F1EFE8,stroke:#888780,color:#444441

Write path. The post service stores the post, appends it to the author’s timeline and publishes a post_created event to a durable log such as Kafka (see Kafka internals). Writing to the database and publishing the event must not be a dual write that can half-fail; use the outbox pattern or CDC. Fan-out workers consume events, look up the author’s followers and push the post ID into each follower’s feed cache, unless the author is a celebrity.

Read path. The feed service reads the user’s precomputed feed from cache, merges in recent posts from any celebrities they follow, sends the candidates to ranking, hydrates the top results (post bodies, author profiles, like counts, “liked by me”) and returns a page with a cursor.

Deep dive 1: fan-out on write, on read, or hybrid

Fan-out on write (push). At post time, copy the post ID into every follower’s feed. Reads are a single cache lookup, so they are fast and cheap. Writes are amplified by follower count. Great for the 99.9% of accounts with modest followings, terrible for celebrities, and wasteful for followers who never log in.

Fan-out on read (pull). At read time, fetch the follow list, pull recent posts from each followee’s timeline and merge. Writes are cheap (one append). Reads fan out to every followee: a user following 400 accounts means 400 timeline lookups per feed load, and the page is only as fast as the slowest of them.

You can feel the read-side tail problem in the widget below: set fan-out to 400 and per-backend slow probability to 1%, and nearly every feed load hits at least one slow shard.

Tail latency at fan-out

Widen the fan-out and watch a rare slow backend become the common case. Then turn on hedged requests.

Requests hit by a slow backend
Fan-out where half are slow

Assumes backends are slow independently. Hedging is approximated as p squared per backend; real systems send the backup only after a delay (for example at the p95), which costs a few percent extra load.

Hybrid. Push for normal accounts, pull for accounts above a follower threshold. At read time, take the precomputed feed and merge in the latest posts from the handful of celebrities the user follows. Twitter described essentially this approach in its 2013 “Timelines at Scale” talk: fan-out on write into Redis-backed timelines, with very high follower accounts merged at read time.

sequenceDiagram
participant U as User
participant F as Feed service
participant FC as Feed cache
participant G as Follow graph
participant CT as Celebrity timelines
participant R as Ranker
participant H as Hydration
U->>F: GET /v1/feed
F->>FC: ZRANGE feed:42 0 499 REV
F->>G: celebrities followed by 42
F->>CT: latest 50 posts each (parallel)
F->>R: about 900 candidates
R-->>F: top 20 with scores
F->>H: posts, authors, counts, liked_by_me
H-->>F: hydrated items
F-->>U: 20 items + signed cursor

The threshold does not need to be a hard number. Many designs choose per account by follower count and by recent posting rate, and move accounts between modes as they grow.

Deep dive 2: feed storage

Each feed is a Redis or Valkey sorted set keyed by user, member = post ID, score = timestamp (or a precomputed rank score). ZADD inserts, ZRANGE with REV reads the newest N, and a trim after each insert keeps the set capped at 500 entries. A capped list (LPUSH then LTRIM) is cheaper in memory when order is purely by arrival, but it cannot be re-scored or deduplicated, so sorted sets are the usual choice.

Store only IDs in the feed, never full posts. A post appears in 200 feeds on average; copying the body would multiply storage by 200 and make edits and deletes impossible to apply. Bodies live once in the post store with a read-through cache in front.

The feed cache is a cache, not the source of truth. If a shard is lost, feeds can be rebuilt by pull from the author timelines and the follow graph, which is slower but correct. This is what makes it acceptable to run the feed cache with asynchronous replication and to evict feeds of inactive users. It is the cache-aside pattern applied to a derived dataset.

Shard the feed cache by user ID with consistent hashing or Redis Cluster hash slots so adding shards moves only a fraction of feeds.

Deep dive 3: ranking

A chronological feed is a sort. A ranked feed is a small recommendation system, and in an interview you describe it at the level of stages, not models.

flowchart LR
A["Candidate generation<br/>feed cache + celebrity pulls<br/>(+ out-of-network recs)<br/>about 1,000 items"] --> B["Light ranker<br/>cheap model, simple features<br/>keep about 200"]
B --> C["Heavy ranker<br/>predicts like, comment,<br/>share, hide probability"]
C --> D["Re-ranking and policy<br/>diversity, author caps,<br/>dedupe, blocks, ads slots"]
D --> E["Page of 20"]
style A fill:#F1EFE8,stroke:#888780,color:#444441
style B fill:#E1F5EE,stroke:#0F6E56,color:#085041
style C fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style D fill:#FAEEDA,stroke:#854F0B,color:#633806
  • Candidate generation gathers everything eligible: the precomputed feed, celebrity posts, and optionally recommended posts from outside your follows.
  • Light ranking cuts a thousand candidates to a couple of hundred using cheap features (recency, author affinity, engagement so far).
  • Heavy ranking scores the survivors with a model that predicts engagement actions and combines them into one score. Features come from a feature store: how often you interact with this author, what topics you engage with, how the post is doing.
  • Re-ranking applies rules on top: no more than two posts in a row from the same author, mix of media types, remove posts from blocked or muted accounts, enforce visibility, insert ads.

The latency budget is the constraint: if the API has 300 ms at p99, ranking might get 100 ms, so the heavy model can only score a few hundred items. Always keep a fallback: if ranking times out, return the candidates in chronological order. A slightly worse feed beats an error.

Deep dive 4: pagination

Offset pagination (page=3) breaks on a feed: new posts arrive at the top while you scroll, so items shift and you see duplicates or skip posts. Use cursors, as explained in pagination patterns.

For a chronological feed, the cursor is the last seen (timestamp, post_id) pair, and the next page is “items strictly older than that”. The post ID breaks ties between equal timestamps.

For a ranked feed, scores change between requests, so a cursor on the score is unstable. The common approach is to snapshot the ranked list for the session: rank about 500 items on the first request, store the ordered IDs in cache for 10 to 30 minutes under a session key, and make the cursor that session key plus an offset. Pull-to-refresh starts a new session. Sign the cursor (HMAC) so clients cannot forge offsets or session IDs.

Deep dive 5: likes and counters

A viral post can receive tens of thousands of likes per second. A single counter row or a single Redis key becomes a write hot spot: one shard, one lock, one CPU.

  • Dedupe first. The likes table has a unique key on (post_id, user_id), so a like is an idempotent insert. Its existence answers “liked by me”.
  • Sharded counters. Split the count across N sub-counters, for example likes:post_id:0 to likes:post_id:15. Each like increments a random shard; reads sum the 16 values (or read a cached sum refreshed every second). This spreads 40,000 writes per second over 16 keys, 2,500 each.
  • Asynchronous aggregation. Alternatively, write like events to the log and let a stream processor aggregate counts per post per second and update the counter. Counts lag by a second or two, which nobody notices.
  • Display approximation. Users see “1.2M likes”, not “1,203,417”, so the displayed number can be cached and slightly stale.

For unique viewer counts on posts, an exact set of viewer IDs per post is enormous. A HyperLogLog per post estimates unique viewers within about 1% error in around 12 KB, covered in probabilistic data structures.

Deep dive 6: media

Clients upload media directly to object storage using a pre-signed URL, rather than streaming bytes through the post service; the file upload design article covers resumable uploads and validation. An asynchronous pipeline generates renditions (thumbnails, several widths, video bitrates) and the post references media IDs. Feeds return CDN URLs, and the CDN serves the bytes with long cache lifetimes, because a given rendition never changes; a new edit is a new object key. At 25 TB of new media per day, egress cost and cache hit ratio at the edge are bigger cost levers than anything in the feed service.

Deep dive 7: the celebrity hot key and cache stampede

Back to the 21:03 post. Even with hybrid fan-out, 8 million users loading their feed in one minute will all hydrate the same post, author profile and like counter. That is about 130,000 reads per second for one key. A single cache node serves perhaps 100,000 to a few hundred thousand simple operations per second, and the moment that key expires or is evicted, every request misses together and hits the post store: a cache stampede.

Defences, each covered in cache stampedes and hot keys:

  • Replicate hot keys. Store the celebrity post under several keys (post:id:r0 to r7) on different shards and read a random replica.
  • Local in-process cache. Feed service instances keep the hottest posts in memory for 1 to 5 seconds. With 500 instances, the backing cache sees at most 500 reads per second per hot key instead of 130,000.
  • Request coalescing. On a miss, one request per instance fetches from the store and the others wait for it (singleflight).
  • Early refresh. Refresh hot entries before expiry, probabilistically or with a background job, so they never expire under load.
  • Detect hotness. Count key access with a sampled sketch (Count-Min) and promote keys to “hot” automatically.

The celebrity timelines themselves are small and read constantly, so they are a natural fit for heavy replication and local caching.

Bottlenecks, failures and trade-offs

Fan-out backlog. A burst of posts pushes the fan-out queue lag up. Feeds go stale but nothing breaks, because the queue decouples posting from delivery. Mitigations: autoscale workers on consumer lag, prioritise fan-out to recently active users, and temporarily raise the celebrity threshold so more accounts switch to pull. Monitor freshness (time from post to feed insertion) as an SLI.

Feed cache shard lost. Users on that shard get a slower feed rebuilt by pull from author timelines, then re-cached. Protect the post store from the rebuild with rate limits and coalescing; a mass rebuild is a thundering herd of its own.

Ranking down or slow. Time out at the budget and serve chronological. Alert on the fallback rate.

Post store slow. Hydration fails; serve cached post bodies, drop items that cannot be hydrated, and never fail the whole page for one missing item.

Morning surge or post-outage reconnect. Millions of clients refresh at once. Client-side jittered retry (see timeouts, retries and backoff) and server-side load shedding keep the recovery from becoming a second outage.

Deletes and privacy. A deleted post or a newly blocked user may still be in thousands of feed caches. Do not try to chase every copy synchronously. Instead filter at hydration: the post store is the authority on deleted and visibility flags, and block lists are checked at read time. Background jobs clean up feed entries lazily.

Consistency choices. Feeds are eventually consistent, which is fine. Two places are not: your own post must appear in your feed immediately (merge the user’s own recent posts from their author timeline at read time, giving read-your-writes without waiting for fan-out), and deletes must be honoured on read.

Multi-region. Home each user to a region; their feed cache lives there. Posts replicate asynchronously between regions through the event log, and fan-out runs in each region for the followers homed there. Celebrity timelines replicate everywhere. A region failure moves its users to another region, where feeds are rebuilt by pull until the caches warm up. The trade-offs are covered in multi-region architecture.

Decision Choose Gain Pay
Fan-out Hybrid push/pull with threshold Fast reads, bounded writes Two code paths, merge logic
Feed contents IDs only Small cache, edits and deletes work Hydration step on every read
Feed store Redis/Valkey sorted sets, capped Fast top-N reads Memory cost; cache must be rebuildable
Pagination Signed cursor, ranked snapshot Stable scrolling Session state in cache
Like counts Sharded or async-aggregated Survives viral posts Counts lag by seconds
Consistency Eventual + read-your-writes + filter on read Availability and scale Brief staleness in others’ feeds

What a staff answer adds

A solid senior answer gets the hybrid fan-out, the cache and the cursor right. A staff answer goes further:

  • Quantifies the threshold. It derives the celebrity cut-off from cluster write capacity and read fan-out cost, not as a magic number, and makes it adaptive.
  • Treats the cache as derived data. It explains how every cache is rebuilt, how fast, and how the rebuild is protected from becoming an outage.
  • Defines SLOs for freshness and feed latency and shows how the design degrades gracefully: stale feed, chronological feed, fewer items, never an error page. See SLIs, SLOs, SLAs and error budgets.
  • Handles abuse and privacy on the read path. Blocks, deletes and visibility enforced at hydration, not by trusting caches.
  • Talks about cost. Media egress, cache memory per active user and inactive-user pruning are the biggest bills, and choices like “push only to active users” are cost decisions.
  • Plans the evolution. Start with fan-out on read at small scale (simplest and correct), move to push when reads dominate, add the hybrid when the skew bites.

Interview questions

Q1: Why not use fan-out on write for everyone?

Write amplification equals follower count. For typical accounts that is a few hundred inserts, which is fine, but follower counts are heavily skewed: a 100 million follower account turns one post into 100 million writes, saturating the fan-out cluster for minutes, delaying everyone else’s posts, and spending most of the work on followers who will not open the app before the post is buried. The hybrid pushes for normal accounts and pulls celebrity posts at read time, which costs a few extra cache reads per feed load against a small, hot, replicated dataset.

Q2: How do you paginate a ranked feed without duplicates or gaps?

Offsets fail because new posts shift positions, and a cursor on the ranking score fails because scores change between requests. On the first request, rank a few hundred candidates, store the ordered list of post IDs in cache under a session ID with a short TTL, and return a signed cursor containing the session ID and offset. Subsequent pages read the next slice of the snapshot. When the snapshot is exhausted or expires, rank again excluding already shown IDs. Pull-to-refresh creates a new session. Signing prevents clients from tampering with the cursor.

Q3: A user deletes a post that is already in 50,000 feed caches. How do you make sure nobody sees it?

Do not depend on removing every cached copy synchronously. Feed caches hold only post IDs, and every read hydrates posts from the post store or its cache, where the post is marked deleted; hydration drops deleted or no longer visible posts and the page is filled from the next candidates. Invalidate the post body cache entry on delete so hydration sees the flag immediately. A background job can remove the ID from feeds lazily. The same mechanism handles blocks and visibility changes, because they are checked on read.

✅ Key takeaways

  • The feed is dominated by two numbers: reads outnumber posts about 20 to 1, and fan-out multiplies writes by a heavily skewed follower count.
  • Use hybrid fan-out: push for normal accounts (to active followers only), pull and merge for celebrities above a threshold derived from capacity.
  • Store only post IDs in capped sorted sets per user; the feed cache is rebuildable derived data, and hydration is where deletes, blocks and visibility are enforced.
  • Rank in stages (candidates, light ranker, heavy ranker, re-ranking) inside a latency budget, with a chronological fallback.
  • Paginate with signed cursors; for ranked feeds, snapshot the ranking per session.
  • Hot posts need hot-key defences (replication, local caches, coalescing, early refresh) and like counts need sharded or asynchronous counters.

🧠 Check your understanding

0 / 4
  1. 1Average follower count is 200 and there are 250 million posts per day. Roughly how many feed inserts per second does pure fan-out on write need on average?

  2. 2In a hybrid design, how does a follower see a new post from a celebrity with 80 million followers?

  3. 3Why do feed caches store post IDs rather than full post bodies?

  4. 4A viral post receives 40,000 likes per second and the single counter key's shard is saturated. What is the best fix?

Where to go next

Finished this lesson?

Mark it complete to track your progress across the roadmap.