01

Requirements & scope

Problem Statement & Requirements

Functional Requirements

  • Publish posts -- users create text posts, links, photos, or videos
  • News feed -- a personalized, ranked stream of posts from friends/followed accounts
  • Retweet / share -- amplify someone else's post to your followers
  • Like, reply, quote-tweet -- engagement actions
  • Follow / friend -- asymmetric (Twitter: follow) or symmetric (Facebook: friend)
  • Trending topics -- surface popular topics in real-time
  • Notifications -- new followers, likes, mentions, replies
  • Real-time updates -- new posts appear in feed without manual refresh (for active users)

Non-Functional Requirements

  • Low latency -- feed renders in < 500 ms
  • High availability -- 99.99% uptime
  • Eventually consistent -- slight delay in feed propagation is acceptable
  • Massively read-heavy -- read:write ratio ~1000:1
  • Scalability -- 500M+ DAU, 1B+ feed reads/day
  • Freshness -- breaking news and viral content surface within seconds

Key Differences from Instagram Design

AspectInstagramTwitter / Facebook
Primary contentPhotos/videoText + mixed media
Feed modelVisual grid + ranked feedChronological stream (Twitter) or ranked (Facebook)
Engagement styleLike + commentLike, reply, retweet, quote-tweet, bookmark
AmplificationNone (no reshare)Retweet = core mechanic, viral amplification
Graph typeAsymmetric (follow)Twitter: asymmetric; Facebook: symmetric
Real-time needModerateHigh (breaking news, live events)
ThreadingFlat commentsThreaded conversations (Twitter threads)
02

Scale estimations

Scale Estimations

Users & Content

MetricValue
Daily Active Users (DAU)500M
Total users2B
New posts / day500M
Average post size (text + metadata)1 KB
Posts with media30% (images/video served via CDN)
Average friends/following per user300
Avg feed reads per user per day10
Total feed reads / day5B

Traffic

MetricValue
Feed reads / second (avg)~58K RPS
Feed reads / second (peak)~200K RPS
Post writes / second~5,800 WPS
Read:Write ratio~10:1 (feed reads) to ~1000:1 (including passive reads)

Storage

MetricValue
Post storage / day500M x 1 KB = 500 GB/day
Post storage / year~180 TB/year
Feed cache (Redis)500M users x 500 post_ids x 16 bytes = ~4 TB
Social graph2B users x 300 avg edges = 600B edges

Fanout

MetricValue
Avg followers per poster300
Total fanout writes / day500M posts x 300 = 150B feed cache writes/day
Fanout writes / second~1.7M WPS
Celebrity post (10M followers)10M writes per single tweet
03

Layered architecture

Phase 1 of 4 · Client & edge

Start with the entry points

First, define who uses the system and where requests enter. This is the boundary of the design, not yet a complete request path.

Client
Separate the publish path from the latency-sensitive timeline read path.
API gateway
Authenticate requests and protect expensive feed generation from abusive traffic.
Architecture after phase 1. Includes Client, API gateway. Client connects to API gateway.
Phase 1 — Start with Client, API gateway.SVGSVGEditable diagramEditable diagram

This first layer defines the system boundary. The next chapters add application logic and data dependencies. After examining the request paths and tradeoffs, we will add operational safeguards and bring the complete architecture together.

04

API & contracts

Phase 2 of 4 · Application & compute

Add the application logic

Keep the entry points and add the services that do the work. Give each service a clear responsibility before defining its contracts. Storage and background dependencies come next.

Post service
Commit post content and metadata before asynchronous distribution begins.
Fanout service
Push regular users' posts to followers, but merge high-fanout accounts on read.
Feed + ranking
Gather candidates, apply visibility filters, then score and order the timeline.
Architecture after phase 2. Includes Client, API gateway, Post service, Fanout service, Feed + ranking. Client connects to API gateway. API gateway connects to Post service. Post service connects to Fanout service. API gateway connects to Feed + ranking.
Phase 2 — Added Post service, Fanout service, Feed + ranking. Earlier layers remain in place.SVGSVGEditable diagramEditable diagram

A feed response needs stable item IDs and an opaque cursor, not just a page number. Carry the ranking or snapshot context needed to continue a reading session. Post creation should have its own idempotency boundary, and every feed read must apply current visibility rules even when candidate IDs came from an older cache.

05

Data model

Phase 3 of 4 · Data & async work

Connect data and background work

The services now need their dependencies: durable state, fast lookups, or work that continues outside a request. Separate these responsibilities rather than treating every component as a database.

Post store
Persist posts independently of any derived feed cache so feeds can be rebuilt.
Feed cache
Store compact ordered IDs and fetch post objects in batches.
Graph + features
Use graph relationships for candidates and freshness-aware features for ranking.
Architecture after phase 3. Includes Client, API gateway, Post service, Fanout service, Feed + ranking, Post store, Feed cache, Graph + features. Client connects to API gateway. API gateway connects to Post service. Post service connects to Fanout service. API gateway connects to Feed + ranking. Post service connects to Post store. Fanout service connects to Feed cache. Feed + ranking connects to Feed cache. Feed + ranking connects to Graph + features.
Phase 3 — Added Post store, Feed cache, Graph + features. Earlier layers remain in place.SVGSVGEditable diagramEditable diagram

Data Model

Posts Table

Posts Table
Posts TableSVGSVGEditable diagramEditable diagram

Conversation Threading

Conversation Threading
Conversation ThreadingSVGSVGEditable diagramEditable diagram
06

Core design decisions

Ranking System (Deep Dive)

Feature Categories

Feature Categories
Feature CategoriesSVGSVGEditable diagramEditable diagram

Ranking Model Architecture

Ranking Model Architecture
Ranking Model ArchitectureSVGSVGEditable diagramEditable diagram

Two-Phase Ranking

Two-Phase Ranking
Two-Phase RankingSVGSVGEditable diagramEditable diagram

Fanout Strategies Compared

Fanout Strategies Compared
Fanout Strategies ComparedWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram
07

Request flows

Post Publishing Flow

Post Publishing Flow
Post Publishing FlowWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram

Retweet / Share Flow

Retweet / Share Flow
Retweet / Share FlowSVGSVGEditable diagramEditable diagram

Feed Read Flow -- Timeline Assembly

This is the core of the design -- how a user's feed is constructed on read.

Feed Read Flow -- Timeline Assembly
Feed Read Flow -- Timeline AssemblySVGSVGEditable diagramEditable diagram

Timeline Assembly Flow Diagram

Timeline Assembly Flow Diagram
Timeline Assembly Flow DiagramWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram
08

Performance & caching

Caching Architecture (Multi-Layer)

Caching Architecture (Multi-Layer)
Caching Architecture (Multi-Layer)SVGSVGEditable diagramEditable diagram
09

Advanced design

Real-Time Feed Updates

Real-Time Feed Updates
Real-Time Feed UpdatesSVGSVGEditable diagramEditable diagram

Trending Topics

Trending Topics
Trending TopicsSVGSVGEditable diagramEditable diagram

Handling Viral Posts

Handling Viral Posts
Handling Viral PostsSVGSVGEditable diagramEditable diagram
10

Edge cases

A reader may refresh while new posts arrive and older posts are deleted. Define whether the cursor represents a snapshot or a moving window, then avoid duplicating items within that contract. Blocks and privacy changes override cached membership: appearing in a precomputed feed is not sufficient authorization to display a post.

11

Tradeoffs

Tradeoffs & Design Decisions Summary

DecisionOption AOption BChosenWhy
Fanout strategyFanout-on-writeFanout-on-readHybridPush for normal users (fast reads), pull for celebrities (avoid 100M writes)
Feed orderChronological onlyML-ranked onlyBoth tabs"Following" for chronological purists; "For You" for engagement optimization
Ranking modelSingle-task (P(click))Multi-task (like, reply, RT, hide)Multi-taskOptimizes for healthy engagement, not just clicks
Ranking pipelineSingle modelTwo-phase (pre-rank + heavy rank)Two-phasePre-rank prunes 80% cheaply; heavy rank uses expensive features on fewer candidates
Real-time updatesWebSocket (all users)Polling + SSE hybridHybridOnly ~5% of users are actively watching feed; WebSocket for all is wasteful
Feed cacheDatabase queryRedis sorted setRedisO(1) reads, pre-computed, handles 200K RPS
Post cacheRedisMemcachedMemcachedSimple key-value, no persistence needed, better memory efficiency for cache
Trending detectionBatch (hourly)Stream processing (real-time)Stream (Flink)Trends need to surface within minutes, not hours
Trending metricAbsolute volumeRelative spike vs baselineRelative spike"Weather" always has high volume but isn't trending; relative detects actual spikes
Retweet storageCopy postPointer to originalPointerOne post can have 1M retweets -- can't copy 1M times
Thread modelFlat repliesConversation threadingThreadingconversation_id groups all replies; reply_to enables tree structure
Out-of-network contentNone (only followed users)SimClusters + social proofSimClusters"For You" tab needs content discovery beyond your follows
Viral post handlingSame as normalHot key replication + async countersSpecial handling100K reads/sec on one post breaks a single cache node
Counter updatesSynchronous DB writeKafka -> aggregate -> batch flushAsync batchCan't do 100K writes/sec to a single row
12

Reliability & fault tolerance

Phase 4 of 4 · Operations & resilience

Add operational safeguards

With the request paths and tradeoffs established, add the controls that help detect trouble and keep the system operating. The final diagram retains every layer introduced so far.

Event pipeline
Track fanout lag and cap expensive viral workloads before queues cascade.
Architecture after phase 4. Includes Client, API gateway, Post service, Fanout service, Feed + ranking, Post store, Feed cache, Graph + features, Event pipeline. Client connects to API gateway. API gateway connects to Post service. Post service connects to Fanout service. API gateway connects to Feed + ranking. Post service connects to Post store. Fanout service connects to Feed cache. Feed + ranking connects to Feed cache. Feed + ranking connects to Graph + features. Fanout service connects to Event pipeline.
Phase 4 — Added Event pipeline. Earlier layers remain in place.SVGSVGEditable diagramEditable diagram

If personalized ranking fails, a chronological list of permitted recent posts is often more useful than a blank page. Bound how long feed assembly waits for optional signals. Keep post records authoritative and rebuild derived feed entries from durable events when fanout workers fall behind.

13

Production architecture

High-Level Architecture

High-Level Architecture
High-Level ArchitectureSVGSVGEditable diagramEditable diagram

Detailed Architecture

Detailed Architecture
Detailed ArchitectureWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram

Production Architecture

Production Architecture
Production ArchitectureWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram
14

Further exploration

Twitter-Specific: "For You" vs "Following"

Twitter-Specific: "For You" vs "Following"
Twitter-Specific: "For You" vs "Following"SVGSVGEditable diagramEditable diagram
15

Interview playbook

Interview Tips

  1. Frame the two core problems -- "A news feed has two hard problems: (1) how to build the feed efficiently (fanout strategy) and (2) how to rank it (ML pipeline). Let me address both."

  2. Fanout is the opening move -- Start with fanout-on-write vs fanout-on-read. Show the celebrity problem. Land on hybrid. This is the foundation everything else builds on.

  3. Timeline assembly is the full picture -- "Building the feed is a 5-stage pipeline: gather candidates, hydrate, rank, filter, return." Walk through each stage. This shows you think about the complete system, not just storage.

  4. Ranking shows ML maturity -- "We use a multi-task model that predicts P(like), P(reply), P(retweet), and P(hide). The final score is a weighted combination optimizing for healthy engagement." Name specific features.

  5. Caching layers show systems depth -- "There are 6 layers of cache: client SQLite, CDN for media, Redis for feed, Memcached for posts, Memcached for users, TAO for social graph." Name each one and its purpose.

  6. Trending is a stream processing problem -- "We use Flink to process every post in real-time, extract entities, count in sliding windows, and compute spike ratios vs baseline." Shows you know stream processing.

  7. Retweet is a unique design concern -- "A retweet is a pointer, not a copy. It triggers the same fanout as a new post but for the retweeter's followers. Celebrity retweets = same celebrity fanout problem."

  8. Real-time updates are overvalued -- "Only ~5% of users are actively watching their feed. For the other 95%, the feed is assembled on next app open. Don't over-engineer WebSocket for everyone."

  9. "For You" vs "Following" is a product decision -- "Algorithmic feeds increase engagement 40-60% but users feel less control. Offering both tabs is the modern compromise."

  10. Viral content handling shows production thinking -- "A single viral post can get 100K reads/sec on one cache key. We detect hot keys, replicate across cache shards, and use approximate counters to avoid write storms."