Skip to main content

Twitter: Requirements & High-Level Design

Editorial

Problem Statement

Design a Twitter-like service. Users post short text tweets (up to 280 characters), follow and unfollow other users, and view a home timeline of tweets from the people they follow, ranked by relevance as well as recency. They can also view a user's profile, with that user's own tweets. The service has hundreds of millions of daily users, reads far outnumber writes, a timeline must load in well under a second, and no posted tweet may ever be lost.

The functional requirements below come from its verbs; the rest of the statement sets the non-functional ones.

Introduction

"Design Twitter" is one of the most frequently asked system design interview questions — and for good reason. Twitter (now X) is deceptively simple on the surface: users post short messages and see a feed of messages from people they follow. But beneath that simplicity is a system for hundreds of millions of daily users. This design assumes 300 million daily active users posting ~600 million tweets a day, with home timelines that blend tweets from hundreds of followed accounts with a recommendation algorithm, all in under 200 ms. (X no longer publishes audited numbers. For a real reference point: in 2012 Twitter served 150 million active users, about 300,000 timeline reads a second, and 5,000 tweets a second on average, over 12,000 during big events.)

The core design challenges that make Twitter such a rich interview problem:

  • Fan-out at write vs. read time: When a user posts a tweet, should the system push it to all followers' timelines immediately (fan-out-on-write), or should each follower pull it when they open their feed (fan-out-on-read)? This single decision shapes the entire architecture.
  • The celebrity problem: an account with 80 million followers turns one tweet into 80 million timeline writes under fan-out-on-write. (In 2012 a tweet from Lady Gaga, then at 31 million followers, took up to 5 minutes to reach them all.) How do you handle users with millions of followers without melting the write path?
  • Timeline ranking: Modern Twitter doesn't just show a chronological feed — it uses an ML ranking model to surface the most relevant tweets. This adds a real-time scoring step between data retrieval and display.
  • Write throughput: At 300M DAU posting ~2 tweets/day on average, that's ~600M tweets/day — ~7,000 writes/sec steady, ~21,000/sec at peak. Each tweet must be durably stored and fanned out.
  • Read throughput: With a 100:1 read-to-write ratio, the read path sees ~700K QPS average and ~2.1M QPS at peak. Caching and pre-computation are essential.

In this editorial we design Twitter from first principles — starting from requirements, estimating scale, choosing between fan-out strategies, designing the API and data model, and then diving deep into the timeline generation pipeline, caching, and the celebrity problem. Depth is stratified by seniority level.

Why Twitter is hard: the home timeline. Three panels. 1, FAN-OUT: one tweet must reach every follower; an AUTHOR is drawn with arrows to four followers' timelines, the newest cell of each filled. If each timeline is built ahead, one tweet from an account with 80M followers means 80M timeline writes. 2, MERGE: one timeline, many authors; four authors feed YOUR TIMELINE, which must blend and rank tweets from hundreds of accounts in under 200 ms. 3, READ-HEAVY: reads far outnumber writes; on one scale, ~7K tweets posted a second is a sliver next to ~700K timeline reads a second (21K and 2.1M at peak): 100 timeline reads for every tweet posted.

Functional Requirements

We derive functional requirements from the verbs in the problem statement:

Core (must-have for MVP)

  1. Post Tweet — Authenticated users can post a short text message (up to 280 characters). Tweets are stored durably and visible on the author's profile and followers' timelines.
  2. Follow / Unfollow — Users can follow other users to see their tweets in the timeline. Unfollowing removes those tweets from future timeline loads.
  3. Home Timeline — Users see a feed of tweets from people they follow, ordered by a blend of recency and relevance (recommendation algorithm). Paginated via cursor.
  4. User Profile / User Timeline — View all tweets posted by a specific user, ordered by recency.

Extended (out of scope but worth mentioning)

  • Retweets, quote tweets, and likes.
  • @mentions and hashtags.
  • Direct messages (DMs).
  • Media attachments (images, videos).
  • Search (full-text tweet search).
  • Trending topics.
  • Notifications.

Non-Functional Requirements

RequirementTargetReasoning
Scale300M daily active users (DAU)Twitter-scale platform
Write throughput~7,000 tweets/sec (peak ~21K/sec)300M users × 2 tweets/day
Read throughput~700K reads/sec (peak ~2.1M/sec)100:1 read:write ratio
Latency (timeline, p99)< 200msUsers expect instant feed loads
Latency (post tweet)< 500ms response to authorFan-out can happen asynchronously
Availability99.99%Core social platform — downtime is PR-damaging
ConsistencyEventual (seconds) for timeline; strong for tweet storageFollowers may see tweets a few seconds late
Storage horizonPlan capacity for 5 yearsTweets are kept until their author deletes them; 5 years sizes the storage
DurabilityNo tweet lossUser-generated content is sacred

The critical insight: Twitter is an extreme read-heavy system with a 100:1 read-to-write ratio. But unlike a key-value store, reads are aggregation queries — assembling a timeline from hundreds of different users' tweets. This makes the fan-out strategy the single most important design decision.

Resource Estimation

Assumptions:

  • 300M daily active users
  • 2 tweets per user per day → 600M tweets/day
  • Average tweet size: 280 bytes (text) + 200 bytes (metadata) = ~480 bytes per tweet record
  • Read:write ratio: 100:1
  • Average user follows 200 accounts
  • Storage planned for 5 years (tweets never expire)

Traffic Estimation

MetricCalculationResult
Daily tweets300M × 2600M/day
Write QPS (avg)600M ÷ 86,400~7,000/sec
Write QPS (peak, 3×)7,000 × 3~21,000/sec
Read QPS (avg)7,000 × 100~700,000/sec
Read QPS (peak, 3×)700K × 3~2,100,000/sec

Storage Estimation

MetricCalculationResult
Daily storage600M × 480 bytes~288 GB/day
Annual storage288 GB × 365~105 TB/year
5 years105 TB × 5~525 TB total

Fan-out Storage (Timeline Cache)

MetricCalculationResult
Timeline cache per user200 tweets × 8 bytes (tweet_id)~1.6 KB/user
Total timeline cache300M × 1.6 KB~480 GB in Redis
Fan-out writes per tweet (avg)avg followers: 200200 cache writes per tweet
Fan-out writes/sec (avg)7,000 tweets/sec × 200~1.4M cache writes/sec

Bandwidth Estimation

MetricCalculationResult
Write ingress21K/sec × 480 bytes~10 MB/sec (80 Mbps)
Read egress2.1M pages/sec × 20 tweets × 480 bytes~20 GB/sec (~160 Gbps)

Images and video are served by a CDN and not counted here.

The most surprising number: 1.4 million cache writes per second just for fan-out. This makes the fan-out pipeline the most infrastructure-intensive component.

API Design

Five core API endpoints grouped by service domain.

Post a Tweet

POST /api/tweets

Request:

{
  "content": "Just had the best coffee of my life ☕️",
  "client_id": "t-9f2a3b81"
}

Response (201 Created):

{
  "tweet": {
    "id": "1901581777106018311",
    "content": "Just had the best coffee of my life ☕️",
    "author_id": "2f6c8a1e-4b7d-4c19-9a3e-5d2b7f0c8e41",
    "author_handle": "@alice",
    "created_at": "2025-03-17T10:30:00Z",
    "likes": 0,
    "retweets": 0,
    "replies": 0
  }
}

Design decisions:

  • Idempotency key (client_id, generated once per tweet by the client) prevents duplicate tweets when the client retries after a network error.
  • Response returns the tweet immediately — fan-out to followers happens asynchronously.
  • The tweet is durably stored before returning 201. Fan-out is eventually consistent.

Home Timeline

GET /api/timeline?cursor={cursor}&size={size}

Returns the user's personalized home timeline. Pagination uses an opaque cursor: the server encodes where the page ended. A timestamp would not do, because a ranked feed is not in time order, so a timestamp cursor would skip or repeat tweets.

Response:

{
  "next_cursor": "eyJwb3MiOjIwfQ",
  "tweets": [
    {
      "id": "1901581777106018311",
      "content": "Just had the best coffee of my life ☕️",
      "author_id": "2f6c8a1e-4b7d-4c19-9a3e-5d2b7f0c8e41",
      "author_handle": "@alice",
      "author_avatar": "https://cdn.example.com/avatars/alice.jpg",
      "created_at": "2025-03-17T10:30:00Z",
      "likes": 42,
      "retweets": 7,
      "replies": 3,
      "liked_by_user": false
    }
  ]
}

User Timeline

GET /api/users/{user_id}/tweets?cursor={tweet_id}&size={size}

Returns all tweets from a single user, ordered by recency. Simpler than home timeline — no fan-out or ranking needed, just a direct query on the author's tweets. Here the order is the ID order, so the cursor is simply the last tweet ID on the page: the next page reads tweet_id < cursor from the author's partition.

Follow and Unfollow

POST   /api/users/{user_id}/follow
DELETE /api/users/{user_id}/follow

Response: 200 OK with updated follower/following counts. Follow triggers an async background job that loads the followed user's recent tweets into the follower's timeline cache. Unfollow starts a job that removes the unfollowed author's tweets from the cache (Deep Dives).

High-Level Design

How does the overall system architecture work?

Level: Senior

The architecture is organized around three independent services — Tweet Service, Follow Service, and Timeline Service — each with its own data store and scaling characteristics.

Twitter end to end: push on write, merge on read. The CLIENT calls a GATEWAY that routes to three services. FOLLOW writes follow edges to the SOCIAL GRAPH (Cassandra). TWEET gets an ID from the SNOWFLAKE ID generation service, writes the tweet to the TWEETS table (Cassandra), and publishes TweetCreated to KAFKA, which feeds search, analytics and the FAN-OUT workers. The fan-out reads the author's followers from the social graph and pushes the tweet ID onto each follower's list in the Redis TIMELINES cache. TIMELINE serves a timeline in three reads: 1, the user's timeline from Redis; 2, the recent tweets of the celebrities they follow, from the TWEETS table; 3, the tweets themselves, hydrated from the Redis TWEET CACHE.

Write path (posting a tweet):

  1. Client sends POST /api/tweets to the API Gateway.
  2. Gateway routes to Tweet Service.
  3. Tweet Service generates a unique ID via the ID Generation Service (Snowflake).
  4. Tweet is written to Tweet DB (Cassandra) — synchronous, durable write.
  5. A TweetCreated event is published to Kafka.
  6. Client receives 201 Created with the tweet. Everything below happens asynchronously.
  7. The Fan-out Service consumes the event and writes the tweet ID to every follower's Timeline Cache (Redis).
  8. Search Indexer and Analytics Pipeline also consume from Kafka.

Steps 4 and 5 are two separate writes: if the Tweet Service dies between them, the tweet is stored but no event is published, so it is never fanned out, indexed or counted. The usual fix is to publish from the database's own record of the write, an outbox table or its change-data-capture stream, so the event can't be lost (see Outbox + CDC: Reliable Events from Your Database in Data Systems at Scale).

Read path (loading timeline):

  1. Client sends GET /api/timeline to the API Gateway.
  2. Gateway routes to Timeline Service.
  3. Timeline Service reads the user's pre-computed timeline from Redis, plus the recent tweets of any celebrities they follow (the hybrid below).
  4. For each tweet ID in the timeline, it hydrates the full tweet data (content, author info, engagement counts).
  5. Returns the hydrated, sorted timeline to the client.

Why three separate services instead of a monolith?

Tweet Service handles writes at 21K QPS peak — it needs to be optimized for fast, durable inserts.

Timeline Service handles reads at 2.1M QPS peak — it needs to be optimized for ultra-fast cache lookups.

Follow Service handles social graph mutations (~relatively rare, bursty when a celebrity account goes viral) — it has different scaling characteristics.

Each service can scale horizontally and independently based on its own traffic patterns. A spike in timeline reads doesn't need to scale the tweet write path, and vice versa.

Why Kafka as the message bus?

When a tweet is posted, multiple things need to happen: fan-out to followers' timelines, indexing for search, analytics ingestion, and (for certain tweets) notification dispatch.

If the Tweet Service called each downstream service synchronously:

  • Write latency would be 200-400ms (4 sequential calls).
  • If fan-out or search indexing is down, tweet posting fails.
  • Adding new consumers (e.g., a new recommendation signals pipeline) requires changing the Tweet Service.

Kafka decouples all of this: Tweet Service publishes once, each downstream consumer processes independently. Adding a new consumer is zero-change to the producer. If a consumer falls behind, events wait in Kafka (for the topic's retention, 7 days by default) — no data loss, no back-pressure on the write path.

Fan-out-on-write vs. fan-out-on-read: which strategy should we use?

Level: Senior

This is the defining design decision for Twitter. Every interviewer will ask about it.

Fan-out-on-write (push model):
When a user posts a tweet, the system immediately writes the tweet ID to every follower's timeline cache. When a follower opens their timeline, the tweets are already pre-computed — the read path is a simple cache lookup.

Fan-out-on-read (pull model):
When a user opens their timeline, the system queries the tweets of every user they follow, merges and sorts them, and returns the result. Nothing is pre-computed.

Push or pull? Twitter does both. Left, FAN-OUT-ON-WRITE (PUSH), where the work happens when a tweet is posted: the AUTHOR's tweet is pushed into the timeline of every follower; writing costs one push per follower, and reading is one list read of a timeline that is already built. Right, FAN-OUT-ON-READ (PULL), where the work happens when a timeline opens: the READER queries the tweets of every followed account and merges them; writing stores the tweet once. Push wins for most accounts, below a threshold such as 100K followers, because reads are 100 times the writes. Pull wins for accounts with millions of followers, where one tweet would mean millions of pushes. The hybrid, which Twitter ran in 2012: push for most accounts, and merge the few celebrities you follow in at read time.

Comparison:

AspectFan-out-on-writeFan-out-on-read
Write costO(N followers) per tweetO(1) per tweet
Read costO(1) — cache lookupO(N following) — merge N feeds
Read latency< 10ms (pre-computed)100-500ms (merge at read time)
Write latencyAsync — author doesn't waitN/A
StorageHigh — duplicate tweet IDs in every follower's cacheLow — store once
Best forMost accounts (below the celebrity threshold, e.g. 100K followers)Celebrities (millions of followers)

Recommendation: Fan-out-on-write for the majority, with a hybrid approach for celebrities. Twitter used exactly this hybrid, as its engineers described in 2012.

Why fan-out-on-write wins for average users

Consider an average user with 200 followers. When they post a tweet:

  • Fan-out-on-write: 200 Redis LPUSH operations (extremely fast — Redis does 100K+ ops/sec per node).
  • Fan-out-on-read: Every time the 200 followers open their timeline, the system queries all 200 accounts' tweets, merges them, and sorts — 200× more reads per timeline load.

With a 100:1 read:write ratio, the math overwhelmingly favors pre-computing timelines at write time. The write cost per tweet (200 cache inserts) is amortized across 100 reads that each cost O(1) instead of O(200).

The celebrity problem: where fan-out-on-write breaks down

Take an account with 80 million followers. A single tweet triggers 80M cache writes. Even at 100K writes/sec per Redis node, that's 800 seconds (over 13 minutes) on one node — or 80 seconds with 10 nodes working in parallel. Meanwhile the fan-out queue backs up behind it, delaying other tweets for millions of users. Twitter saw exactly this: in 2012 a tweet from Lady Gaga (31 million followers then) took up to 5 minutes to reach everyone.

The hybrid approach:

  1. Define a "celebrity threshold" (e.g., users with > 100K followers).
  2. For non-celebrities: fan-out-on-write (push). Tweet IDs are eagerly written to all followers' caches.
  3. For celebrities: fan-out-on-read (pull). The tweet is NOT pushed to follower caches. Instead, when a follower loads their timeline, the Timeline Service:
    • Reads the pre-computed timeline from their cache (non-celebrity tweets).
    • Queries the recent tweets of each celebrity they follow (a handful for most users).
    • Merges the two lists and returns the combined timeline.

This hybrid is what Twitter ran, as Raffi Krikorian, who led Twitter's platform services, described in his talk Timelines at Scale (QCon San Francisco, 2012): the largest accounts were not fanned out but merged into timelines at read time.