Skip to main content

Twitter: Deep Dives

Editorial

Data Model and Fan-out Pipeline

Level: Senior

Database choice: Cassandra for tweets and social graph.

At 600M tweets/day and 300M DAU, we need a database optimized for:

  • High write throughput (distributed, no single point of bottleneck).
  • Time-series-like queries (get recent tweets by user, ordered by timestamp).
  • Horizontal scaling (add nodes to handle growth).

Cassandra excels at all three. Its log-structured merge (LSM) tree storage is optimized for writes, and its partition-key + clustering-key model is perfect for "get all tweets by user X ordered by time".

-- Tweets table (partitioned by author_id, clustered by tweet_id descending)
CREATE TABLE tweets (
    author_id    UUID,
    tweet_id     BIGINT,          -- Snowflake ID (roughly time-ordered)
    content      TEXT,
    created_at   TIMESTAMP,
    PRIMARY KEY (author_id, tweet_id)
) WITH CLUSTERING ORDER BY (tweet_id DESC);

-- Engagement counts: Cassandra counters must live in a table of their own
CREATE TABLE tweet_counters (
    tweet_id     BIGINT PRIMARY KEY,
    likes        COUNTER,
    retweets     COUNTER,
    replies      COUNTER
);
-- e.g. UPDATE tweet_counters SET likes = likes + 1 WHERE tweet_id = ?;

-- Social graph: who does user X follow?
CREATE TABLE following (
    user_id      UUID,
    followed_id  UUID,
    followed_at  TIMESTAMP,
    PRIMARY KEY (user_id, followed_id)
);

-- Social graph: who follows user X? (for fan-out)
-- A celebrity's followers would be one giant partition, so rows are spread over buckets:
-- most users have a single bucket (0); a celebrity gets one bucket per ~100K followers.
CREATE TABLE followers (
    user_id      UUID,
    bucket       INT,
    follower_id  UUID,
    followed_at  TIMESTAMP,
    PRIMARY KEY ((user_id, bucket), follower_id)
);

-- Users table
CREATE TABLE users (
    user_id      UUID PRIMARY KEY,
    handle       TEXT,
    display_name TEXT,
    avatar_url   TEXT,
    follower_count BIGINT,
    following_count BIGINT,
    is_celebrity BOOLEAN,        -- true if follower_count > 100K
    created_at   TIMESTAMP
);
Data model, keyed by the query. Cassandra tables, every column, with partition keys (P) and clustering keys (C). tweets: author_id (partition), tweet_id (clustering, newest first), content, created_at; it serves a user's tweets, newest first. tweet_counters: tweet_id (partition) and the counters likes, retweets, replies, because counters need a table of their own. following: user_id (partition), followed_id (clustering), followed_at; whom user X follows. followers: user_id and bucket (together the partition), follower_id (clustering), followed_at; who follows user X, which the fan-out reads; a celebrity gets one bucket per ~100K followers. users: user_id (partition), handle, display_name, avatar_url, follower_count, following_count, is_celebrity, created_at. In REDIS: timeline:{user_id} holds at most 200 tweet IDs, newest first, and tweet:{id} holds the tweet (the tweet cache).

Why Cassandra over DynamoDB or PostgreSQL?

AspectCassandraDynamoDBPostgreSQL
Write throughputExcellent (LSM tree, tunable consistency)Excellent (managed)Good but needs sharding
Partition-key + sort-key queriesNativeNativeRequires manual partitioning
Operational controlFull control when self-hosted (or managed, e.g. DataStax Astra)Fully managed (AWS lock-in)Full control
Multi-regionNative multi-DC replicationGlobal Tables (multi-region, multi-writer)Complex (logical replication; sharding needs an extension such as Citus)
Cost at scaleLower (commodity hardware)Variable (expensive at high throughput)Moderate

Cassandra's partition-key model maps perfectly to our access patterns:

  • tweets partitioned by author_id → "get all tweets by user X" is a single partition scan.
  • followers partitioned by (user_id, bucket) → "get all followers of user X", the fan-out's query, reads one partition for every account below the celebrity threshold; a celebrity's followers spread over hundreds of partitions (800 for 80M followers), so none grows huge.

The real Twitter originally used sharded MySQL, then built Manhattan, its own distributed key-value database.

Timeline cache (Redis):

Each user has a Redis list that stores the tweet IDs in their timeline:

Key: timeline:{user_id}
Value: [tweet_id_1, tweet_id_2, ..., tweet_id_200]  // capped at 200 entries

When the user opens their app, the Timeline Service:

  1. LRANGE timeline:{user_id} 0 19 — get the first 20 tweet IDs.
  2. Batch-hydrate the 20 tweets from a separate Redis tweet cache: one pipelined round of GET tweet:{id} commands per node. (On Redis Cluster a single MGET works only when every key is in the same hash slot, so cluster clients split the batch by node.)
  3. Return the hydrated tweets.

Twitter's own timeline cache worked this way, with 800 entries per user and 3 copies of each timeline.

One tweet, pushed to its active followers. A TweetCreated event in Kafka reaches the FAN-OUT WORKERS (50 of them), drawn as one box holding their steps: 1, skip celebrity authors, whose tweets are merged in at read time; 2, read the author's followers from the FOLLOWERS table in Cassandra; 3, skip followers inactive for 30+ days, whose timelines are rebuilt when they return; 4, for each follower f, LPUSH timeline:f with the tweet ID and LTRIM timeline:f 0 199, pipelined per node, into a REDIS CLUSTER that spreads keys over 16,384 hash slots, each list newest first and at most 200 IDs. When a follower opens the app, the TIMELINE service 5, runs LRANGE timeline:u 0 19; 6, hydrates those 20 IDs from the TWEET CACHE, one pipeline per node; 7, returns a page of 20 tweets to the CLIENT.

Fan-out Service internals: handling 1.4M writes/sec

The Fan-out Service is the most write-intensive component. For each tweet from a non-celebrity:

  1. Look up the author's follower list from Cassandra (or a cached copy).
  2. For each follower, do LPUSH timeline:{follower_id} tweet_id in Redis.
  3. Do LTRIM timeline:{follower_id} 0 199 to cap the list at 200.

To handle 1.4M timeline writes/sec (2.8M Redis commands, since each is an LPUSH plus an LTRIM):

  • Parallel fan-out workers: 50 worker instances consuming from Kafka. Each handles ~28K timeline writes/sec.
  • Redis pipelining: Batch ~100 commands into one pipeline per node — one round trip instead of 100.
  • Redis Cluster: the ~110-primary cluster sized in Deep Dive 3 spreads keys over 16,384 hash slots (CRC16(key) mod 16384, not consistent hashing). That is ~25K fan-out commands/sec per node on average (~76K at the 3× peak), well within what a node handles with pipelining.

Snowflake ID generation: roughly time-sorted unique IDs

Each tweet needs a unique ID. Using a centralized auto-incrementing counter is a bottleneck. Twitter invented Snowflake — a distributed ID generation service that produces 64-bit IDs containing:

  • 1 bit: Unused — the sign bit stays 0, so IDs are positive 64-bit integers.
  • 41 bits: Timestamp (millisecond precision, from a custom epoch: good for 69 years) — makes IDs time-sorted.
  • 10 bits: Machine ID — supports 1024 generator instances.
  • 12 bits: Sequence number — supports 4096 IDs per millisecond per machine.

So each machine can mint up to 4,096 × 1,000 ≈ 4 million IDs/sec, and 1,024 machines ≈ 4.2 billion IDs/sec. Since IDs start with the timestamp, sorting by ID is sorting by time, roughly: Twitter promised IDs ordered to within a second across machines (k-sorted), aiming for tens of milliseconds. That is close enough for timelines, so no separate timestamp column is needed for ordering.

Snowflake: 64-bit IDs, ordered by time. The 64 bits drawn to scale, from the top bit down: bit 63, the sign, always 0; bits 62 to 22, a 41-bit TIMESTAMP in milliseconds since a custom epoch, enough for 69 years; bits 21 to 12, a 10-bit MACHINE ID, for 1,024 machines; bits 11 to 0, a 12-bit SEQUENCE, 4,096 IDs per millisecond per machine. The API example's tweet ID, 1901581777106018311, decoded: shifted right by 22 it is 453372425343 ms, which added to Twitter's epoch (2010-11-04 01:42:54.657 UTC) gives 2025-03-17 10:30:00.000 UTC; its machine field is 42 and its sequence 7. Throughput: 4,096 × 1,000 ≈ 4M IDs a second per machine, and 1,024 machines ≈ 4.2B a second. Order: sorting by ID is sorting by time, roughly: k-sorted, within about a second across machines.

Timeline Generation and Ranking

Level: Senior

Modern Twitter doesn't show a purely chronological timeline — it uses an ML-based ranking algorithm to surface the most relevant tweets. This adds a scoring step between retrieving tweet IDs and returning the response.

Timeline generation pipeline:

  1. Candidate retrieval: Get 200 tweet IDs from the user's timeline cache (Redis), plus the recent tweets of the celebrities they follow (below).
  2. Hydration: Batch-fetch tweet content, author info, and engagement metrics.
  3. Feature extraction: For each tweet, compute features:
    • Author features: follower count, engagement rate, historical tweet quality.
    • Tweet features: age, likes, retweets, replies, media type.
    • User-author features: interaction history (how often does this user engage with this author?).
  4. Ranking: An ML model (e.g., a lightweight neural network) scores each tweet 0-1.
  5. Filtering: Remove duplicates, already-seen tweets, and blocked users.
  6. Return: Top 20 tweets sorted by score.
From candidates to the top 20: the timeline ranking pipeline in six stages. 1, CANDIDATES: the 200 cached tweet IDs plus the recent tweets of followed celebrities. 2, HYDRATE: the tweet, its author and its counts. 3, FEATURES about the author, the tweet, and you. 4, RANK: an ML model scores each tweet from 0 to 1. 5, FILTER: duplicates, already seen, blocked. 6, TOP 20, sorted by score. The whole page has one target: p99 under 200 ms. Stage 3's features: AUTHOR (follower count, engagement rate, past tweet quality), TWEET (age, likes, retweets, replies, media type), and YOU × AUTHOR (how often you engage with this author).

The hybrid timeline: merging pre-computed and on-demand data

For the hybrid fan-out strategy, a follower's timeline is assembled from two sources:

  1. Pre-computed cache (fan-out-on-write tweets from non-celebrities):
    LRANGE timeline:{user_id} 0 199 → 200 tweet IDs.

  2. On-demand queries (fan-out-on-read tweets from celebrities the user follows):
    For each celebrity (say 5 celebrities), query their latest tweets from Cassandra:
    SELECT * FROM tweets WHERE author_id = ? LIMIT 20.

The Timeline Service merges these two lists, deduplicates, scores them through the ML ranker, and returns the top 20.

Performance impact: The celebrity queries run in parallel, so they add about as much as the slowest one — roughly 5–10 ms with tail latency, not the 25 ms of five in a row. Compared to fanning out 80M writes, this is an excellent trade-off.

Inactive user optimization

Followers include every registered account, not just the 300M people active today, and many haven't opened the app in weeks. Fanning out tweets to their caches wastes writes and memory.

Optimization: Only fan out to users active recently (Twitter used 30 days). For users who haven't been active:

  • When they open the app, compute their timeline on-the-fly (fan-out-on-read) from the tweets of users they follow.
  • Cache the result so subsequent reads are fast.
  • Resume normal fan-out for this user going forward.

The saving is the share of followers who are dormant; with far more registered accounts than daily users, that share is large.

Follow/unfollow timeline merging

When a user follows a new account:

  1. The Follow Service writes the edge to the social graph (Cassandra).
  2. An async job fetches the followed user's latest 20 tweets from Cassandra.
  3. These tweet IDs are merged into the follower's timeline cache (Redis).
  4. The list is re-sorted by tweet_id (roughly time-sorted, via Snowflake) and trimmed to 200.

When a user unfollows an account:

  1. The Follow Service deletes the edge from the social graph.
  2. An async job reads the follower's ≤ 200 cached IDs, looks up each tweet's author in the tweet cache, and removes the unfollowed author's IDs with LREM. The entries hold only tweet IDs, so the job must look the authors up; Twitter's entries carried the author's ID (plus 4 bytes of flags) for exactly this kind of work.

Both operations are eventually consistent — the user might see a brief period where the followed/unfollowed user's tweets appear or disappear.

Database Sharding, Caching, and Scaling

Level: Staff

At 525 TB of tweet data over 5 years and 2.1M peak read QPS, both the data layer and cache layer need careful scaling.

Cassandra partitioning:

The tweets table is partitioned by author_id. This means all tweets from a single user live on the same Cassandra replicas — making the common query ("get tweets by user X") a single-partition read (the fastest query type in Cassandra).

Partitioning keyProsCons
author_idSingle-partition for user timeline; even distributionVery prolific accounts (bots, news feeds) grow large partitions
tweet_idEven distributionUser timeline requires scatter-gather across all nodes
compound (author_id + date bucket)Limits partition size for prolific authorsMore complex routing

Recommendation: author_id, adding a date bucket only for the few very prolific authors. (The table where celebrities hurt is followers, one row per follower, which is why it is bucketed in Deep Dive 1.) Cassandra automatically distributes partitions across the ring using consistent hashing.

Redis cluster sizing for timeline cache

Memory estimation:

  • 300M users × 200 tweet IDs × 8 bytes per ID = 480 GB of timeline data.
  • Tweet content cache: 600M tweets/day × 5 days hot window × 480 bytes = ~1.44 TB.
  • Total: ~2 TB of Redis memory.

Cluster sizing:

  • Plan ~25 GB of data per node (a planning choice that leaves headroom for overhead; Redis itself has no such limit).
  • 2 TB ÷ 25 GB = 80 Redis nodes minimum.
  • With a replica each (for HA): 160 nodes, on memory alone.

QPS capacity:

  • A node serves ~100K commands/sec one at a time, and several hundred thousand with pipelining (~500K simple commands/sec).
  • At peak: 2.1M timeline reads (LRANGE), 42M tweet GETs to hydrate them (20 per page), and 8.4M fan-out commands (21K tweets/sec × 200 followers, each an LPUSH plus an LTRIM). Hydration dominates.
  • ~52M commands/sec ÷ ~500K per node ≈ 105 nodes.

So throughput (~105 nodes), not memory (80 nodes), sets the size: plan ~110 primaries + 110 replicas = ~220 nodes.

Sizing Redis: peak commands set the size. Left, MEMORY, what the cluster must hold, as a bar: timelines, 300M users × 200 IDs × 8 B = 480 GB, and the tweet cache, 600M tweets a day × 5 days × 480 B = 1.44 TB; about 2 TB ÷ 25 GB a node = 80 nodes. Right, PEAK COMMANDS a second, what the cluster must answer, as a bar on its own scale: timeline reads (LRANGE) 2.1M, fan-out 21K tweets × 200 followers × 2 commands = 8.4M, and hydration 2.1M pages × 20 GETs = 42M; about 52M ÷ 500K a node ≈ 105 nodes. The plan: ~110 primaries + 110 replicas ≈ 220 nodes. Throughput, not memory, sets the size: 80% of the peak commands are hydration GETs.

Data lifecycle: hot, warm and analytics tiers

Tweets never expire: a tweet from 2006 still opens today, and the requirements promise no tweet loss. Five years is only the horizon the storage estimate plans for. What changes with age is where a tweet lives:

Hot tier (0-30 days): Tweets in the last 30 days are most frequently accessed. These live in Cassandra on SSDs and are cached in Redis for the timeline.

Warm tier (older): Older tweets move to a cheaper Cassandra cluster on HDDs. Still online for profile pages and tweet links, just slower.

Analytics copy: Every tweet is also exported to object storage (S3) for batch jobs (Spark/Presto). It is a copy, not the only home, because anyone can open an old tweet at any time.

No TTL goes on the tweets table: a TTL would delete tweets their authors never deleted.

Multi-region deployment

Twitter serves users globally. For low latency, deploy in 3+ regions (e.g., US-East, EU-West, AP-Southeast).

  • Cassandra: Native multi-DC replication with tunable consistency. Writes go to the local DC and replicate asynchronously to other DCs. Reads are served locally.
  • Redis: Each region has its own Redis cluster with its own copy of timeline data. Fan-out happens locally in each region.
  • Kafka: Cross-region replication with MirrorMaker 2. Tweet events published in US-East are replicated to EU-West and AP-Southeast, triggering local fan-out.

User-follows-user across regions: the Follow Service writes are replicated to all regions within seconds via Cassandra's multi-DC replication.

Tweet Delivery Guarantees and Edge Cases

Level: Senior

Users post tweets expecting them to be visible. What happens when things go wrong?

Failure scenario 1: Fan-out worker crashes mid-distribution.

A tweet has been written to Cassandra and the TweetCreated event is in Kafka. The fan-out worker processes 50,000 out of 200,000 followers and crashes.

Solution: Kafka consumer offsets are only committed after the entire fan-out is complete. When the worker restarts (or another worker picks up the partition), it re-processes the event from the uncommitted offset. Some followers get the tweet ID in their cache twice: LPUSH is not idempotent, it adds a second copy. The Timeline Service removes duplicates when it reads, so users never see them. (A sorted set scored by tweet ID — ZADD — would make the write itself idempotent, at a higher memory cost.)

Failure scenario 2: Redis node goes down.

A Redis node holding timelines for ~2.7M users (300M ÷ ~110 primaries) crashes.

Solution: Redis Cluster promotes that node's replica on its own: the other primaries vote, and the replica takes over its hash slots (no Sentinel needed; Sentinel is for non-clustered setups). The switch takes the cluster's node timeout (15 seconds by default) plus a second or two for the vote. Until then, reads of those timelines fail, so the Timeline Service builds them on the fly from Cassandra — slower but correct. Fan-out writes to the node fail too; since a worker commits its Kafka offset only after the whole fan-out succeeds (scenario 1), they are retried and land on the promoted replica. Replication is asynchronous, so the last writes the dead primary acknowledged may never have reached the replica: a few tweet IDs can be missing from some cached timelines. No tweet is lost: each stays in Cassandra and on its author's profile.

When things fail: no tweet is lost. Left, 1, a worker dies mid-fan-out: the Kafka offset is committed only after the whole fan-out succeeds, so when a worker dies after 50,000 of 200,000 followers, a worker re-runs the event for all 200,000. The first 50,000 lists hold the tweet ID twice, because LPUSH adds a copy; the TIMELINE service drops duplicates on read, so users never see them (ZADD would make the write idempotent, at more memory). Right, 2, a Redis primary dies: its REPLICA takes over its hash slots after the other primaries vote, with no Sentinel. That takes the node timeout, 15 s by default, plus the vote. Meanwhile, timelines are rebuilt from Cassandra and failed fan-out writes are retried. What can be lost: a write acknowledged just before the crash and never copied to the replica, since replication is asynchronous; that costs a tweet ID in a cached timeline, not the tweet, which stays in Cassandra.

Handling tweet deletions in the fan-out cache

When a user deletes a tweet, it must be removed from:

  1. Cassandra: soft-delete (mark as deleted) for compliance, then hard-delete after grace period.
  2. Redis (author's profile cache): remove tweet_id.
  3. Redis (every follower's timeline cache): scanning and removing a specific tweet_id from 200,000+ lists is expensive.

Practical approach: Don't eagerly remove from follower caches. Instead:

  • Mark the tweet as deleted in the tweet content cache.
  • When the Timeline Service hydrates tweet IDs, it skips deleted tweets.
  • Over time, new tweets push deleted tweet IDs off the end of the 200-entry list.

This is a lazy cleanup approach — simple, efficient, and eventually consistent.

Rate limiting and abuse prevention

To prevent spam and abuse:

  1. Per-user tweet rate limit: Max 300 tweets/day, max 1 tweet per 15 seconds. Enforced via Redis counter with TTL: INCR tweet_count:{user_id}:{date}, check < 300.
  2. Per-user follow rate limit: Max 400 follows/day (X's own technical cap). Prevents mass-follow spam.
  3. Global rate limit: If total write QPS exceeds 3× steady-state, shed traffic via HTTP 429 with Retry-After header.
  4. Spam detection: Content analysis on tweets (URL blacklists, ML-based spam classifier). Flagged tweets are hidden from timelines pending review.
  5. Bot detection: CAPTCHA challenges for accounts that exhibit bot-like patterns (rapid-fire tweets, immediate follower-unfollower cycles).