Home Interview Design Twitter: System Design Interview Guide
Advanced 3 min · July 13, 2026

Design Twitter: System Design Interview Guide

Master the Design Twitter system design interview question.

N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Notes here come from systems that actually shipped.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic understanding of distributed systems
  • Familiarity with microservices architecture
  • Knowledge of databases (SQL and NoSQL)
  • Understanding of caching and message queues
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • Focus on core features: tweet posting, news feed generation, and user following.
  • Use a hybrid approach: fan-out on write for active users, fan-out on read for celebrities.
  • Key components: API gateway, tweet service, feed service, user service, and notification service.
  • Storage: SQL for user data, NoSQL (Cassandra) for tweets and feeds, Redis for caching.
  • Handle scale with sharding, caching, and asynchronous processing.
✦ Definition~90s read
What is Design Twitter?

Design Twitter is a system design interview question where you architect a scalable social network service that supports posting tweets, following users, and generating personalized news feeds.

Imagine a giant bulletin board where millions of people post sticky notes.
Plain-English First

Imagine a giant bulletin board where millions of people post sticky notes. When you follow someone, you want to see their notes on your personal board. If you follow a celebrity, you can't copy all their notes to your board instantly (too many followers). So, you keep a list of who you follow and fetch their notes when you open your board. For close friends, you pre-copy their notes to your board so it loads fast. That's the trade-off between fan-out on write and fan-out on read.

Designing Twitter is a classic system design interview question that tests your ability to build a real-time, high-scale social network. With over 330 million monthly active users and billions of tweets per day, Twitter must handle massive write and read loads while maintaining low latency. In this guide, we'll walk through a complete system design for Twitter, covering requirements, data models, architecture, and key algorithms. We'll also explore trade-offs like fan-out on write vs. read, caching strategies, and sharding approaches. By the end, you'll be ready to tackle this question in any interview.

1. Requirements and Constraints

Start by clarifying functional and non-functional requirements. Functional: Users can post tweets, follow/unfollow users, view a timeline of tweets from followed users, and like/retweet. Non-functional: Low latency (feed load < 500ms), high availability, scalability to billions of tweets, and eventual consistency for feeds. Estimate scale: 200M daily active users, each posting 0.5 tweets/day = 100M tweets/day. Each user follows 200 on average, so feed generation needs to handle 200 * 100M = 20B fan-out operations daily.

💡Interview Tip
📊 Production Insight
In real Twitter, media uploads are handled by a separate service (Media Platform) to avoid blocking tweet writes.
🎯 Key Takeaway
Define clear functional and non-functional requirements before diving into design.

2. Data Model and Storage

Design the schema. Users table: user_id (PK), name, email, etc. Tweets table: tweet_id (PK), user_id, text, timestamp, media_ids. Follows table: follower_id, followee_id (composite PK). Likes table: user_id, tweet_id (composite PK). For storage, use a relational DB (PostgreSQL) for user data and a NoSQL DB (Cassandra) for tweets and feeds due to high write throughput. Tweets are sharded by user_id to keep all tweets of a user together. Feeds are stored as a list of tweet IDs in Redis for fast retrieval.

schema.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-- Users table
CREATE TABLE users (
  user_id BIGINT PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100)
);

-- Tweets table (sharded by user_id)
CREATE TABLE tweets (
  tweet_id BIGINT,
  user_id BIGINT,
  text VARCHAR(280),
  created_at TIMESTAMP,
  PRIMARY KEY (user_id, tweet_id)
) WITH CLUSTERING ORDER BY (tweet_id DESC);

-- Follows table
CREATE TABLE follows (
  follower_id BIGINT,
  followee_id BIGINT,
  PRIMARY KEY (follower_id, followee_id)
);
🔥Why Cassandra?
📊 Production Insight
Twitter uses Manhattan (in-house) and Flock for graph data, but Cassandra is a common choice for similar systems.
🎯 Key Takeaway
Use a combination of SQL and NoSQL databases to handle different access patterns.

3. High-Level Architecture

The system consists of several microservices: API Gateway, User Service, Tweet Service, Feed Service, Timeline Service, and Notification Service. The API Gateway routes requests and handles authentication. Tweet Service receives new tweets and writes to the database. Feed Service generates timelines using fan-out. Timeline Service serves the feed to users. Notification Service handles push notifications. Communication is asynchronous via message queues (Kafka) for fan-out and notifications.

💡Diagram Tip
📊 Production Insight
Twitter's early monolithic architecture caused frequent outages. Microservices improved reliability.
🎯 Key Takeaway
Microservices architecture with async messaging allows independent scaling and fault isolation.

4. Feed Generation: Fan-out on Write vs. Read

This is the core design decision. Fan-out on write: When a user tweets, pre-compute the feed for all followers by inserting the tweet into each follower's timeline cache. Pros: Fast reads. Cons: Heavy writes for celebrities with millions of followers. Fan-out on read: When a user loads their feed, fetch tweets from all followed users and merge them. Pros: No write amplification. Cons: Slow reads for users following many accounts. Hybrid approach: Use fan-out on write for users with fewer than a threshold (e.g., 10k followers) and fan-out on read for celebrities. This balances load.

fanout.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
def post_tweet(user_id, tweet_content):
    tweet_id = generate_id()
    save_tweet(user_id, tweet_id, tweet_content)
    followers = get_followers(user_id)
    if len(followers) < 10000:
        # Fan-out on write
        for follower_id in followers:
            add_to_feed(follower_id, tweet_id)
    else:
        # Fan-out on read: mark tweet for celebrity
        mark_celebrity_tweet(user_id, tweet_id)
⚠ Trade-off
📊 Production Insight
Twitter uses a similar hybrid approach: 'Earlybird' for real-time search and 'Fanout Service' for timeline generation.
🎯 Key Takeaway
Hybrid fan-out approach optimizes for both read and write performance.

5. Caching Strategy

Cache aggressively to reduce database load. Use Redis for: (1) User sessions, (2) Tweet IDs for each user's timeline (list of tweet IDs), (3) Popular tweets (full objects). Cache-aside pattern: On feed request, check cache; if miss, fetch from DB and populate cache. Set TTL based on recency. For celebrity tweets, cache the list of recent tweets to avoid DB queries on every feed load. Use a distributed cache like Redis Cluster for scalability.

cache.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
def get_feed(user_id):
    feed_key = f"feed:{user_id}"
    tweet_ids = redis.lrange(feed_key, 0, 199)
    if not tweet_ids:
        # Cache miss: fetch from DB
        tweet_ids = fetch_recent_tweets_from_db(user_id)
        redis.rpush(feed_key, *tweet_ids)
        redis.expire(feed_key, 300)  # 5 min TTL
    # Fetch full tweet objects from cache or DB
    tweets = [get_tweet(tid) for tid in tweet_ids]
    return tweets
💡Cache Warm-up
📊 Production Insight
Twitter uses Twemcache (fork of Memcached) and Redis for caching. They also use a custom cache called 'Twemproxy'.
🎯 Key Takeaway
Caching is critical for low-latency feed reads. Use TTL and cache-aside pattern.

6. Sharding and Partitioning

Shard databases to handle scale. For tweets, shard by user_id (hash mod N) to keep all tweets of a user together, enabling efficient retrieval. For follows, shard by follower_id. For likes, shard by tweet_id. Use consistent hashing to minimize rebalancing. For the feed cache, shard by user_id. Each shard is a Redis node. Use a configuration service like ZooKeeper to manage shard mapping.

🔥Shard Key Choice
📊 Production Insight
Twitter uses 'Gizzard' (a sharding framework) and later 'Manhattan' for distributed storage.
🎯 Key Takeaway
Choose shard keys based on access patterns. Consistent hashing helps with scalability.

7. Handling Viral Events and Thundering Herd

When a celebrity tweets, millions of followers need feed updates. Use a message queue (Kafka) to buffer fan-out requests. Workers consume from the queue and update feeds in batches. Implement rate limiting to protect downstream services. For the feed read path, use a 'read-your-writes' consistency model: after posting, the user's own feed is updated immediately via a direct write to cache. For others, eventual consistency is acceptable.

viral.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
def handle_celebrity_tweet(user_id, tweet_id):
    # Publish fan-out job to Kafka
    kafka.produce('fanout', key=user_id, value={'tweet_id': tweet_id})
    # Update own feed immediately
    add_to_feed(user_id, tweet_id)

# Worker
while True:
    msg = kafka.consume('fanout')
    followers = get_followers_batch(msg.user_id, batch_size=1000)
    for follower in followers:
        add_to_feed(follower, msg.tweet_id)
⚠ Thundering Herd
📊 Production Insight
Twitter's 'Fanout Service' uses a priority queue: tweets from celebrities are processed with lower priority to avoid overwhelming the system.
🎯 Key Takeaway
Use async processing and batching to handle viral events gracefully.

8. Timeline Ranking and Relevance

Twitter's timeline is not purely chronological; it uses a ranking algorithm to show relevant tweets first. Factors include recency, engagement (likes, retweets), and user affinity. Implement a scoring function: score = f(recency, engagement, affinity). Store scores in the feed cache along with tweet IDs. When serving the feed, sort by score. For simplicity, you can start with chronological and later add ranking.

ranking.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
def score_tweet(tweet, user):
    recency = (now - tweet.created_at).seconds
    engagement = tweet.likes + tweet.retweets * 2
    affinity = get_affinity(user.id, tweet.user_id)
    return 0.4 * recency + 0.3 * engagement + 0.3 * affinity

def get_ranked_feed(user_id):
    tweet_ids = get_feed_tweet_ids(user_id)
    tweets = [get_tweet(tid) for tid in tweet_ids]
    tweets.sort(key=lambda t: score_tweet(t, user_id), reverse=True)
    return tweets[:200]
💡ML Models
📊 Production Insight
Twitter's 'Home Timeline' uses a machine learning model called 'TwHIN' for ranking.
🎯 Key Takeaway
Ranking improves user engagement. Start with a simple heuristic and iterate.

9. Real-time Updates and Notifications

To support real-time updates, use WebSockets or Server-Sent Events (SSE). When a new tweet is added to a user's feed, push it to the user's active connection. For notifications (likes, retweets), use a separate notification service that listens to Kafka events and sends push notifications via Firebase/APNs. For simplicity, you can use polling with a long timeout, but WebSockets are preferred.

🔥WebSocket vs Polling
📊 Production Insight
Twitter uses a custom real-time service called 'Twist' for streaming tweets to clients.
🎯 Key Takeaway
Real-time updates enhance user experience. Use WebSockets for push and async queues for notifications.

10. Monitoring and Observability

Monitor key metrics: feed load latency, tweet write latency, cache hit ratio, queue depth, and error rates. Use distributed tracing (Jaeger) to debug slow requests. Set up alerts for anomalies. Log all requests for auditing. Implement health checks for each service. Use a dashboard (Grafana) to visualize metrics.

💡Interview Tip
📊 Production Insight
Twitter uses 'Observability Platform' with metrics, traces, and logs aggregated in a central system.
🎯 Key Takeaway
Observability is crucial for maintaining system health. Monitor everything.
● Production incidentPOST-MORTEMseverity: high

The Fail Whale: Twitter's Early Scaling Woes

Symptom
Users saw a 'Fail Whale' image when Twitter was overloaded.
Assumption
The team assumed adding more servers would solve the problem.
Root cause
Monolithic Ruby on Rails app with a single database couldn't handle viral events.
Fix
Rewrote key services (tweet, user, timeline) in Scala and Java, introduced sharding and caching.
Key lesson
  • Plan for viral spikes from the start.
  • Use asynchronous processing for heavy operations like feed fan-out.
  • Shard databases to distribute load.
  • Cache aggressively to reduce database reads.
  • Monitor and auto-scale based on traffic patterns.
Production debug guideSymptom to Action4 entries
Symptom · 01
High latency for news feed loading
Fix
Check cache hit ratio for feed cache; if low, increase cache size or precompute feeds for active users.
Symptom · 02
Tweets not appearing in followers' feeds
Fix
Verify fan-out job queue; check for backpressure or failures in the feed generation service.
Symptom · 03
Database write spikes during peak hours
Fix
Implement write batching and shard by user ID to distribute load.
Symptom · 04
Inconsistent feed ordering
Fix
Ensure timeline service uses consistent timestamps and consider using a distributed counter for ranking.
★ Quick Debug Cheat SheetCommon issues and immediate actions for Twitter system design.
Feed loading slow
Immediate action
Check Redis cache for feed data
Commands
redis-cli GET user:123:feed
curl -X GET http://feed-service/v1/feed?userId=123
Fix now
Increase cache TTL or precompute feed for active users.
Tweet not appearing+
Immediate action
Check tweet service logs
Commands
kubectl logs -l app=tweet-service --tail=100
curl -X POST http://tweet-service/v1/tweet -d '{"userId":"123","text":"hello"}'
Fix now
Restart tweet service if down; check database connectivity.
High database CPU+
Immediate action
Identify slow queries
Commands
SHOW FULL PROCESSLIST;
EXPLAIN SELECT * FROM tweets WHERE user_id = 123;
Fix now
Add index on user_id and created_at; consider read replicas.
ApproachWrite LatencyRead LatencyScalabilityComplexity
Fan-out on WriteHigh (for celebrities)LowLimited by write capacityMedium
Fan-out on ReadLowHigh (for many follows)HighLow
HybridMediumLowHighHigh
⚙ Quick Reference
5 commands from this guide
FileCommand / CodePurpose
schema.sqlCREATE TABLE users (2. Data Model and Storage
fanout.pydef post_tweet(user_id, tweet_content):4. Feed Generation
cache.pydef get_feed(user_id):5. Caching Strategy
viral.pydef handle_celebrity_tweet(user_id, tweet_id):7. Handling Viral Events and Thundering Herd
ranking.pydef score_tweet(tweet, user):8. Timeline Ranking and Relevance

Key takeaways

1
Start with clear requirements and scale estimates.
2
Use a hybrid fan-out approach for feed generation.
3
Cache aggressively and shard databases for scalability.
4
Handle viral events with async processing and rate limiting.
5
Monitor everything and plan for failure.

Common mistakes to avoid

3 patterns
×

Ignoring the scale of celebrity tweets

×

Using a single database for all data

×

Not considering caching

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
Design Twitter's news feed generation system. Compare fan-out on write v...
Q02SENIOR
How would you handle a celebrity with 10 million followers tweeting simu...
Q03SENIOR
Design the database schema for Twitter. Explain your choice of database.
Q01 of 03SENIOR

Design Twitter's news feed generation system. Compare fan-out on write vs. fan-out on read.

ANSWER
Fan-out on write pre-computes feeds when a tweet is posted, leading to fast reads but heavy writes for celebrities. Fan-out on read computes feeds on demand, leading to fast writes but slow reads. A hybrid approach uses fan-out on write for users with few followers and fan-out on read for celebrities.
FAQ · 3 QUESTIONS

Frequently Asked Questions

01
How do you handle tweet deletion?
02
What if a user follows thousands of accounts?
03
How do you ensure eventual consistency for feeds?
N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Notes here come from systems that actually shipped.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's System Design Interview. Mark it forged?

3 min read · try the examples if you haven't

Previous
Design Uber: System Design Interview
11 / 12 · System Design Interview
Next
Design a Rate Limiter: System Design Interview