System Design
Case Study: Twitter
Requirements
Functional
- Post tweets (280 chars)
- Follow users
- Timeline (home feed)
- Search tweets
Scale
- 500M users
- 200M DAU
- 500M tweets/day
- 100B timeline requests/day
Core Challenge: Timeline
Problem: User’ning timeline’ini qanday generate qilish?
Approach 1: Pull (Read-time)
-- User timeline request
SELECT tweets.* FROM tweets
JOIN follows ON follows.following_id = tweets.user_id
WHERE follows.follower_id = {current_user}
ORDER BY created_at DESC
LIMIT 20;
Slow: Million followers = heavy query
Approach 2: Push (Write-time)
// User posts tweet
async function postTweet(userId, content) {
const tweet = await db.saveTweet(userId, content);
const followers = await db.getFollowers(userId);
// Fan out to all followers
for (const followerId of followers) {
await redis.lPush(`timeline:${followerId}`, tweet.id);
}
}
Celebrity problem: 100M followers = 100M writes!
Hybrid Approach (Twitter actual)
Normal users (< 1M followers): Push model
Celebrities (> 1M followers): Pull model
Timeline = Precomputed + Celebrity tweets merged
Architecture
Write Path:
Tweet → API → Fanout Service → Redis (timelines)
→ Cassandra (tweet storage)
Read Path:
Timeline request → Redis (precomputed)
→ Merge celebrity tweets
→ Return
Keyingi dars: WhatsApp loyihalash.