Skip to content

Case Study: News Feed

“Design Twitter’s timeline” or “design Instagram’s feed” is the most common mid-to-senior design question after the URL shortener. It has one central trade-off — fan-out on write or on read — and everything else is a consequence.

Functional

  1. A user follows other users.
  2. A user sees a feed of recent posts from the people they follow, ranked.
  3. Posting appears in followers’ feeds within a few seconds.
  4. Infinite scroll.

Non-functional

  • 300M daily active users, 500M posts/day.
  • Feed load < 200 ms p99 for the first page.
  • Reads vastly outnumber writes per user, but the total write volume is large because of fan-out.
  • Eventual consistency is acceptable: a post appearing 5 seconds late is fine. A post never appearing is not.
  • Availability over consistency: a stale feed beats an error page.

Out of scope: media upload and transcoding, direct messages, ads auction (mention as a real consumer of the ranking pipeline).

Posts: 500M/day ≈ 5,800/s, peak 3× ≈ 17,000/s
Feed reads: 300M users × 10 opens/day = 3B/day ≈ 35,000/s, peak ≈ 100,000/s
Followers: median 200, mean 500, p99 50,000, max 100M+
Feed size: 1,000 post ids per user, 8 bytes each = 8 KB per cached timeline
Cache: 300M × 8KB = 2.4 TB for everyone (only active users matter: ~20% → 500 GB)
Post storage: 500M × 500B = 250 GB/day ≈ 90 TB/year
Fan-out write: 500M posts × 500 avg followers = 250B timeline writes/day ≈ 2.9M/s

That last number is the entire problem. 2.9 million timeline insertions per second to deliver posts eagerly. No single store does that affordably, and one account with 100M followers would alone produce 100M writes per post.

POST /v1/posts
{ "text": "...", "media_ids": [...] }
201 { "id": "01HZX...", "created_at": "..." }
GET /v1/feed?cursor=<opaque>&limit=20
200 { "items": [ { "post_id": "...", "author": {...}, "score": 0.83 } ],
"next_cursor": "..." }
POST /v1/follows/{user_id}
DELETE /v1/follows/{user_id}

The cursor encodes (score, post_id) or (created_at, post_id) so pagination is stable while new posts arrive. Offset pagination breaks immediately in a feed: new posts shift every page.

Fan-out on write (push). When a user posts, write the post id into every follower’s timeline list.

post created → look up followers (cached) → LPUSH post_id into feed:{user_id} for each
→ trim to 1,000 entries
  • Read is LRANGE feed:{user_id} 0 19 — one Redis call, very fast.
  • Write cost is proportional to follower count.
  • A celebrity post with 100M followers is a 100M-write operation. Unacceptable.

Fan-out on read (pull). Store posts per author; on read, fetch the recent posts of everyone you follow and merge.

read → for each of 500 followees: ZRANGE posts:{author} 0 9 → merge by score → top 20
  • Write is O(1). Read is O(followees) — 500 queries per feed load. Also unacceptable at this scale.

Hybrid (what real systems do). Push for normal users, pull for celebrities.

on post:
if author.followers < 10,000: push to every follower's timeline
else: do nothing; mark the post as "pull-only"
on read:
ids = LRANGE feed:{user} 0 199 -- pushed posts
ids += recent posts from each pull-only followee -- a handful of queries
merge by score, filter, take 20

The number of pull-only accounts a user follows is small (tens, not hundreds), so the read stays cheap. The threshold is a tuning parameter; state it as one.

Chronological is a legitimate v1 and much easier to reason about. Ranked feeds add:

  • Candidate generation: pull a few hundred ids (pushed + pulled + recommended).
  • Feature fetch: author affinity, recency, engagement prediction, media type, already-seen.
  • Scoring: a model (logistic regression or a small neural net) producing a score per candidate.
  • Filtering: blocked users, muted words, deleted posts, already-seen items, policy violations.
  • Diversity: avoid five posts from the same author in a row.
candidates (500) → hydrate features (batch, one round trip per feature store)
→ score (in-process model) → filter → diversify → top 20

Latency budget: candidates in <20 ms, features in <50 ms, scoring in <20 ms. Anything that cannot fit moves to a precomputed feature.

Because ranking is expensive, the scored result set is cached per user for a short window (1–5 minutes). New posts arriving in that window can be injected at the top unranked.

Pagination with ranking is subtle: a cursor must encode the score boundary, and the ranked list must be stable enough that page 2 does not repeat items from page 1. Freezing the candidate set per session for a short TTL is the usual compromise.

Data Store Why
Posts (text, media refs) Wide-column or partitioned relational Write-heavy, keyed by post id
Timeline (list of post ids) Redis lists / sorted sets Bounded, fast, disposable
Social graph Graph store or adjacency table High fan-out reads, followers(user) and followees(user)
Counters (likes, replies) Sharded counters, periodically flushed Hot rows otherwise
Features / embeddings Feature store / vector index Batch-fetched at rank time

The timeline cache is disposable. If Redis is wiped, feeds rebuild lazily from the post store. That property is what makes the design operable: the expensive, durable data is the posts and the graph; the timeline is a cache with a TTL and a trim.

Never store the timeline only in memory if losing it means losing posts. Store posts durably, ids in the cache.

1. POST /v1/posts → validate → assign id (Snowflake-style, time-ordered)
2. Persist the post (durable)
3. Publish post.created to a queue
4. Fan-out workers:
- read follower list in pages
- for each follower: LPUSH feed:{id}, LTRIM to 1,000
- skip if the author is pull-only
5. Update author's own post index (for profile pages and pull reads)

Two things to get right:

  • Idempotency. The worker will be redelivered. LPUSH twice means duplicate entries in a feed. Either deduplicate at read time, or use a sorted set with the post id as the member so re-adding is a no-op.
  • Backpressure. A megastar post creates a huge fan-out job. Split followers into chunks, rate limit the workers, and let the queue absorb the burst. This is exactly why pull-only exists.
1. GET /v1/feed?cursor=...
2. LRANGE feed:{user_id} 0 499 (or ZREVRANGE by score)
3. Fetch pull-only followees' recent posts (cached per author, short TTL)
4. Merge, hydrate post bodies via a multi-get (batched, never N+1)
5. Filter (deleted, blocked, seen)
6. Rank the top ~500 → take 20
7. Return items + opaque cursor

Hydration is where feeds get slow: 20 posts × 3 services is 60 calls if done naively. Batch by service: one call to the post store with 20 ids, one to the user service with N author ids, one to the counter service. This is the same N+1 lesson as in REST vs GraphQL, at a larger scale.

  • Cache the first page aggressively; it is read far more than any other page.
  • Precompute for inactive users: rebuild a feed when they log in rather than maintaining it forever. Most of the 300M DAU open the app a handful of times a day.
  • Shard the timeline cache by user id. It is a pure key-value workload.
  • Degrade gracefully: if ranking fails, serve chronological from the cached id list. If the timeline cache misses, fall back to a pull-based merge over a smaller followee set.
  • Multi-region: posts replicate globally; timelines are region-local and rebuildable, which makes active-active feasible.
  • Delete: a deleted post must disappear from cached timelines. Either filter at read (hydrate fails → skip) or publish a post.deleted event that removes the id from cached lists.
  1. How would you handle a user with 100M followers posting ten times an hour?
  2. What is the write amplification of fan-out on write, and where does it break?
  3. How do you paginate a ranked feed without duplicates or gaps?
  4. Where does the “already seen” filter live, and how big does that set get?
  5. What happens when Redis loses the timeline cache?
  6. How do you guarantee a deleted post stops appearing everywhere?
  • Not quantifying fan-out. 500M posts × 500 followers is 250B writes/day. Say it out loud.
  • Choosing pure push or pure pull. Both fail at some follower count; the hybrid is the answer.
  • Offset pagination. Feeds shift constantly; the cursor must be opaque and stable.
  • Ignoring hydration cost. Fetching 20 post bodies from three services per request is an N+1 at scale.
  • Making the timeline the source of truth. It must be rebuildable, or a cache flush becomes data loss.