SkillSprout
Chapter 6 · Lesson 3
Advanced
26 min read

Design Twitter (Microblogging)

Overview

Twitter lets people post short messages (tweets), follow other accounts, and read a home timeline: a feed of recent tweets from everyone they follow. The product is simple, but the shape of the traffic is brutal. Each tweet must reach hundreds of followers within seconds, a few accounts have tens of millions of followers, and every user opens their timeline many times a day. This lesson walks the eight-step interview framework and focuses on the hard parts: tweet storage with time-sortable IDs, the follow graph, fan-out on write into per-user timeline caches, the celebrity problem, search, and trending topics.

Detailed Notes

How to use this lesson

Treat this as a 45-minute interview. The numbers are assumptions you state out loud, not facts about the real company. The interviewer checks that your estimates drive your design, not that they match reality.

A few terms we use throughout:

  • A tweet is a short post (up to 280 characters) with optional media (images, video) and links.
  • A follow is a one-way relationship: A follows B means A sees B's tweets, B does not have to follow back.
  • The home timeline is the feed of tweets from accounts you follow. The user timeline (profile timeline) is the list of tweets written by one account.
  • Fan-out means copying one event to many destinations. One tweet fans out to all of the author's followers.

Step 1: Clarify Requirements

Start by turning "design Twitter" into a scope you and the interviewer agree on. A good opening: "Twitter has dozens of features. I'd like to focus on posting, following and the home timeline, then touch search and trending if time allows. Is that right?"

Functional requirements

  • A user can post a tweet (text up to 280 characters, optional images or video, optional links).
  • A user can follow and unfollow other users.
  • A user can view their home timeline: recent tweets from followed accounts, newest first, loaded page by page.
  • A user can view a user timeline: all tweets from one account.
  • A user can delete their own tweet, retweet someone else's tweet, and reply to a tweet.

Extended requirements

Mention these and ask whether to include them.

  • Search: find tweets by keyword.
  • Trending topics: the hashtags or phrases growing fastest right now.
  • Likes, notifications, direct messages, ads, "For You" ranking.

We will design search and trending at a high level because they are classic follow-up questions.

Non-functional requirements

  • Low read latency: p99 (99 of 100 requests faster than this) for loading the home timeline under 300 ms.
  • Fresh enough: a tweet should appear in followers' timelines within about 5 seconds. Eventually consistent is acceptable.
  • High availability: 99.99% for reading and posting. Availability beats consistency: showing a timeline that is a few seconds stale is fine, an error page is not.
  • Durability: once we confirm a tweet, it must not be lost.
  • Scalability: hundreds of millions of daily users, tens of thousands of timeline reads per second, accounts with 50 million followers.

Consistency decision. Timelines are eventually consistent (a new tweet may take a few seconds to show up). Two things are stricter: the author must see their own tweet immediately (read-your-writes), and a deleted tweet must disappear quickly everywhere.

Out of scope

Ads, recommendations and ranking algorithms, direct messages, notifications, and content moderation pipelines. We assume a separate service handles authentication and user profiles.

Interview tip. The most common failure here is designing a chronological feed with "SELECT tweets WHERE author IN (my follows) ORDER BY time". It works for 1,000 users and collapses at scale. Say at the start that the central problem is reading fast, and that we will do work at write time to make reads cheap.

Step 2: Estimate Scale

Assumptions to state

  • 200 million daily active users (DAU) and 400 million total users.
  • Each DAU posts 0.5 tweets per day on average (most people read much more than they post).
  • Each DAU opens the timeline 10 times per day; one open loads one page of 20 tweets.
  • The average user follows 200 accounts and has 200 followers.
  • A tweet record (text plus metadata) averages 300 bytes. Media is stored separately.
  • 20% of tweets carry media, averaging 500 KB.
  • A day has about 100,000 seconds; a peak factor of 3 covers the busiest moments.

Tweet writes

text
200M DAU x 0.5 tweets            = 100M tweets per day
100M / 100,000 seconds           = 1,000 tweets per second
1,000 x 3 peak factor            = 3,000 tweets per second at peak

So what: 3,000 writes per second is easy for a partitioned database. Posting itself is not the hard part.

Timeline reads

text
200M DAU x 10 opens              = 2 billion timeline reads per day
2B / 100,000 seconds             = 20,000 reads per second
20,000 x 3 peak factor           = 60,000 reads per second at peak
Read : write ratio               = 20,000 / 1,000 = 20 : 1
Tweets loaded per second         = 20,000 x 20 = 400,000 tweets per second

So what: reads dominate and each read needs 20 tweets. We cannot compute a timeline by querying many accounts on every open. We must keep a ready-made timeline per user.

Twitter: Estimate the Scale
Estimation

Request load

200Mdaily active users
given
100Mtweets / day
× 0.5 per user
1K/stweets written
÷ 100,000 s
20K/stimeline reads
2B/day ÷ 100,000 s
200K/sfan-out inserts
× 200 followers

Tweet storage

~11 TB / year

100M tweets × 300 bytes = 30 GB per day

Partition by tweet_id; media goes to object storage

Timeline cache

~1.3 TB raw

200M users × 800 IDs × 8 bytes (about 3 TB with overhead)

Cache IDs only, for active users, capped at 800

Celebrity fan-out

50M writes

one tweet at 100K inserts/s takes about 8 minutes

Pull celebrity tweets at read time (hybrid)
Key point. 1,000 tweets/s fan out into 200,000 timeline inserts/s, so we keep a ready-made timeline per user and treat celebrities specially.

Starting from 200 million daily users: writes are small, reads are large, and fan-out multiplies writes by followers.

Fan-out writes

text
1,000 tweets/s x 200 followers   = 200,000 timeline inserts per second
Peak: 200,000 x 3                = 600,000 inserts per second
Celebrity tweet: 50M followers   = 50M inserts for ONE tweet
At 100,000 inserts/s             = 50M / 100,000 = 500 s = about 8 minutes

So what: we turned 1,000 writes per second into 200,000 cheap in-memory inserts per second. That is the price of fast reads, and it is acceptable on average. But the celebrity case takes 8 minutes and floods the system, so very large accounts need special handling (Step 6).

Storage

text
Tweets:   100M x 300 bytes       = 30 GB per day
          30 GB x 365            = about 11 TB per year  (55 TB over 5 years)
Media:    20M tweets x 500 KB    = 10 TB per day = about 3.6 PB per year
Follow graph: 400M users x 200 follows = 80 billion edges
          80B x 16 bytes         = about 1.3 TB per direction, 2.6 TB for both

So what: tweet text is modest (tens of terabytes) but needs partitioning for throughput and recoverability. Media is 300 times larger than text, so it goes in object storage with a CDN, never in the tweet database.

Timeline cache size

text
Keep the newest 800 tweet IDs per active user
800 IDs x 8 bytes                = 6.4 KB per user
200M DAU x 6.4 KB                = 1.3 TB of raw IDs
With list and key overhead (x2)  = about 2.5 to 3 TB
At about 50 GB usable per node   = 60 nodes; with a replica, about 100 nodes

We store only IDs, not whole tweets: 8 bytes instead of 300 bytes, a 37x saving. Tweet bodies live in a separate tweet cache (the last two days of tweets, 200M x 300 bytes = 60 GB, which is small).

Other sizing checks

  • Bandwidth: 20,000 reads/s x 20 tweets x 300 bytes = 120 MB/s of text. Easy. Media bandwidth is the real cost and is served by a CDN.
  • Search index (recent): the last 7 days is 700M tweets x 300 bytes = 210 GB of raw text. The index fits on a modest cluster.
  • Trending: about 1,000 tweets per second carry a few thousand hashtag events per second. Small; the challenge is accuracy per unit of memory, not volume.

Interview tip. State the headline out loud: "1,000 writes per second fan out to 200,000 timeline inserts per second, and 20,000 reads per second hit a pre-built cache. The celebrity case breaks the average."

Step 3: Define the APIs

Post a tweet

http
POST /v1/tweets
Authorization: Bearer <token>
Idempotency-Key: 7c1b9e52-...
Content-Type: application/json

{
  "text": "Shipping the new release today!",
  "media_ids": ["m_9812"],
  "reply_to": null,
  "retweet_of": null
}
json
{
  "tweet_id": "1790324998412345344",
  "author_id": "42",
  "text": "Shipping the new release today!",
  "created_at": "2026-11-28T10:15:30Z"
}
  • 201 Created on success. 400 for empty or too-long text. 401 if not logged in. 429 if the user posts too fast (rate limit).
  • Idempotency-Key: if the client retries after a timeout, the server returns the first tweet instead of posting twice.
  • Media is uploaded first to a separate upload endpoint that returns media_ids. Tweet creation then only stores references.

Timelines

http
GET /v1/timeline/home?cursor=1790324998412345344&limit=20
GET /v1/users/42/tweets?cursor=...&limit=20
json
{
  "tweets": [ { "tweet_id": "...", "author": { "id": "7", "name": "Ada" }, "text": "...", "media": [] } ],
  "next_cursor": "1790324998400000000"
}

We use cursor pagination: the cursor is the ID of the last tweet seen, and the next page is "tweets older than this ID". Offset pagination (page=3) breaks on a feed because new tweets shift every page while the user scrolls.

Other endpoints

http
POST   /v1/users/{id}/follow          # 204 No Content; idempotent
DELETE /v1/users/{id}/follow
DELETE /v1/tweets/{tweet_id}          # 204; 403 if not the author
POST   /v1/tweets/{tweet_id}/retweet  # creates a retweet entry
GET    /v1/search?q=release&cursor=...
GET    /v1/trends?region=US

How the API shapes the design

The home timeline endpoint is the busiest and has the strictest latency target, so it gets its own service and a dedicated cache. Posting is rare and can do extra work asynchronously. Every list is cursor-paginated by tweet ID, so tweet IDs must sort by time. That requirement drives the next step.

Step 4: Define the Data Model

Start from access patterns:

  1. Get tweets by ID (400,000 per second): hydrate a timeline page into full tweets.
  2. Get an account's recent tweets (user timeline) and the source for pull-based reads.
  3. Who does user X follow? and who follows user X? (needed for fan-out and for graph display).
  4. Read the home timeline (20,000 per second): the newest IDs for one user.

Tweet IDs: snowflake

We need an ID that is unique across many machines, needs no central counter, and sorts by creation time (so "newer than" is a numeric comparison and cursors work). A snowflake ID (see the unique-ids lesson) is a 64-bit number:

text
| 41 bits: milliseconds since a custom epoch | 10 bits: machine id | 12 bits: sequence |
  • 41 bits of milliseconds last about 69 years.
  • 10 bits allow 1,024 ID-generating machines, each able to make 4,096 IDs per millisecond. We need only 3 per millisecond at peak overall.
  • IDs from one machine are strictly increasing; across machines they are roughly ordered (within clock skew, usually a few milliseconds), which is good enough for a feed.
  • Because the time is inside the ID, a range of IDs is a range of time. We never need a separate created_at index to sort.

Fields and why each exists

  • tweets.tweet_id: snowflake, primary key and partition key.
  • author_id: who wrote it; used for the user timeline and permission checks.
  • text, media_ids: content and references to object storage.
  • reply_to, retweet_of: link to another tweet. A retweet is a small row that points at the original, so the original text is stored once.
  • deleted_at: marks a deleted tweet (a tombstone: a marker record that says "this was deleted", so every copy can learn about it).
  • follows and followers: the same edge stored twice, keyed by each side, so both "who do I follow" and "who follows me" are single-partition lookups.
  • user_timeline: tweet IDs per author, newest first.
  • home_timeline: a capped list of tweet IDs per user, held in a cache.
The Data Model
Data model
tweetsWide-column store
  • PKtweet_idbigint

    snowflake: time + machine + sequence

  • IDXauthor_idbigint

    who wrote it

  • textvarchar(280)
  • media_idslist<varchar>

    pointers to object storage

  • IDXreply_tobigint

    parent tweet, if a reply

  • retweet_ofbigint

    original tweet, if a retweet

  • deleted_attimestamp

    tombstone; null = live

Hash-partitioned by tweet_id for even load. Time is inside the ID, so no created_at index is needed.

user_timelineWide-column store
  • PKauthor_idbigint

    partition key

  • SKtweet_idbigint

    sorted newest first

One author's tweets in one sequential read; also the pull source for celebrities.

followsKey-value store
  • PKfollower_idbigint

    who is following

  • SKfollowee_idbigint

    who is followed

  • followed_attimestamp

Answers 'who do I follow?' for pull and for rebuilding a timeline.

followersKey-value store
  • PKfollowee_idbigint

    bucketed for huge accounts

  • SKfollower_idbigint

The same edge, reversed. Fan-out workers page through it 1,000 at a time.

home_timelineRedis list
  • PKuser_idbigint

    cache key

  • tweet_idslist<bigint>

    newest first, LTRIM to 800

Rebuildable from tweets and follows, so it needs no durable storage.

  • user_timeline.tweet_idtweets.tweet_id· points to
  • followers.follower_idfollows.follower_id· mirror edge
  • home_timeline.tweet_idstweets.tweet_id· IDs only
Key point. Every table is shaped for one lookup: by tweet, by author, by follower, by followee, or by timeline owner.

Tweets are keyed by snowflake ID; the follow edge is stored in both directions; the home timeline is a capped list of IDs.

Which databases?

  • Tweets: lookups are by a single key, there are no joins, and volume is high. A wide-column or key-value store partitioned by tweet_id (hash of the ID) fits. A sharded MySQL also works and is what early Twitter used. Name the access pattern, not the brand.
  • Follow graph: two lookup patterns, each by one user ID, returning large lists. A key-value or wide-column store keyed by user works. A dedicated graph database is not needed because we never traverse more than one hop.
  • Home timeline: Redis lists (an in-memory key-value store with list values). Fast pushes and range reads.
  • Media: object storage plus CDN.

Trade-off thinking. Storing the follow edge twice doubles storage (2.6 TB instead of 1.3 TB) and makes a follow two writes. In exchange, both read directions are a single fast lookup. Storage is cheap; cross-partition queries are not.

Step 5: High-Level Design

The central decision: do the expensive work when a tweet is written, not when a timeline is read. Reads are 20 times more frequent and have the tight latency target.

The Write Path and the Read Path
Architecture
Write pathFan-outRead pathClientapp / browserAPI gatewayauth, limits, LBTweet servicesnowflake IDTweet storesharded by tweet_idFollow graphfollowers by userFan-out queueTweetCreatedFan-out workerspush IDsTimelineservice~20K reads/sTimeline cacheRedis lists, 800 IDsPOST /tweetsGET /homewritepublishfollowersLPUSHread IDs
Key point. Work moved from the read path to the write path: 20 reads per write justify the extra cost.

The tweet is stored once; fan-out workers do the copying asynchronously so reads are a single cache lookup.

Components and why each exists

  • API gateway / load balancer: authenticates, rate limits, routes to services.
  • Tweet service (write path): validates, assigns a snowflake ID, writes the tweet, publishes an event.
  • Tweet store: source of truth for tweets, sharded by tweet_id.
  • Fan-out queue and workers: a durable queue of "tweet created" events. Workers look up the author's followers and push the tweet ID into each follower's timeline. This is asynchronous: the author does not wait for 200 inserts.
  • Follow graph store: who follows whom.
  • Timeline cache: one capped list of IDs per active user.
  • Timeline service (read path): reads the ID list, loads the tweets, returns a page.
Fan-out on Write: One Worker's Job
Request flow
Fan-out queueFan-out workerFollow graphTimeline cache1TweetCreated(id, author)author is not a celebrity2followers(author, page 1)1,000 per page31,000 follower IDs4LPUSH + LTRIM 800pipelined per cache node, active users only5OK6followers(author, page 2)repeat until the last page7ack eventretry on crash is safe
Key point. Redelivery is safe: duplicate inserts are removed by ID when the timeline is read.

A worker pages through the follower list and pushes the tweet ID into each follower's capped list.

Request flow

Posting.

  1. Client sends POST /v1/tweets; the gateway authenticates and rate limits.
  2. The tweet service creates a snowflake ID and writes the tweet (and the user_timeline row) durably.
  3. It publishes TweetCreated(tweet_id, author_id) to the queue and returns 201. The author's own timeline is updated immediately.
  4. Fan-out workers take the event and push the ID into each follower's list (Step 6).

Reading the home timeline.

  1. Client sends GET /v1/timeline/home.
  2. The timeline service reads the newest 20 IDs older than the cursor from the user's cached list.
  3. It hydrates the IDs: loads tweet bodies from the tweet cache (misses go to the tweet store), plus author names and counts.
  4. It filters out deleted or blocked tweets and returns the page.

Step 6: Deep Dive

6.1 Fan-out on write, pull, or hybrid?

There are two basic strategies for building a timeline.

Push, Pull and Hybrid Timelines
Comparison

Fan-out on write

push into follower lists

  1. 1

    Tweet is stored

    one durable write

  2. 2

    Workers read the followers

    about 200 on average

  3. 3

    Push the ID to each list

    LPUSH + LTRIM

  4. 4

    Read = one list lookup

    fast and predictable

  • Reads are a single cache lookup
  • Matches the 20:1 read ratio
  • 50M writes for one celebrity tweet
  • Wasted work for inactive followers

Best for the typical account

Fan-out on read

pull and merge at open time

  1. 1

    Tweet is stored only

    no copies made

  2. 2

    User opens the timeline

    20,000 times a second

  3. 3

    Fetch recent tweets of each followee

    about 200 lookups

  4. 4

    Merge by tweet ID

    sorted by time

  • Cheap writes, no wasted work
  • Always fresh
  • Slow reads: 200 lookups plus a merge
  • Heavy load at peak

Only for celebrities and cold timelines

Hybrid

push normal, pull celebrity

  1. 1

    Normal tweet: push to followers

    under 100K followers

  2. 2

    Celebrity tweet: store only

    skip fan-out

  3. 3

    Read the pushed list

    one cache lookup

  4. 4

    Merge in celebrity tweets

    usually fewer than 10 accounts

  • Bounded work on both paths
  • Handles 50M-follower accounts
  • Two code paths to test and run
  • Threshold needs tuning

Recommended: best of both

Key point. Reads outnumber writes 20 to 1, so push is the default. Pull is kept only for the few huge accounts.

Push pays at write time, pull pays at read time, hybrid pushes for normal accounts and pulls for celebrities.

Fan-out on write (push). When a tweet is posted, copy its ID into every follower's timeline list. Reads become one cache lookup. This is a perfect fit for the average user with 200 followers.

Fan-out on read (pull). Store nothing extra. When a user opens the timeline, fetch recent tweets from each followed account and merge them. Writes are cheap but each read does 200 lookups plus a merge, at 20,000 reads per second.

The celebrity problem. An account with 50 million followers makes a push strategy write 50 million list entries for a single tweet (about 8 minutes at 100,000 inserts/s). Worse, those followers are mostly inactive, so most writes are wasted. Pure pull is also wrong for ordinary users.

Hybrid (recommended). Use push for ordinary accounts and pull for celebrities (say, over 100,000 followers):

  1. Celebrity tweets are not fanned out. They are only written to the tweet store and the author's user_timeline.
  2. On a home timeline read, the timeline service reads the user's pushed list, plus the recent tweets of the few celebrities the user follows (typically fewer than 10), then merges by tweet ID (IDs sort by time).
  3. Celebrity timelines are tiny and extremely hot, so they sit in cache and are cheap to read.
Reading the Home Timeline (Hybrid)
Architecture
ClientGET /homeTimelineservicemerge by tweet IDTimeline cachepushed IDsCelebritytweetspulled, per authorTweet cachehydrate 20 IDsTweet storesource of truthpushed IDsceleb IDshydrateon miss
Key point. Typical read: one list lookup, a handful of celebrity lookups, and one batch hydration.

The service merges the pushed list with the celebrity tweets by ID, then hydrates the IDs into full tweets.

Details an interviewer will probe:

  • Inactive users. Only push into timelines of active users (opened the app in the last 30 days). For a dormant user, rebuild the timeline by pull on their next visit.
  • Cold timeline. If a user's list is missing (new or evicted), build it by pulling the latest tweets of followed accounts, then store it.
  • Threshold. A follower-count cutoff is a tunable knob. Accounts near the threshold are a gray zone; add hysteresis (switch at 100,000 up but 80,000 down) so accounts do not flip back and forth.
  • Ranking. If the product later ranks tweets instead of ordering by time, the same candidate list feeds a ranker; this lesson stays chronological.

Trade-off thinking. Push moves cost from the read path to the write path, which is good when reads outnumber writes 20 to 1. Pull does the opposite. Hybrid accepts the complexity of two code paths to avoid the worst case of each.

6.2 The timeline cache

  • Structure: a Redis list per user holding tweet IDs. Fan-out does LPUSH (add at the head) followed by LTRIM (cut to the first 800 entries). The list never grows without bound.
  • Capped length: 800 IDs covers 40 pages of 20, far more than almost anyone scrolls. Older pages fall back to a pull from the user timelines.
  • Sharding: partition by user_id with consistent hashing, so a node failure only affects its slice of users.
  • Batching: a worker groups inserts per cache node and sends them in one pipelined request (many commands sent without waiting for each reply), so 200,000 inserts per second becomes tens of thousands of network calls.
  • Idempotent inserts: a worker retry could insert the same ID twice. The timeline service de-duplicates by ID while reading, so a retry is harmless.
  • Persistence: the cache is rebuildable from the tweet store and follow graph, so we accept losing it, but a full loss means a mass of pull rebuilds. Keep a replica per shard.

6.3 Follow graph storage and sharding

  • Two tables, follows(follower_id, followee_id) and followers(followee_id, follower_id), each partitioned by the first column. "Who follows 42?" is a single-partition range read.
  • Large lists are paged. A celebrity has 50 million followers, so fan-out workers read 1,000 followers at a time.
  • Hot partitions. The celebrity's followers row is huge but rarely read (no fan-out for celebrities). Spread very large follower lists across several partitions by adding a bucket suffix (followee_id#0, followee_id#1, and so on).
  • Follow is a two-row write (one per table). Write both in one batch, and run a repair job comparing them. A brief mismatch is harmless.
  • Counts (followers, following) are stored as separate counters updated asynchronously, not computed with a count query.
  • Unfollow removes the edge and schedules removal of that author's tweets from the user's timeline, or filters them at read time.

6.4 Tweet storage, user timeline and caching

  • Partition tweets by hash of tweet_id. This spreads load evenly. The user timeline cannot rely on that, so it is a separate table partitioned by author_id and clustered by tweet_id descending: "latest 20 from author 42" is one sequential read.
  • Replication. Three copies per partition across zones. A tweet is acknowledged after a quorum (2 of 3) has it, so one failure loses nothing.
  • Tweet cache. Hot tweets (recent and viral) are cached with LRU eviction. A cache hit rate near 95% means 400,000 tweet lookups per second become 20,000 database reads.
  • Hot tweets. A viral tweet is read by millions. Replicate that entry across cache nodes, add a short in-process cache, and serve counters (likes, retweets) approximately and asynchronously.

6.5 Retweets, replies, deletes and edits

  • Retweet creates a new tweet row with retweet_of = original. It fans out like a normal tweet but contains only a pointer. At hydration time we load the original and show "retweeted by X". Timeline entries are the retweet's own ID, which has its own timestamp so it sorts correctly.
  • Reply stores reply_to. A conversation view is a query by reply_to, served from an index on that column.
  • Delete. Write a tombstone (deleted_at) in the tweet store. Do not chase 200 or 50 million timeline entries. Instead the timeline service filters at hydration: if the tweet is deleted, skip it. The tweet cache entry is invalidated immediately. A background job removes the tombstoned tweet from the search index and later purges the row. Delete cost does not scale with follower count.
  • Edit. Keep one tweet ID, store a new version, and invalidate the cache entry. Timelines hold only IDs, so every follower sees the new text next read. This is another reason to store IDs, not bodies, in timelines.
  • The client uploads media to object storage directly using a short-lived signed URL, so large files never pass through app servers. A worker creates thumbnails and video renditions (a transcoding step: converting video into several sizes and formats).
  • The tweet stores only media_ids; a CDN serves the files from locations near the user. 10 TB of new media per day makes the CDN, not our servers, the main bandwidth consumer.
  • Links are replaced with a shortened form (see the URL shortener lesson) so a link costs a fixed number of characters. A background worker fetches the page title and image to build a preview card.

Search needs "find tweets that contain the word release". A database scan is far too slow, so we build an inverted index: a map from each word (term) to the list of tweet IDs containing it, like the index at the back of a book.

text
"release" -> [1790324998412345344, 1790324998399999000, ...]   (sorted newest first)
"shipping" -> [1790324998412345344, ...]
  • Indexing is asynchronous. The same TweetCreated event feeds an indexer that tokenizes the text (splits it into lowercase words, removes noise) and appends the tweet ID to each term's list. Tweets become searchable in a few seconds.
  • Partition the index by time: a hot index for the last 7 days (about 210 GB raw) and older indexes for history. Most searches want recent tweets, so the hot tier answers them.
  • Multi-word queries intersect the lists for each word. A search service queries all index shards in parallel (scatter-gather) and merges the top results by recency or relevance.
  • Deletes remove the tweet ID from the index asynchronously, and results are also filtered against the tweet store, so a deleted tweet does not show up.

Trending means "which hashtags are growing fastest right now", not "most used ever". We count on a stream of events instead of querying the database.

Trending Topics from the Event Stream
Architecture
In memoryTweet eventstreamTweetCreatedStream workershashtag hashCount-minsketchsliding windowTop-K heapscore vs baselineTrending cachetop 50 per regionTrends APIGET /trendsincrementupdateevery 1 min
Key point. A count-min sketch gives fixed memory and slightly high counts, which is fine for a top-50 list.

Counting happens in memory over a sliding window, so the database is never queried.

  1. Each TweetCreated event is parsed for hashtags and phrases.
  2. Stream processors keep a count per topic over a sliding window (for example the last hour, built from 1-minute buckets; old buckets drop off as time moves).
  3. Exact counters for every possible hashtag would need huge memory, so each processor keeps a count-min sketch: a small grid of counters where each topic is hashed to one cell per row and increments all of them. The estimated count is the minimum across rows. It can slightly over-count (collisions) but never under-counts, and 4 rows by 1 million counters is only 16 MB.
  4. A small top-K heap (the K highest-scoring topics) is maintained next to the sketch.
  5. Trend score compares the current window to the normal baseline for that topic, so "good morning" does not trend every day but a sudden spike does.
  6. Results per region are written to a trending cache (top 50 topics) refreshed every minute and served by GET /v1/trends.

Partition the stream by topic hash so one topic is always counted by one processor, then merge top-K lists. Accuracy within a few percent is fine for a trending list.

Interview discussion. "For trends I don't query the database. I count in a stream with a sliding window and a count-min sketch. It trades a small over-count for fixed memory, which is the right trade for a top-50 list."

Step 7: Bottlenecks and Failure Handling

Bottlenecks

  • Celebrity fan-out. Cause: 50 million inserts per tweet. Mitigation: hybrid pull-merge for accounts over 100,000 followers, and push only to active users.
  • Fan-out lag. Cause: a burst of tweets (big sports event, 3x peak or more). Mitigation: scale workers by queue depth, prioritize ordinary accounts, accept a few extra seconds of lag, and alert when lag exceeds 10 seconds.
  • Hot cache node. Cause: one celebrity list or viral tweet. Mitigation: replicate hot entries, use in-process caches, and add short TTLs.
  • Follow-graph hot partition. Mitigation: bucket very large follower lists across partitions.
  • Timeline cache memory. Mitigation: active users only, 800-entry cap, store IDs not bodies.
  • Snowflake clock skew. Cause: a machine's clock moves backwards. Mitigation: the ID generator refuses to issue IDs until the clock catches up and alerts operators.

Failures

  • Timeline service or app server fails. Stateless; the load balancer routes around it.
  • Timeline cache node fails. Its users' lists are gone. Fall back to a pull rebuild (read recent tweets of followed accounts), rate limited so the database is not stampeded, and re-populate the list. Replicas make this rare.
  • Fan-out worker crashes mid-tweet. The queue redelivers the event (at-least-once delivery), and idempotent inserts with read-time de-duplication make the retry safe.
  • Queue down. Posting still succeeds because the tweet is stored first. Keep a transactional outbox: store the event in the same database write as the tweet and a relay publishes it later, so no tweet is permanently un-fanned-out.
  • Tweet store partition fails. Promote a replica. Timelines still show cached tweets; other tweets on that partition are temporarily unavailable and are skipped by hydration rather than failing the whole page.
  • Partial hydration. If some tweet lookups fail, return the page with those tweets omitted instead of a 500. Availability beats completeness.
  • Zone failure. Every tier runs in at least three zones.
  • Search or trending down. Both are off the critical path. Posting and timelines keep working; search shows an error and trends serve the last cached list.

Interview tip. Pick the two likeliest failures (cache node loss and fan-out lag), say what the user sees (a slightly stale or slower timeline), and name the metrics: timeline p99 latency, fan-out lag, cache hit rate, queue depth, error rate per dependency.

Step 8: Final Design Walkthrough

Final Design
Architecture
Write pathAsyncRead pathMedia + CDNobject storageClientGateway + LBauth, rate limitTweet servicesnowflake IDTweet storesharded, replicatedFollow graphEvent streamTweetCreatedWorkersfan-out, trendsSearch indexinverted, by timeTimelineservicemerge + hydrateTimeline cachecapped ID listsimagespublishpush IDs

Solid arrows are synchronous requests. Dashed arrows are asynchronous events.

Request flow

Post: client, gateway, tweet service (snowflake ID, durable write to tweet store), event published, 201 returned. Home timeline: client, gateway, timeline service, ID list from the timeline cache plus celebrity tweets, merge by ID, hydrate from tweet cache or store, filter deleted, page returned.

Data flow

Tweets live in the sharded, replicated tweet store (source of truth) with a hot tweet cache. The follow graph lives in two edge tables. Per-user home timelines are capped ID lists in the timeline cache. Media lives in object storage behind a CDN. Search indexes and trending counters are derived from the tweet event stream.

Background processing

Fan-out workers push IDs to followers of ordinary accounts. Indexers update the search index. Stream processors compute trends. A cleanup job purges tombstoned tweets. A repair job reconciles the two follow tables.

Critical design decisions

  1. Snowflake tweet IDs, so IDs are unique without coordination and sort by time for cursor pagination.
  2. Fan-out on write into capped Redis lists of IDs, because timeline reads outnumber tweets 20 to 1.
  3. Hybrid pull-merge for celebrities, to avoid 50 million writes per tweet.
  4. Follow edges stored twice, sharded by user, so both directions are single-partition lookups.
  5. Tombstones and read-time filtering for deletes, so delete cost does not grow with followers.
  6. Search and trends from the event stream, so these features can lag or fail without hurting posting or reading.

If time remains, discuss multi-region: the tweet store replicates across regions, each region has its own timeline cache and fan-out workers, and users are routed to the nearest region.

Common Interview Questions

Finished this lesson?

0 of 44 lessons done · 0% of the course