Design Twitter
Understanding the Problem
🐦 What is Twitter? Twitter (now X) is a social network built around short public posts called tweets. You follow other accounts, and your home timeline shows their tweets, newest first. The follow graph is one-directional: you can follow someone without them following you back, which is why a handful of accounts end up with tens of millions of followers.
The interesting part of this problem isn't storing 280 characters. It's building every user's home timeline, which is a different view of the data for each of hundreds of millions of people, and doing it fast enough that opening the app feels instant.
Functional Requirements
Twitter has a long tail of features. Agree early with your interviewer that we're designing the core loop: post, follow, read.
Core Requirements
- Users should be able to post a tweet: up to 280 characters of text, optionally with images or a video.
- Users should be able to follow and unfollow other users.
- Users should be able to view their home timeline: tweets from the people they follow, newest first, with paging as they scroll.
- Users should be able to view a user's profile timeline: that one user's tweets, newest first.
Below the line (out of scope)
- Likes, retweets and replies (we'll touch on counts where they affect reads).
- Search, trends and hashtags.
- A machine-learned "For You" ranking. We'll build the chronological timeline, which is also the candidate source a ranker would sit on top of.
- Direct messages, notifications and ads.
Non-Functional Requirements
Ask your interviewer for the scale. We'll assume 300 million daily active users, 100 million new tweets a day, and that the average user opens their timeline around 10 times a day.
Core Requirements
- The system should return a home timeline in under 200ms at p99.
- The system should be highly available. We prefer showing a slightly stale timeline over showing an error, so we accept eventual consistency: a new tweet can take a few seconds to reach followers.
- The system should scale to 100M tweets a day and around 35k timeline reads per second on average, several times that at peak.
- The system should handle very skewed follower counts, including accounts with 100M+ followers.
- Tweets must be durable. Once a user sees "posted", the tweet is not lost.
Below the line (out of scope)
- Strict ordering across followers. If two followers see the same tweet a second apart, that's fine.
- Multi-region write conflicts. Tweets are immutable once posted, which makes replication across regions straightforward.
A little arithmetic shapes everything that follows:
- Writes: 100M tweets / 86,400s ≈ 1,200 tweets/s, peaking at maybe 5-10k/s during big live events.
- Reads: 300M users × 10 opens = 3B timeline loads a day ≈ 35k reads/s, peaking well above 100k/s. Reads outnumber writes about 30 to 1.
- Fan-out: if the average tweet goes to ~200 followers, delivering every tweet to every follower's timeline is 100M × 200 = 20B timeline inserts a day, about 230k/s on average.
- Storage: a tweet with metadata is around 300 bytes, so text is about 30GB a day, roughly 11TB a year. Media dwarfs that and lives in object storage.
The read-heavy ratio says we should do work at write time to make reads cheap. The fan-out number says that's affordable on average. The 100M-follower accounts say the average is lying, and we'll need a plan for the tail.
The single most important observation in this problem: a home timeline is a join between the follow graph and the tweet table, and computing that join on every read is what we're trying to avoid. Everything else is a detail.
The Set Up
Planning the Approach
We'll build the simple version of each requirement first, including a home timeline that's computed on read. Then the deep dives fix its performance: precomputed timelines, the celebrity problem, storage, and keeping timelines correct when the graph changes.
Defining the Core Entities
- User: an account, with a handle, display name and profile data. We also keep follower and following counts on it.
- Tweet: an immutable post with an ID, author ID, text, optional media references and a creation time.
- Follow: a directed edge from a follower to a followee, with a timestamp.
- Timeline: a user's home feed, an ordered list of tweet IDs. It's derived data: we can always rebuild it from Follows and Tweets.
Calling out that the Timeline is derived matters. It means we can store it in a cache, lose it, and rebuild it, rather than treating it as a source of truth that needs replication and backups.
API or System Interface
POST /tweets
{ text, mediaIds? }
-> 201 { tweetId, createdAt }
POST /users/{userId}/follow
DELETE /users/{userId}/follow
-> 204
GET /timeline?cursor={tweetId}&limit=50
-> { tweets: [ { tweetId, author, text, media, createdAt, likeCount } ], nextCursor }
GET /users/{userId}/tweets?cursor={tweetId}&limit=50
-> { tweets: [...], nextCursor }
The acting user comes from the auth token. Paging uses a cursor (the last tweet ID the client saw), not an offset. New tweets arrive at the top of the timeline constantly, so offset=50 would skip or repeat tweets as the list shifts underneath the reader.
High-Level Design
1) Users should be able to post a tweet
A client sends the tweet to an API gateway, which authenticates the user and routes to a Tweet Service. The service validates the text, assigns an ID, writes the tweet to the Tweet Store, and returns.
For IDs we want something unique across many servers and roughly sorted by time, so "newest first" is just "highest ID first." A Snowflake-style 64-bit ID does this: 41 bits of milliseconds since an epoch, 10 bits of worker ID, 12 bits of per-millisecond sequence. Each Tweet Service instance generates IDs locally without coordination. See /system-design/unique-id-generator for the details.
Media doesn't go through the Tweet Service. The client first asks for a pre-signed upload URL, uploads the image or video straight to object storage (S3), and then posts the tweet with the returned mediaIds. Followers load media from a CDN. This keeps large binary uploads off our API servers entirely.
For the Tweet Store, the access pattern is simple: write once, read by ID, and read "this user's recent tweets." There are no joins and no multi-row transactions. A wide-column store like Cassandra or a key-value store like DynamoDB fits well, and it shards horizontally as we add 11TB a year.
2) Users should be able to follow and unfollow other users
A Follow Service writes the edge. The graph is queried in two directions, and we want both to be a single-partition read:
- "Who does Alice follow?" is needed to build Alice's timeline.
- "Who follows Alice?" is needed to deliver Alice's tweets.
So we store each edge twice, once in each direction:
following: partition key = follower_id, sort key = followee_id -> who I follow
followers: partition key = followee_id, sort key = follower_id -> who follows me
A follow writes both rows and increments two counters (Alice's following count, Bob's follower count). With DynamoDB the two edge writes can go in one transaction; with Cassandra a logged batch covers both rows. Counts can lag by a moment, so they're updated asynchronously.
We don't need a graph database here. Every query is one hop ("my followees", "my followers"), and a partitioned edge list does one-hop queries perfectly well. Graph databases earn their keep on multi-hop traversals like "friends of friends", which this design doesn't need.
3) Users should be able to view their home timeline
The simplest correct version computes the timeline when it's requested, often called fan-out on read or the pull model:
- The Timeline Service asks the Follow Service for everyone Alice follows (say 300 IDs).
- It queries the Tweet Store for the recent tweets of each followee.
- It merges the results by tweet ID, newest first, and returns the top 50.
SELECT * FROM tweets
WHERE author_id IN (:followee_ids) -- 300 IDs
AND tweet_id < :cursor
ORDER BY tweet_id DESC
LIMIT 50;
This works, and for a small site it's what you should build. At our scale it has two problems. First, the IN list touches up to 300 partitions spread across the cluster, so one timeline load becomes hundreds of storage reads, and the p99 is set by the slowest of them. At 35k timeline loads a second, that's on the order of 10M partition reads a second. Second, the work is repeated: Alice opens the app 10 times a day and we redo the same join each time, though only a handful of new tweets arrived in between.
4) Users should be able to view a user's profile timeline
This one is easy once the Tweet Store is keyed well. We keep a user_tweets table partitioned by author_id and clustered by tweet_id descending. "Bob's tweets, newest first, after this cursor" is a single-partition range scan:
SELECT tweet_id FROM user_tweets
WHERE author_id = :bob AND tweet_id < :cursor
ORDER BY tweet_id DESC LIMIT 50;
The Timeline Service then fetches the tweet bodies by ID. Profile pages for popular accounts are read millions of times, so we also cache each user's most recent tweet IDs in Redis. That same per-author cache will come back in the celebrity deep dive.
Potential Deep Dives
1) How do we make home timeline reads fast?
We need p99 under 200ms at 100k+ reads a second, and the pull model's scatter-gather won't get there.
Bad Solution: Pull From the Database With Better Indexes
Approach
Keep computing the timeline on read, but add read replicas and make sure the per-author query uses the (author_id, tweet_id) index.
Challenges
Indexes make each partition read fast, but they don't change the number of reads. A user who follows 2,000 accounts still costs 2,000 partition reads per page, and adding replicas just spreads the same wasted work over more machines. Latency is dominated by the slowest of hundreds of parallel requests, which is exactly the tail behavior a 200ms p99 can't absorb.
Good Solution: Pull From a Cache of Recent Tweets per Author
Approach
Keep a Redis list of each author's last ~100 tweet IDs (we already have it for profile pages). The Timeline Service fetches the followee list, then does a pipelined multi-get against Redis for each followee's list, merges in memory, and hydrates the top 50.
Challenges
Memory reads are much faster than disk, so this is a real improvement, and it has a nice property: posting is cheap, since a tweet is written to exactly one author list. But the read still fans out to hundreds of keys across many Redis shards, and merging 300 lists of 100 IDs on every request costs CPU. It scales with the number of accounts you follow, which is the wrong variable: power users who follow thousands of accounts get the slowest timelines.
Great Solution: Precompute Timelines With Fan-out on Write
Approach
Flip the work to write time. When Bob tweets, we push the tweet ID into the home timeline of every one of his followers. Reading Alice's timeline becomes one lookup of one key.
The write path:
- The Tweet Service stores the tweet and publishes a
TweetCreatedevent to Kafka. - Fan-out workers consume the event, page through Bob's
followerspartition, and for each follower append the tweet ID to that follower's timeline cache entry. - Each timeline is a Redis list of tweet IDs, capped at the most recent ~800 entries.
LPUSH timeline:{followerId} {tweetId}
LTRIM timeline:{followerId} 0 799
Workers batch these commands with pipelining, grouping followers that live on the same Redis shard.
The read path:
- Read
timeline:{alice}, a few kilobytes of IDs. - Slice the page after the cursor.
- Hydrate: multi-get the 50 tweet bodies from a tweet cache (Memcached or Redis, keyed by tweet ID), plus author profiles and counts, falling back to the Tweet Store on a miss.
The timeline cache only stores IDs, not tweet bodies. That keeps it small and means a tweet edit, a deleted tweet or a changed display name shows up correctly, because bodies are looked up fresh at read time.
Size check: 300M active users × 800 IDs × 8 bytes ≈ 2TB of raw IDs. With Redis overhead and replicas, plan for several terabytes of RAM across a cluster of large nodes. That's a real cost but an ordinary one.
Challenges
Writes are now amplified by follower count: 20B inserts a day, which the cache cluster handles, but they have to be spread evenly. Delivery is asynchronous, so a follower may see the tweet a few seconds late. That's within our consistency requirement, but the author should see their own tweet at once, so the Tweet Service writes it into the author's own timeline synchronously (or the client inserts it locally). The big remaining problem is accounts with 100M followers, which is the next deep dive.
If you store timelines in a Redis sorted set instead of a list, watch the score. Scores are 64-bit doubles, which hold integers exactly only up to 2^53, and a Snowflake ID is bigger than that. Use the millisecond timestamp as the score and the ID as the member, or just use a capped list.
2) How do we handle celebrities with millions of followers?
With fan-out on write, one tweet from an account with 100M followers means 100M cache writes. Even at a million writes a second across the fan-out fleet, that's over a minute and a half of work for one tweet. Those accounts tend to tweet during big events, exactly when everyone else is tweeting too.
Bad Solution: Fan Out to Everyone Anyway
Approach
Treat every account the same. Fan-out workers grind through the celebrity's follower list like any other.
Challenges
The queue backs up behind one giant job, so ordinary users' tweets take minutes to arrive. Followers see the celebrity's tweet at wildly different times, so the replies show up before the tweet for many of them. And much of the work is wasted: a large share of those 100M followers won't open the app before the tweet scrolls out of their 800-entry window.
Good Solution: Async Fan-out With Priorities and Chunking
Approach
Split big fan-outs into chunks of, say, 10,000 followers each, put them on a separate low-priority Kafka topic, and run them on their own pool of workers. Normal users' fan-outs stay on the fast topic and aren't delayed. Within a big fan-out, deliver to recently active followers first.
Challenges
It isolates the damage but doesn't reduce it. We still do 100M writes per celebrity tweet and pay for the capacity, and followers at the back of the line still get the tweet minutes late.
Great Solution: Hybrid Push and Pull
Approach
Don't fan out for accounts above a follower threshold (say 100k followers). Their tweets are written only to their own per-author cache, the same user_tweets:{authorId} list we use for profile pages. At read time, the Timeline Service merges two sources:
- Alice's precomputed timeline (pushed tweets from normal accounts).
- The recent tweets of the celebrities Alice follows, pulled from their per-author caches.
Alice probably follows a few dozen celebrities at most, so that's a small, bounded pull. And because millions of people read the same celebrity's list, it's always hot in cache.
pushed = LRANGE timeline:{alice} 0 799
celebs = celebrity_followees(alice) // cached, usually < 50 IDs
pulled = for c in celebs: LRANGE user_tweets:{c} 0 99 (pipelined)
page = merge_desc(pushed, pulled) after cursor, take 50
Challenges
Reads are a little more complex, and the merge has to be correct with cursors: we page by tweet ID, so both sources are filtered by tweetId < cursor before merging. The threshold needs hysteresis. An account crossing 100k followers shouldn't flip modes back and forth, so we switch at 100k and switch back below, say, 80k. When an account becomes a celebrity, its old tweets are already pushed and new ones are pulled, which merges cleanly because the merge deduplicates by ID.
This is the answer interviewers are looking for. You get there by noticing that push is cheap when follower count is small and pull is cheap when followee count is small, and that celebrity accounts are rare on both sides.
3) How do we store tweets and the follow graph at scale?
Tweets. We partition the Tweet Store by tweet_id, which spreads writes evenly, and keep the user_tweets index partitioned by author_id. A very prolific author's partition grows forever, so we bucket it by time: (author_id, month). Tweets are immutable apart from deletes, so replicas never conflict and we can replicate asynchronously to other regions. Cassandra with replication factor 3 and QUORUM writes gives us durability without a single primary to fail over.
Media. Images and videos go to S3 under a content-addressed key, are transcoded into a few sizes by an async pipeline, and are served through a CDN. The tweet row only stores media IDs.
The follow graph. The following table is small per user (most people follow a few hundred accounts). The followers table is where skew hurts: a 100M-follower account has a 100M-row partition. At roughly 20 bytes per row that's about 2GB, far beyond what a single Cassandra partition should hold, and a hot spot for every read. We split big followee partitions into buckets, (followee_id, bucket), with the bucket derived from a hash of follower_id. Fan-out workers then read the buckets in parallel. With the hybrid model, the largest follower lists are rarely read by fan-out anyway, only for things like notifications.
Counts. Follower counts and like counts are read on every hydrated tweet but change constantly. We keep them in a counter store (Redis or a sharded counter table), updated from events, and accept that they lag by a second or two.
Timelines. The timeline cache is derived data, so we don't back it up. If a Redis shard dies, its replica takes over. If both are lost, timelines on that shard are rebuilt on the next read with the pull model, which is slower for those users but correct.
4) How do timelines stay correct when the graph or the tweets change?
A precomputed timeline is a cache of a join, and the join's inputs keep changing. Each change needs a rule:
- Follow. Alice follows Bob, but her timeline has none of Bob's old tweets. We backfill: read Bob's last ~20 tweets from his per-author cache and merge them into Alice's timeline. It's a small, one-off job on the follow event.
- Unfollow. We could remove Bob's tweet IDs from Alice's list, but that means scanning 800 entries and we don't store the author in the list. A cheaper approach is to filter at read time: hydration already loads the author of each tweet, so we drop tweets from authors Alice no longer follows, and an async job cleans the list up later.
- Delete. The tweet row is marked deleted. Hydration skips deleted tweets, so they disappear from every timeline at once without touching 100M lists. Pages may come back with 49 tweets instead of 50; the client just asks for the next page.
- Blocks and protected accounts. Same idea: a read-time filter for correctness, with async cleanup for tidiness.
- Inactive users. On a large account, a meaningful share of followers haven't opened the app in a month. Fan-out workers skip users who've been inactive for, say, 30 days, which cuts write volume a lot. When an inactive user comes back, their timeline is missing or stale, so we rebuild it with the pull model once and then let fan-out keep it fresh.
The pattern is the same each time: precomputation for speed, a filter at read time for correctness, and the pull model as the fallback that can always rebuild the truth.
5) How do we handle hot tweets and traffic spikes?
During a big event, two things spike at once: tweet volume and reads of a few viral tweets.
Tweet volume. Kafka absorbs bursts between the Tweet Service and the fan-out workers. If workers fall behind, timelines lag by seconds, but posting stays fast and nothing is lost. We autoscale fan-out workers on consumer lag, which is a much better signal than CPU.
Hot tweets. A viral tweet is hydrated by millions of timeline reads, so a single key in the tweet cache gets hammered, and that key lives on one shard. We keep a small in-process cache (a few seconds of TTL) on each Timeline Service instance for the hottest tweet bodies, which removes most of those reads before they leave the box. For keys that are still too hot, we can replicate them under several suffixes (tweet:{id}#0..7) and have readers pick one at random.
Counts on hot tweets. A viral tweet gets thousands of likes a second, all incrementing the same counter. We buffer increments in the service and flush aggregated deltas every second, or shard the counter. See /system-design/likes-counter for that problem in depth.
Final Design
The main flows:
- A user posts a tweet. The Tweet Service assigns a Snowflake ID, writes the tweet to the Tweet Store and the author's
user_tweetscache, and publishesTweetCreatedto Kafka. Media was already uploaded to S3 via a pre-signed URL. - Fan-out workers consume the event. For a normal author, they page through the follower buckets, skip inactive followers, and push the tweet ID into each follower's capped timeline list in Redis. For a celebrity, they do nothing.
- A user opens the app. The Timeline Service reads their precomputed timeline, pulls recent tweets from the celebrities they follow, merges by ID after the cursor and takes 50.
- It hydrates those IDs from the tweet cache and counter store, filters deleted tweets and unfollowed or blocked authors, and returns the page. Media loads from the CDN.
- Follows and unfollows update both edge tables, backfill or filter timelines, and change which celebrity lists a reader pulls from.
What is Expected at Each Level?
Mid-level
You should get to a working design with sensible entities and APIs, store follows in both directions, and recognize that computing the timeline from scratch on every read is too slow. With some guidance, you should arrive at precomputed timelines with fan-out on write, and when the interviewer brings up celebrities, you should see why that breaks for accounts with huge follower counts.
Senior
You should lead with the read/write ratio and the fan-out arithmetic, and reach the hybrid push/pull model mostly on your own. Expect to explain why timelines store IDs and hydrate at read time, how cursors work across the merged sources, and how Kafka decouples posting from delivery. You should handle follow, unfollow and delete without hand-waving, and size the timeline cache.
Staff+
You should treat the timeline as a derived, rebuildable cache and design for that: what's durable, what's lost on failure, and how it's rebuilt. Expect to go deep on skew: celebrity thresholds with hysteresis, bucketed follower partitions, hot-key mitigation and skipping inactive users, with numbers behind each. You should also know where the chronological timeline ends and a ranked one begins, and how this design becomes the candidate-retrieval stage for a ranker without being rebuilt.