FUNCTIONAL
- Compose/post a tweet: text up to 280 chars + optional media (image/video)
- Home timeline: see tweets from the accounts I follow
- Follow / unfollow other users
- Like / unlike (favorite) a tweet
- View a user's profile timeline
- Delete my own tweet
NON-FUNCTIONAL
- Fast response: feed load should feel instant (~sub-200ms p99); writes acknowledge quickly
- High availability: the feed must stay readable during peak load, degrading to staler/slower rather than failing
- Scales to a large audience: horizontal scaling, partitioned data, no single point of failure for federated reads
- Read-heavy: reads greatly outnumber writes, so the read path is what we optimize
- Eventual consistency is acceptable for timelines (a follower may see a new tweet a few seconds late)
- Media stored durably in object storage and served via CDN, never through the app servers
OUT OF SCOPE
DMs, ads, search/trending, ranking ML, retweets/replies threading, notifications
CAPACITY ESTIMATION
ASSUMPTIONS
500M DAU, 2 tweets per user per day, 10 feed loads per user per day,
20 tweets per feed page, 200 average followers per user, 3x peak factor.
WRITES
500M x 2 = 1B tweets/day / 86,400 s = ~12k tweets/s; 3x peak = ~35k/s
READS
500M x 10 = 5B feed loads/day / 86,400 s = ~58k loads/s; 3x peak = ~175k/s
Each load hydrates 20 tweets: 58k x 20 = ~1.16M tweet fetches/s (peak ~3.5M/s)
FAN-OUT (the number that drives the design)
1B tweets/day x 200 followers = 200B timeline inserts/day / 86,400 s = ~2.3M/s;
3x peak = ~7M/s
STORAGE
Tweet text/row ~300B: 1B x 300B = 300GB/day -> x365 = ~110TB/yr raw;
x3 replication = ~330TB/yr
Media: 10% of 1B = 100M uploads/day x 300KB = 30TB/day -> ~11PB/yr (object store + CDN)
TOP-K TIMELINE CACHE
500M users x 800 tweet_ids x 8B = 3.2TB RAM -> feasible on a Redis cluster
(~100 nodes x 32GB), which is why we precompute rather than assemble on read
CONCLUSION: 7M fan-out writes/s rules out synchronous fan-out on write.
We need async fan-out plus a hybrid for high-follower accounts.
POST /v1/tweets
body {text, media_ids[]} -> {tweet_id, created_at}
DELETE /v1/tweets/{tweet_id}
-> 204
GET /v1/feed?limit=20&cursor={opaque}
-> {tweets:[{tweet_id, author, text, media_url, like_count, created_at}],
next_cursor}
cursor-based (not offset) so new tweets don't cause skips/duplicates
GET /v1/users/{user_id}/tweets?limit=20&cursor={opaque}
-> {tweets[], next_cursor} (profile timeline)
POST /v1/users/{user_id}/follow -> 204
DELETE /v1/users/{user_id}/follow -> 204
POST /v1/tweets/{tweet_id}/like -> {like_count}
DELETE /v1/tweets/{tweet_id}/like -> {like_count}
GET /v1/tweets/{tweet_id} -> single tweet (deep link)
POST /v1/media -> {media_id, upload_url} (direct-to-S3)
CLIENTS -> CDN (static + media) -> API GATEWAY / LB -> services
SERVICES (separate responsibilities, no god service)
- Tweet Service ...... validate, assign Snowflake id, persist, emit tweet-created
- Social Graph Service follow/unfollow, follower/followee lists, follower counts
- Timeline (Feed) Service serve home feed + profile timeline
- Engagement Service .. likes, like counts
- Notification Service (async consumer of fan-out events)
- Media Service ....... upload URLs, transcode, CDN publish
WRITE PATH
client -> gateway -> Tweet Service -> write tweet to Cassandra
-> publish tweet-created to Kafka -> fan-out workers read the author's
follower list from Social Graph -> insert tweet_id into each
follower's Redis timeline -> client gets 202/201 immediately
READ PATH
client -> gateway -> Timeline Service -> read top-K tweet_ids from Redis
-> batch hydrate tweet bodies from Cassandra + author from user cache
-> re-rank, filter blocked/muted/deleted -> return 20 + cursor
(materialized feed; assembles on read only when cache is cold)
STORES
Tweets Store (Cassandra) | Timelines Store (Redis hot + Cassandra cold)
Follow Graph (Cassandra) | Engagement store + Redis counters
Object Storage + CDN for media
Fan-out Queue (Kafka) + Fan-out Workers decouple write from fan-out
flowchart TD C[Client] --> CDN[Edge CDN] --> GW[API Gateway / LB] GW --> TW[Tweet Service] GW --> FS[Timeline Service] GW --> SG[Social Graph Service] GW --> EN[Engagement Service] GW --> MS[Media Service] TW -->|persist| TDB[(Tweets Store - Cassandra)] TW -->|tweet-created| K[[Fan-out Queue - Kafka]] MS --> S3[(Object Storage)] --> CDN K --> FW[Fan-out Workers] SG --> GDB[(Follow Graph - Cassandra)] FW -->|read followers| GDB FW -->|insert tweet_id| TL[(Timeline Store - Redis)] FS -->|top-K ids| TL FS -->|hydrate| TDB EN --> RC[(Like Counters - Redis)] K --> NS[Notification Service]
CHOICE: hybrid precomputed + on-demand
Precompute each active user's top-K timeline so a feed read is one cache
lookup + one batch hydration (hits the latency SLO). Full on-demand assembly
would require merging ~200 followee timelines per read at 58k reads/s.
Fan-out can't be fully synchronous either, because that's 2.3M-7M writes/s
on the publish path. Hence: async precompute + read-time merge.
NEW TWEET -> FEED
1. Tweet Service persists and emits tweet-created
2. Fan-out workers pull follower list from Social Graph in batches
3. If author.follower_count <= 100k (push): insert tweet_id into each
follower's Redis timeline with score = time/rank
4. If author is above that threshold (pull): skip fan-out entirely; mark the
author as a pull-source and let the read path merge their recent tweets
5. Retries/replays are idempotent - ZADD by tweet_id dedupes
CELEBRITY / VIRAL SPIKE
Never fan out a 50M-follower account (one tweet = 50M writes). High-follower
authors are pulled at read time from author_tweets, merged into the follower's
cached timeline, capped to recent N tweets.
RANKING
Cached timeline holds ~800 candidates; read path re-ranks the top ~100 and
returns 20. Score mixes recency (exponential time decay), engagement
(likes/replies normalized by impressions), and author affinity (do I
interact with this author). Ranking, not strict reverse-chron, drives order.
COLD START / CACHE MISS
New user or evicted key: assemble the feed on read by merging recent tweets
from the followee set (or from pull sources), return it, and write the result
back to Redis asynchronously so the next read is a cache hit.
PAGINATION
Opaque cursor encodes (score, tweet_id) - keyset pagination. Stable ordering
means no duplicates or skips as new tweets arrive; never use offsets.
QUEUE DELAY / OUTAGE
If Kafka or fan-out lags, timelines are stale but reads still succeed (pull
fallback still sees the newest celebrity tweets). Updates are idempotent so
replays after recovery converge; consumers catch up to eventual consistency.
CAPACITY CHECK
500M users x 800 ids x 8B = 3.2TB in Redis - feasible on a cluster of
~100 nodes. Only active users' timelines are hot; inactive users get rebuilt
on next read (LRU eviction is acceptable).
DATABASE DESIGN
users user_id PK, handle, display_name, follower_count, following_count
-> sharded RDBMS (MySQL/Postgres), lookup by user_id or handle
tweets tweet_id PK, author_id, text, media_ids, created_at
-> Cassandra, partition key tweet_id (point lookup + hydration)
author_tweets partition key author_id, clustering key created_at DESC
-> Cassandra, serves profile timeline and pull-mode authors
follows partition key follower_id, clustering followee_id
followers partition key followee_id, clustering follower_id
-> Cassandra both directions; needed because fan-out reads
the follower list on every tweet
likes partition key tweet_id, clustering user_id (who liked this)
liked_by partition key user_id, clustering tweet_id (what I liked)
like_counts tweet_id -> count, Redis with periodic Cassandra write-back
-> toggle is idempotent (insert-if-absent / delete)
home_timeline user_id -> sorted set of tweet_ids (score = time/rank)
-> Redis (hot top-K), Cassandra (cold tail / rebuild source)
media media_id -> S3 key + CDN URL
-> object storage + CDN, metadata row in RDBMS
tweet_id: Snowflake (41-bit ms timestamp, 10-bit machine, 12-bit sequence)
-> 4,096 ids/ms/node, no coordination, time-sortable so a
timeline read is a single ordered range scan