Designing Twitter's home timeline is a rite of passage in system design interviews. It perfectly encapsulates the challenges of building a read-heavy, high-throughput system where data is highly interconnected. The core of this problem isn't just storing text; it's efficiently delivering that text to millions of followers in near real-time. In this guide, we will break down the architecture, focusing heavily on the infamous "fan-out" problem and the caching strategies required to make the timeline feel instantaneous.
Requirements (functional and non-functional)
Before jumping into boxes and arrows, we must align with the interviewer on what exactly we are building. Twitter is a massive platform, so we need to aggressively scope the problem down to the core timeline experience.
Functional Requirements
- Publish Tweet: A user should be able to post a text-based tweet (we will ignore media/video for simplicity in this core design).
- View Timeline: A user should be able to view their home timeline, which consists of tweets from the people they follow, sorted in reverse chronological order.
- Follow/Unfollow: Users can follow or unfollow other users.
Non-functional Requirements
- High Availability: The system must be highly available. It's better to show slightly stale data than no data at all.
- Low Latency Reads: Timeline generation must be lightning fast (under 200ms). Users expect immediate feedback when they open the app.
- Eventual Consistency: When a user tweets, it is acceptable if it takes a few seconds (or slightly longer for celebrities) to appear in all their followers' timelines.
- Scale: The system must handle massive read-heavy traffic and sudden spikes (e.g., during the Super Bowl or breaking news).
Capacity estimates
Let's establish some concrete numbers to understand the scale. We will state our assumptions clearly.
- Daily Active Users (DAU): 300 million.
- Read/Write Ratio: Twitter is heavily read-biased. Let's assume an average user reads their timeline 5 times a day and fetches 20 tweets per read (100 tweets read/day). Let's assume users post an average of 2 tweets per day.
- Writes (Tweets): 300M * 2 = 600 million tweets per day.
- Reads (Timeline loads): 300M * 5 = 1.5 billion timeline requests per day.
Throughput (QPS):
- Write QPS: 600M / 86,400 seconds ≈ 7,000 QPS.
- Read QPS: 1.5B / 86,400 seconds ≈ 17,300 QPS.
- Peak QPS: Traffic is not uniform. We should design for a peak of at least 3x to 5x the average. So, ~35,000 Write QPS and ~85,000 Read QPS.
Storage:
- Assume a tweet object (text, metadata, IDs) is about 1 KB.
- 600M tweets * 1 KB = 600 GB per day.
- In a year, this is roughly 219 TB. While significant, this is easily manageable with modern distributed databases.
API design
We need three primary endpoints to satisfy our functional requirements. We'll use a RESTful approach.
| Endpoint | Method | Request Body / Params | Description |
|---|---|---|---|
/v1/tweets | POST | {"text": "Hello world!"} | Publishes a new tweet for the authenticated user. Returns the created Tweet object. |
/v1/timeline | GET | ?cursor=12345&limit=20 | Fetches the home timeline. Returns a list of Tweet objects and a next_cursor. |
/v1/follow | POST | {"target_user_id": "987"} | Follows a specific user. |
Data model
We need to store Users, Follow relationships (the social graph), and Tweets. Given the scale, we will use a mix of relational and NoSQL concepts, but for the source of truth, a distributed NoSQL database (like Cassandra or DynamoDB) or a heavily sharded RDBMS (like MySQL) works well.
1. Users Table
user_id(Primary Key, Snowflake ID)username(String, Indexed)email,password_hash,created_at
2. Tweets Table
tweet_id(Primary Key, Snowflake ID - sortable by time)user_id(Foreign Key, Indexed to fetch a user's tweets quickly)text(String)created_at(Timestamp)
3. Social Graph (Followers/Following) Table To efficiently query both "Who does user A follow?" and "Who follows user A?", we often need two tables or a graph database.
- Followers Table: Primary Key
(followee_id, follower_id). Used to find all followers of a user (crucial for fan-out). - Following Table: Primary Key
(follower_id, followee_id). Used to find everyone a user follows.
High-level architecture
Here is the high-level flow of how a tweet goes from being published to appearing on a follower's screen.
Write Path (Publishing a Tweet):
- The client sends a
POST /v1/tweetsrequest. - The Tweet Service saves the tweet to the Tweet DB (source of truth).
- The Tweet Service pushes an event (containing the
tweet_idanduser_id) to a message queue like Kafka. - The Fan-out Service consumes this event, asks the Graph Service for the user's followers, and pushes the
tweet_idinto the Timeline Redis Cache of each follower.
Read Path (Viewing Timeline):
- The client sends a
GET /v1/timelinerequest. - The Timeline Service queries the user's Timeline Redis Cache to get a list of
tweet_ids. - It then fetches the actual tweet content for those IDs from the Tweet Object Cache (falling back to the DB if missing).
- The fully hydrated tweets are returned to the client.
Deep dives
1. The Fan-out Problem (Push vs. Pull vs. Hybrid)
This is the most critical part of the Twitter interview. "Fan-out" refers to the process of delivering a message to multiple destinations. How do we generate the timeline?
Approach A: Fan-out on Write (Push Model) When User A tweets, we immediately fetch all their followers and push the tweet ID into each follower's pre-computed timeline cache (usually a Redis List or Sorted Set).
- Pros: Reads are incredibly fast. The Timeline Service just does an O(1) or O(log N) fetch from Redis.
- Cons: The "Justin Bieber" problem. If a celebrity with 100 million followers tweets, we have to update 100 million Redis caches. This takes time, causes massive spikes in write operations, and delays the tweet's appearance (high eventual consistency latency).
Approach B: Fan-out on Read (Pull Model) We don't pre-compute anything. When User B opens their app, the system fetches all the people User B follows, gets the latest tweets for each of them, merges them, sorts them, and returns the result.
- Pros: Writes are instantaneous. No massive background processing.
- Cons: Reads are painfully slow. Doing this heavy aggregation on the fly for every single timeline load will crush the database and result in unacceptable latency.
The Solution: The Hybrid Approach Twitter uses a hybrid model. We categorize users into two buckets: Active/Normal Users and Celebrities (High-follower users).
- For Normal Users (e.g., < 100k followers): We use Fan-out on Write. When they tweet, we push the tweet ID to their followers' caches.
- For Celebrities (e.g., > 100k followers): We use Fan-out on Read. When a celebrity tweets, we do not push it to 100 million caches. We just save it to their personal "User Timeline" cache.
- The Merge: When a user loads their home timeline, the Timeline Service fetches their pre-computed cache (which contains tweets from normal users). It then checks if the user follows any celebrities. If so, it pulls the latest tweets directly from those celebrities' caches, merges them with the pre-computed timeline in memory, sorts them by timestamp, and returns the result.
Here is how you might implement the Hybrid Timeline fetch logic:
def get_home_timeline(user_id, cursor, limit):
# 1. Fetch pre-computed timeline (Normal users' tweets)
normal_tweets = redis.zrevrangebyscore(
f"timeline:{user_id}", max=cursor, min="-inf", start=0, num=limit
)
# 2. Fetch celebrities the user follows
celebrity_ids = graph_service.get_followed_celebrities(user_id)
# 3. Pull latest tweets from those celebrities
celeb_tweets = []
for celeb_id in celebrity_ids:
celeb_tweets.extend(
redis.zrevrangebyscore(
f"user_timeline:{celeb_id}", max=cursor, min="-inf", start=0, num=limit
)
)
# 4. Merge, sort by timestamp (descending), and take top 'limit'
all_tweets = normal_tweets + celeb_tweets
all_tweets.sort(key=lambda x: x.timestamp, reverse=True)
return all_tweets[:limit]2. Caching Strategy and Memory Optimization
Storing timelines for 300 million users in Redis requires massive amounts of RAM. We cannot store the entire history of a user's feed in memory. We must optimize.
- Cache only active users: If a user hasn't logged in for 14 days, we evict their timeline from Redis. If they log in on day 15, we experience a cache miss, synchronously rebuild their timeline from the database (Fan-out on Read), and put it back in Redis.
- Cap the timeline length: We only store the latest 800 tweets in the Redis timeline cache. If a user scrolls past 800 tweets (which is rare), we fall back to querying the database.
- Store IDs, not objects: The Timeline Cache should only store
tweet_ids (and timestamps for sorting). We use a separateTweet Object Cache(often Memcached or a separate Redis cluster) to store the actual text and metadata. This allows deduplication; if 100 users have the same retweet in their timeline, the heavy text payload is only stored once in the Object Cache.
Bottlenecks and trade-offs
- Zombie Followers: A significant portion of a user's followers might be inactive accounts. Pushing tweets to inactive users' caches wastes CPU and memory. Trade-off: We filter out inactive users during the fan-out phase. The Graph Service must keep track of the last login time of followers.
- Hot Partitions: If a celebrity's tweet goes viral, the
Tweet Object Cachenode holding that specific tweet will get hammered with reads. Trade-off: We can mitigate this by caching extremely hot tweets in the application memory (local cache) of the Timeline Service itself, bypassing Redis entirely for the most viral content. - Eventual Consistency during Fan-out: The Kafka queue processing the fan-out can lag during peak traffic (e.g., New Year's Eve). Trade-off: We accept this. It is better for a tweet to show up 30 seconds late than for the entire system to crash. We can scale the Fan-out workers horizontally to drain the queue faster.
Questions an interviewer will ask next
1. What happens if the Redis cluster storing timelines goes down? Answer: We need a fallback mechanism. If Redis fails, the Timeline Service must query the underlying database (pull model). However, this will be extremely slow. To prevent cascading failures, we must implement circuit breakers and rate limiting, potentially serving degraded experiences (e.g., only showing celebrity tweets or cached global trends) until Redis recovers.
2. How would you handle retweets?
Answer: A retweet is essentially a pointer. We can create a new Tweet object with its own ID, but its content is just a reference to the original tweet_id. In the timeline cache, we store the retweet's ID. When hydrating, the client or Gateway resolves the pointer to display the original content.
3. How do you transition this to an algorithmic (ranked) timeline? Answer: Fan-out on write becomes less useful. Instead of pre-computing a perfectly sorted list, we pre-fetch a "pool" of candidate tweets (e.g., the last 500 tweets from followed users). We then pass this pool to a Machine Learning ranking service that scores each tweet based on user affinity, engagement probability, and recency, before returning the top 20 to the user.