Case Study: X / Twitter
"fanout can be really slow! …especially for high follower counts" — Raffi Krikorian, Timelines at Scale, QCon San Francisco 2012, slide 18 (InfoQ recording)
Summary: Twitter is the classic read-heavy social feed: hundreds of millions of tweets a day, each read many times by followers. This chapter rebuilds its architecture from Twitter's own posts, papers and talks: the Redis timeline cache filled by fan-out on write, the hybrid path for high-follower accounts, Snowflake ids, the storage line from sharded MySQL through Gizzard and FlockDB to Manhattan and Blobstore, the cache tier (Twemcache, Redis, Pelikan), Earlybird real-time search, Heron and Kafka, Finagle and Zipkin, Mesos and Aurora, and the ranked For You timeline published in 2023 as the-algorithm. Focus: Every architecture claim on this page cites a source published by Twitter/X itself (engineering blog, open-source repository, conference talk or paper by its engineers). Anything this page infers or generalises is labelled inference. Learning goal: Run the four-step method (scope → estimate → high-level design → decisions) on a Twitter-like product, explain why the home timeline is precomputed and where that stops working, and implement the two core mechanisms (k-ordered ids and hybrid fan-out) in Go and Laravel with tests.
This is a case study, not a mechanism chapter. The generic mechanics live elsewhere and are linked once: the method in The Four-Step Approach; push vs pull feeds in Feeds: Fan-out & Fan-in; id schemes in ID Generation at Scale; cache patterns in Caching and Redis; search in Search Systems; streams in Kafka in Depth and Stream Processing; ranking in ML Systems Architecture.
How to read the sources
Twitter's engineering blog moved from blog.twitter.com/engineering to blog.x.com/engineering. The live site answers automated clients with a bot challenge (HTTP 403), so every blog post below is cited through its Internet Archive copy of the original Twitter page, which returns 200. The text is Twitter's own; only the hosting differs. The 2012 talk is cited by slide number from the InfoQ recording.
Page map
| If you are looking for | Go to |
|---|---|
| The whole case in three tables | Everything in one minute |
| Why Twitter is a hard feed problem | Why it exists |
| Dated history from Twitter's own posts | Where it comes from |
| Step 1: what the product must do | Scope |
| Step 2: the numbers Twitter published | Estimate |
| Step 3: the boxes | High-level design |
| Step 4: one block per subsystem | Timelines, Hybrid fan-out, Snowflake, Storage, Caching, Search, Real-time, Infrastructure, Reliability, Ranked timeline, ML |
| What changed and when | What changed over time |
| Which generic chapter each part maps to | What you can copy |
| Knobs, sizes, error messages | Mechanics |
| Code | Go, Laravel |
| Celebrity storms, inactive users, id collisions | Solving the classic problems |
| Push, pull or hybrid for your product | Choosing |
| Monolith to distributed system | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The subsystems and the source for each.
| Subsystem | What Twitter built or adopted | Primary source (date) |
|---|---|---|
| Home timeline | Fan-out on write into a Redis timeline cache; Timeline Service reads it | Krikorian, Timelines at Scale (QCon SF 2012) |
| High-follower accounts | Not fanned out; their user timeline is merged at read time | Same talk, slides 18–28 |
| Ids | Snowflake: 64-bit, time + machine + sequence, k-sorted | Announcing Snowflake (1 June 2010) + README |
| Tweet storage | Temporally sharded MySQL, then Gizzard-hashed MySQL (T-Bird), later Manhattan | New Tweets per second record (16 Aug 2013); Manhattan (2 Apr 2014) |
| Social graph | FlockDB on Gizzard + MySQL | Introducing FlockDB (3 May 2010) |
| Media | Blobstore | Blobstore (11 Dec 2012) |
| Cache | Twemcache (memcached fork), Nighthawk (sharded Redis), Haplo (Redis for timelines), Pelikan | Caching with Twemcache (10 Jul 2012); Infrastructure behind Twitter: scale (19 Jan 2017); Pelikan repo |
| Search | Earlybird, real-time inverted index on Lucene; Blender front-end | Search post (31 May 2011); full index (18 Nov 2014) |
| Streams and pub/sub | Storm → Heron; EventBus (DistributedLog) → Kafka | Heron (2 Jun 2015); Kafka adoption (28 Nov 2018) |
| RPC and tracing | Finagle, Finatra, Zipkin | Finagle (19 Aug 2011); Zipkin (7 Jun 2012); Finatra README |
| Scheduling | Apache Aurora on Apache Mesos | Aurora (12 Feb 2015) |
| Ranked For You timeline | Candidate sourcing → light ranker → heavy ranker → filters → Home Mixer | Twitter's Recommendation Algorithm (31 Mar 2023) + the-algorithm repo |
| Embeddings | SimClusters, TwHIN | 2023 post; TwHIN paper (KDD 2022) |
The numbers Twitter published.
| Number | Value | Source |
|---|---|---|
| Tweets per day (2012) | about 400 million | Krikorian slides 21, 34 |
| Tweet input rate (2012) | ~5K/s average, ~7K/s daily peak, more than 12K/s in large events | slide 34 |
| Timeline reads (2012) | more than 300K QPS, 1 ms p50 / 4 ms p99 | slide 33 |
| Timeline deliveries (2012) | 30 billion a day, ~300K per second, 3.5 s p50 to reach 1 million followers | slide 35 |
| Record peak (2013) | 143,199 tweets per second, about 25× the 5,700/s average | TPS post, Aug 2013 |
| Cache (2012) | over 20 TB in memory, almost 2 trillion queries a day | Twemcache post |
| For You pipeline (2023) | about 5 billion runs a day, under 1.5 s average, 220 s CPU per run | 2023 algorithm post |
The decisions in one line each.
| Decision | Choice | Price paid |
|---|---|---|
| Precompute or compute on read | Precompute (fan-out on write) for most authors | Write amplification; seconds of delivery delay for big accounts |
| Celebrities | Read-time merge (hybrid fan-out) | Read path does extra lookups and a merge |
| Ids | Uncoordinated, k-sorted 64-bit | No strict global order; depends on clocks |
| Storage | Availability over consistency (Manhattan), strong consistency opt-in | Conflict resolution and repair machinery |
| Platform | Build in-house, later adopt community tools (Kafka, Heron-compatible Storm API) | Migration cost twice |
Why it exists
A follow graph turns one write into many reads. When you open the app you want the latest posts of everyone you follow, now, in order. Two ways to do that:
| Pull (fan-out on read) | Push (fan-out on write) |
|---|---|
| Store each author's tweets once | Also copy each new tweet id into every follower's list |
| Home read = query all followed authors and merge | Home read = read one precomputed list |
| Cheap writes, expensive reads | Expensive writes, cheap reads |
| Cost grows with how many accounts you follow | Cost grows with how many followers the author has |
Krikorian's slide 17 states the trade-off compactly: Redis timelines are "O(n) write, O(1) read", the Earlybird search index is "O(1) write, O(n) read". Twitter's reads vastly outnumber writes (300K QPS of timeline reads against about 5K tweets per second in 2012), so pushing work to the write side wins, until one author has tens of millions of followers (slide 20 lists accounts with 23 to 31 million followers). That is the whole case in one paragraph.
Everyday picture. A newspaper (push) prints one copy per subscriber at night so that breakfast reading is instant. A library (pull) keeps one copy and every reader walks to the shelf. Twitter runs the newspaper for ordinary authors and the library for celebrities, and the reader sees one merged paper.
Three common misunderstandings, up front
- "Twitter stores a full copy of every tweet in every follower's timeline." The 2012 slides show the cached entry is a tweet id, user id and a few flag bits (8 + 8 + 4 bytes, slide 9); tweet bodies are hydrated from other services: slide 12 shows Gizmoduck and TweetyPie beside Timeline Service, and the-algorithm README calls Tweetypie the "Core service that handles the reading and writing of post data" (that Gizmoduck serves users is inference from the name and diagram).
- "Fan-out on write means every user has a timeline in memory." The insert uses
RPUSHX, which only appends to lists that already exist (slide 10), so only cached (in practice: recently active) timelines are written. Which users stay cached is not stated in the slides: inference. - "The ranked For You timeline is still built from that cache." The 2023 post says Twitter "recently stopped using Fanout Service"; in-network candidates now come from the Earlybird search index (the-algorithm README: "~50% of posts come from this candidate source").
Where it comes from
Every date in this section comes from the post or talk named; the dated list is the backbone of What changed over time.
- 2008–2010, the Rails and MySQL era. Search came from the 2008 Summize acquisition, built on Rails and MySQL (search post, 2011). Tweets lived in "a MySQL storage system that was temporally sharded and had a single master" (TPS post, 2013). The 2010 World Cup "repeatedly took its toll and made Twitter unavailable for short periods of time" (TPS post).
- 2010, the data layer. Gizzard (6 April 2010), FlockDB (3 May 2010), Snowflake (1 June 2010); Earlybird replaced MySQL search in October 2010 (search post).
- 2011–2012, services on the JVM. Finagle (19 August 2011), the JVM rewrite and services for the "core nouns" Tweet, timeline and user (TPS post), Zipkin (7 June 2012), Twemcache (10 July 2012), Blobstore (11 December 2012), and Krikorian's Timelines at Scale at QCon SF 2012.
- 2013–2015, platform. 143,199 tweets per second without an outage (16 August 2013), Manhattan (2 April 2014), a full index of every public tweet (18 November 2014), Aurora on Mesos (12 February 2015), Heron (2 June 2015).
- 2016–2018, ranking and migration. Ranked timeline with deep learning (9 May 2017, saying the ranked timeline launched "more than a year" earlier), the 2017 infrastructure overview (19 January 2017), Kafka replacing EventBus (28 November 2018).
- 2023, X. Open-sourced recommendation code and the For You post (31 March 2023). The README now speaks of "X's Recommendation Algorithm".
The concept catalogue
The catalogue follows the four-step method from The Four-Step Approach: steps 1–3 set up the problem, step 4 is one concept block per subsystem.
Step 1, scope: what the product must do
| Requirement | Source of the requirement | Kind |
|---|---|---|
| Post a tweet (with media) | product | functional |
| Home timeline of followed accounts, newest first (later ranked) | Krikorian slides 3, 13; 2017 ranking post | functional |
| User timeline (one author's tweets) | slide 28 (user_timeline:) | functional |
| Real-time search over all public tweets | search posts 2011, 2014 | functional |
| Follow / unfollow with no follower limit | FlockDB post | functional |
| Timeline reads in single-digit milliseconds | slide 33 (1 ms p50, 4 ms p99) | non-functional |
| Survive event spikes (25× average) | TPS post 2013 | non-functional |
| Favour availability over consistency | Manhattan post | non-functional |
| Out of scope here | DMs, ads auction, trust and safety internals | boundary |
Step 2, estimate: the published numbers and what they imply
The inputs are Twitter's figures; the derivations are arithmetic done on this page and labelled as such. The method is in Back-of-the-Envelope Capacity Estimation.
input (Twitter, 2012) derivation (this page, inference)
1 400M tweets/day, ~5K/s avg, >12K/s events
2 30B timeline deliveries/day -> 30B / 400M = ~75 deliveries per tweet on average
3 ~300K deliveries/s -> same order as 300K timeline reads/s
4 entry = 8 B tweet id + 8 B user id + 4 B -> 20 B per cached entry
5 assume 800 entries x 150M cached timelines -> 800 * 20 B * 150M = 2.4 TB per copy (assumption, not a Twitter figure)
6 slide 8: insert is "replicated" -> multiply memory by the replica count
7 3.5 s p50 to deliver to 1M followers -> a 30M-follower push would take minutes at that rate (inference)Line 7 is why the hybrid exists. Line 5 is a sizing exercise only: the per-timeline length is not on the slides we read, so 800 is our assumption.
Step 3, high-level design: the boxes
The write path (slides 6–16): Write API → Fanout, which asks the Social Graph Service for followers and inserts into the Redis timeline cache "keyed off recipient", "pipelined 4k destinations at a time", "replicated" (slide 8); in parallel an Ingester indexes the tweet into Earlybird (slide 16). The read path: Timeline Service reads the list; Gizmoduck and TweetyPie sit beside it on slide 12 and hydrate the ids (Tweetypie handles post data per the-algorithm README; Gizmoduck as the user service is inference); Blender serves search. The 2023 For You timeline adds a ranking funnel on top, shown in Ranked timeline.
Step 4, decisions: one block per subsystem
Home timeline: fan-out on write into a Redis timeline cache Must-know
In plain words: When you tweet, a worker copies the tweet's id into the home timeline list of each of your followers, so that opening the app is one cache read.
Common misunderstanding: "Fan-out on write is a database trigger." It is an asynchronous service (Fanout) that writes to a separate cache tier; the tweet is durable before fan-out starts, and followers see it a little later (3.5 s p50 to one million followers, slide 35).
Definition: The home timeline is a precomputed, bounded list of entries (tweet id, author id, flag bits) per recipient, stored in Redis using its native list type and appended with RPUSHX so only existing lists grow (slides 9–10). Twitter later described the timeline cache as Haplo: "It is the primary cache for Tweet timelines and is backed by a customized version of Redis (implementing the HybridList)" (2017 infrastructure post). Haplo "is read-only from Timeline Service and written to by Timeline Service and Fanout Service" (same post).
author @a (2k followers) Fanout service Redis timeline cache
1 POST tweet 1001 -> Write API
2 followers(@a) from Social Graph Service
3 batch 1: 4000 RPUSHX home:<f> 1001 appended only where list exists
4 (pipelined, replicated)
5 follower @f opens app -> Timeline Service: LRANGE home:@f 1 read, ids only
6 Timeline Service hydrates ids via Tweetypie / Gizmoduck -> rendered timelineReal scenario: a regular user with a few hundred followers tweets: a few hundred list appends, all followers see it within seconds; a follower who has not opened the app for a long time has no cached list, so nothing is written for them and the list is rebuilt when they return (inference from RPUSHX semantics; the rebuild policy is not described in the sources we read).
What provides it:
| Concern | Twitter's choice (source) | Generic alternative |
|---|---|---|
| Storage of the list | Redis native list, later Haplo HybridList (slides 9–10; 2017 post) | sorted set, wide-column row (Wide-Column & Key-Value) |
| Only active users | RPUSHX (slide 10) | TTL-based eviction |
| Write efficiency | pipelined 4k destinations (slide 8) | per-follower RPC |
| Durability | replicated cache; source of truth is tweet storage | write-through to a store |
| Hydration | ids only; Tweetypie and Gizmoduck fill in (slide 12) | denormalised copies |
Fix / how to use it: the Go fanout package and the Laravel FanoutTweet job implement exactly this: RPUSHX + LTRIM in pipelines of 4,000, ids only. The general push/pull theory is in Feeds: Fan-out & Fan-in.
Hybrid fan-out for high-follower accounts (the celebrity problem) Must-know
In plain words: For accounts with millions of followers, do not copy the tweet to everyone; when a follower reads, fetch that celebrity's recent tweets and merge them in.
Common misunderstanding: "Hybrid means celebrities' followers get a slower timeline." The read adds a merge of a few short user timelines, which are themselves hot and cached; the alternative is minutes of write lag and a burst of millions of writes per celebrity tweet.
Definition: Slide 18: "fanout can be really slow! …especially for high follower counts". Slides 25–28 show the home timeline expressed as a query: home_timeline:raffi becomes home_timeline:raffi OR user_timeline:taylorswift13, i.e. the reader's precomputed list unioned with the user timeline of a high-follower account they follow. The threshold, and whether the merge runs in Timeline Service or elsewhere, are not on the slides: inference that it is a follower-count cut-off decided per author.
reader @r follows 300 normal accounts + @celebrity (30M followers)
1 @celebrity tweets 2001 -> stored in user_timeline:@celebrity; Fanout skips the 30M push
2 @normal tweets 2002 -> RPUSHX home:@r 2002 (normal fan-out)
3 @r reads home
4 LRANGE home:@r -> [2002, 1990, ...]
5 newest N of user_timeline:@celebrity -> [2001, 1985, ...]
6 merge by id (Snowflake ids are time ordered), dedupe, take N -> [2002, 2001, 1990, ...]Real scenario: a pop star with 31 million followers (slide 20 lists @ladygaga at 31 million) posts during an awards show; a breaking-news account posts every minute during an election; a brand account suddenly goes viral. In all three the read-time merge caps write cost at one append to the author's own timeline.
What provides it:
| Policy | Write cost per tweet | Read cost | Freshness for followers |
|---|---|---|---|
| Pure push | one append per cached follower | one list read | seconds to minutes for huge accounts |
| Pure pull | one append | one query per followed account | immediate, but slow reads |
| Hybrid (Twitter 2012) | one append per follower of normal authors; one append for heavy authors | one list read + one per followed heavy account | seconds for normal, immediate for heavy |
Fix / how to use it: Service.Threshold in the Go package and timelines.heavy_threshold in the Laravel job; the lab measures the trade-off on a synthetic graph.
Snowflake ids: k-ordered 64-bit ids without coordination Must-know
In plain words: Every tweet needs a unique number that roughly sorts by time, generated on many machines without asking each other.
Common misunderstanding: "Snowflake ids are strictly increasing across Twitter." They are k-sorted: "We’re aiming to keep our k below 1 second" (Snowflake post, footnote). Two tweets from different machines within a second can be out of order.
Definition: "we settled on a composition of: timestamp, worker number and sequence number" (Snowflake post, 2010). The README fixes the layout: 41-bit millisecond time with a custom epoch ("gives us 69 years"), a 10-bit configured machine id, and a 12-bit sequence that "rolls over every 4096 per machine". The 2010 IdWorker.scala splits the machine id into 5 datacenter bits and 5 worker bits, uses epoch 1288834974657, and on a backwards clock throws "Clock moved backwards. Refusing to generate id for %d milliseconds". Worker numbers "are chosen at startup via zookeeper (though that’s overridable via a config file)".
worker dc=1,w=7 worker dc=2,w=3
1 t=1000ms seq=0 -> id A
2 t=1000ms seq=1 -> id B (B > A)
3 t=999ms (clock 1 ms behind) seq=0 -> id C (C < A)
4 readers sort A, B, C by id -> C, A, B: within 1 ms of truth, the "k" in k-sorted
5 t=998ms after NTP step back -> refuse: "Clock moved backwards"Real scenario: tweet ids in public API pagination (since_id-style "look things up since this id", README); sharded tweet storage that lost MySQL auto-increment when Gizzard started hashing tweets ("Snowflake was born to solve that problem", TPS post); the home-timeline merge in the hybrid path relies on ids sorting by time.
What provides it:
| Option Twitter considered (Snowflake post) | Why rejected |
|---|---|
| MySQL ticket servers (Flickr style) | no ordering guarantee without a re-sync routine |
| UUIDs | all schemes found needed 128 bits |
| ZooKeeper sequential nodes | performance, and coordination would lower availability |
| Chosen: time + machine + sequence | uncoordinated, 64-bit, roughly sortable |
Fix / how to use it: snowflake.go and SnowflakeId.php. The general comparison with UUIDv7, ULID and ticket servers lives in ID Generation at Scale.
Storage: temporal MySQL → Gizzard/T-Bird → Manhattan; FlockDB; Blobstore Must-know
In plain words: Twitter moved from "add a new MySQL database when the current one is full" to hashing tweets across many MySQL servers, then to its own distributed key-value database; the follow graph and media each got a dedicated store.
Common misunderstanding: "FlockDB is a graph database for traversals." Twitter says "it isn’t a database optimized for graph-traversal operations"; it is optimised for very large adjacency lists, fast reads and writes, and page-able set arithmetic (FlockDB post).
Definition, per store:
- Temporal sharding (to 2010–2012). One row per tweet, stored in order; "when the database filled up we spun up another one" (TPS post). Problem: all writes hit one master and reads concentrated on the "most recent" database.
- Gizzard and T-Bird. Gizzard is "a middleware networking service that manages partitioning data across arbitrary backend datastores", with a forwarding table mapping key ranges to shards and eventual consistency by "requiring that all write-operations are idempotent AND commutative" (Gizzard post). Applied to tweets it became T-Bird: "every time a tweet comes into the system, Gizzard hashes it, and then chooses an appropriate database" (TPS post).
- FlockDB. Edges between 64-bit node ids with a 64-bit position for sorting (a timestamp for the following graph), deleted edges marked by state rather than removed, paging by position cursor instead of
LIMIT/OFFSET(FlockDB post). In 2017 Flock "can manage peaks over tens of million QPS, averaging our MySQL servers to 30k - 45k QPS" (2017 post). - Manhattan (April 2014). "Most of our use cases strongly favor availability over consistency, so an always-on eventually consistent database was a must." Layers: interfaces, storage services, storage engines (seadb read-only from Hadoop, sstable LSM, btree) and core; replica reconciliation plus read-repair and hinted-handoff; an opt-in Strong Consistency service with
LOCAL_CASandGLOBAL_CAS; multi-tenancy, QoS and rate limiting built in (Manhattan post). By 2017 Manhattan was "the backend for Tweets, Direct Messages, Twitter accounts, and more" and Cassandra had been deprecated (2017 post). - Blobstore (December 2012). "Twitter’s low-cost and scalable storage system" for photos: front-ends, storage nodes, a multi-DC metadata store, a blob manager, Kestrel queues for cross-DC replication, images hashed into a fixed number of virtual buckets, 256 MB pre-allocated "fat" files so a read costs a single disk seek (Blobstore post).
tweet write, 2010 (temporal) tweet write, T-Bird (Gizzard)
1 INSERT into db_current (single master) id = Snowflake.next()
2 db_current full -> spin up db_next, reconfigure shard = hash(id) via forwarding table
3 all spikes serialize on one master write to MySQL shard; retry later if it fails
4 reads pinned to the newest database reads spread over every shardWhat provides it:
| Data | Store | Consistency stance | Source |
|---|---|---|---|
| Tweets (2012) | T-Bird: Gizzard over MySQL | eventual, idempotent + commutative writes | TPS post, Gizzard post |
| Tweets, DMs, accounts (2017) | Manhattan | eventual by default, CAS opt-in | Manhattan, 2017 posts |
| Social graph | FlockDB on Gizzard/MySQL | idempotent, commutative writes | FlockDB post |
| Photos, video, large files | Blobstore | read-your-write in the receiving DC, async to others | Blobstore post |
| Analytics | Hadoop, over 500 PB in 2017 | batch | 2017 post |
Fix / how to use it: the schema keeps tweets keyed by Snowflake id with an (author_id, id DESC) index and the follow edge indexed both ways, the FlockDB shape on one PostgreSQL. Sharding mechanics: Sharding & Consistent Hashing; anti-entropy behind Manhattan's replica reconciliation: Merkle Trees & Anti-Entropy; the graph store family: Graph Databases; Blobstore's problem space: Object Storage & File Systems.
Caching: Twemcache, Redis (Nighthawk, Haplo) and Pelikan Important
In plain words: Most reads are served from memory; Twitter forked memcached, ran sharded Redis, and later built one cache framework to replace both.
Common misunderstanding: "Cache is a small optimisation." In 2017 cache was "~3% of our infrastructure" but "critical for Twitter"; in 2012 Twemcache held "over 20TB of data from over 30 services" and served "almost 2 trillion queries on any given day" (2017 post; Twemcache post).
Definition: Twemcache is Twitter's fork of memcached 1.4.4 with random eviction (evict a whole random slab to cure "slab calcification") and lock-less stats (Twemcache post). In 2017 Twitter ran dedicated and multi-tenant Twemcache clusters plus "Nighthawk (sharded Redis)", caches logically partitioned "by users, Tweets, timelines, etc.", each cluster at 10M–50M QPS, and Haplo for timelines (2017 post). The Pelikan repository describes itself as "Pelikan is Twitter's unified cache backend", API-compatible with Twemcache and Redis, written because each covered only part of Twitter's needs (per-item overhead, FLUSHALL-style footguns, latency spikes on connection churn).
rendered tweet read
1 Timeline Service -> cache GET tweet:1001 hit: return (memory)
2 miss -> Tweetypie -> Manhattan read load from disk tier
3 SET tweet:1001 (rendered form, CPU saved) "optimization for cpu" (Twemcache post)
4 reconnect storm after a cache restart throttled by per-instance connection rules (2017 post)Real scenario: "caching of Tweets" both as a disk optimisation (recent and hot tweets) and as a CPU optimisation (rendered tweets with counts), the two categories named in the Twemcache post; a process restart that triggers "DDoS-esque connect attacks against the cache tier", which Twitter throttled (2017 post).
What provides it:
| Cache | Engine | Used for (Twitter's words) |
|---|---|---|
| Twemcache | memcached 1.4.4 fork | users, tweets, rendered tweets |
| Nighthawk | sharded Redis | general caching ("users, timelines, tweets and more") |
| Haplo | customised Redis, HybridList | primary cache for tweet timelines |
| Pelikan | new framework, Twemcache/Redis compatible | unified backend |
Fix / how to use it: patterns in Caching, Redis lists and pipelining in Redis.
Search: Earlybird, a real-time inverted index on Lucene Important
In plain words: Tweets must be searchable seconds after posting; Twitter built an in-memory Lucene-based index that accepts a stream of new tweets while serving queries.
Common misunderstanding: "Twitter search was always Lucene." Until October 2010 the inverted index was built in MySQL: "we constructed our reverse indexes in MySQL" (search post, 2011).
Definition: "Earlybird, a real-time, reverse index based on Lucene" gave "an order of magnitude better performance than MySQL for real-time search" and doubled memory efficiency; Blender, launched April 2011, fans each query out to Earlybird servers and merges and re-ranks results (search post). In 2014 Twitter added a full archive index, more than 100 times the size of the real-time index (which held about a week of tweets in RAM), built offline on Hadoop and served from SSD-backed Earlybird shards (full index post). The current README describes three clusters (realtime ~7 days, protected, archive) with Ingesters reading tweets from Kafka topics and a "single writer, multiple reader structure".
1 tweet -> Ingester: annotate (language, user info), tokenize (search post 2011)
2 Ingester -> Kafka topic -> Earlybird partition appends to in-memory segment (README)
3 updater pushes engagement counts into the same docs (search post 2011)
4 query -> Blender -> all Earlybird partitions in parallel -> top-k each -> merge, re-rankReal scenario: 2,200 tweets per second indexed and 18,000 QPS served in 2011; duplicate removal with MinHash at 4 bytes per tweet; the searcher's social graph compressed into a Bloom filter for personalised ranking (search post). In 2023 the same index is the in-network candidate source for the For You timeline (README).
What provides it:
| Generation | Index | Throughput (source) |
|---|---|---|
| 2008 | MySQL B-tree reverse index | 20 TPS, 200 QPS |
| Oct 2010 | Earlybird | 1,000 TPS, 12,000 QPS |
| 2011 | Earlybird + Blender | 2,200 TPS, 18,000 QPS |
| 2014 | real-time + full archive (~half a trillion docs) | under 100 ms average latency |
Fix / how to use it: inverted-index mechanics in Search Systems and Full-Text Search; Bloom filters in Bloom Filters & Probabilistic Structures.
Real-time: Heron stream processing and the Kafka adoption (EventBus) Important
In plain words: Events (tweets, engagements, logs) flow through a pub/sub log to stream jobs; Twitter replaced its Storm with its own Heron, and its own EventBus with Kafka.
Common misunderstanding: "Twitter never used Kafka before 2018." It did: "Twitter actually used Kafka (0.7) a few years ago", dropped it for I/O cost on catch-up reads and missing replication, then came back (Kafka adoption post).
Definition: Heron is "a real-time analytics platform that is fully API-compatible with Storm", with a topology master, stream managers, process-isolated Heron instances and back pressure; Twitter reported throughput "10–14x higher than that of Storm in all experiments" and a 3× hardware reduction (Heron post). EventBus was built on Apache DistributedLog with separate serving and storage layers; Kafka won on "cost and community": 68% resource savings for single-consumer and 75% for fan-out cases in Twitter's evaluation, and the team had to accept acknowledging writes before fsync because of replication (Kafka adoption post).
1 Write API -> event "tweet created" -> Kafka topic (2018+)
2 Heron topology: spout reads topic -> bolts count engagements per second
3 results -> Manhattan Timeseries Counters / search updater / ads systems
4 slow bolt -> Heron back pressure slows the spout instead of dropping dataWhat provides it:
| Aspect | EventBus (DistributedLog) | Kafka (Twitter's evaluation) |
|---|---|---|
| Layers | serving and storage separate (extra hop) | one process serves and stores |
| Durability | ack after fsync | ack after replication, OS flushes later |
| Replication | quorum writes in parallel | leader then followers |
| Cost | more machines | 68–75% fewer resources |
| Community | about eight engineers | hundreds of contributors |
Fix / how to use it: Kafka in Depth, Stream Processing.
Infrastructure: Finagle RPC, Finatra, Zipkin tracing, Mesos/Aurora, Kubernetes Important
In plain words: Every service talks through one RPC library that handles pools, timeouts, load balancing and tracing; a scheduler places services on a shared cluster.
Common misunderstanding: "Microservices were the fix." The TPS post says the services split worked only together with a uniform concurrency and failure model: "we had no consistent back-pressure mechanism" and "thundering herds" before Finagle and Futures.
Definition:
- Finagle, "a protocol-agnostic, asynchronous RPC system for the JVM", bundles connection pools, failure detectors, failover, least-connections load balancing, back-pressure and Dapper-style tracing, built on Futures, Services and Filters (Finagle post). Finatra is a "lightweight framework for building fast, testable, scala applications" on TwitterServer and Finagle (README).
- Zipkin: "we implemented a basic version of the Google Dapper paper for Thrift"; sampled requests carry trace ids, collected via Scribe into Cassandra (Zipkin post).
- Aurora on Mesos: Aurora uses Apache Mesos to schedule and reschedule services; "Today, all new stateless services – and most existing services – run on Aurora" (Aurora post, 2015). By 2017 Twitter had "migrated nearly all of our main caching to Mesos" (2017 post).
- Kubernetes: secondary reports describe a later Twitter announcement of a move from Mesos to Kubernetes; we found no fetchable Twitter-owned post, so treat it as unverified here.
1 Timeline Service (Finagle client) -> Tweetypie: request with trace id, deadline
2 Finagle: pick host (least-connections), fail over from a slow host
3 span annotations: cs, sr, ss, cr (client send ... client receive; Krikorian slide 41 shows them in Zipkin)
4 Aurora restarts a crashed instance on a healthy Mesos agentWhat provides it: gRPC & Protobuf and Service Communication for the RPC layer today; Observability: Logs, Metrics, Traces for Zipkin's successors; Containers & Kubernetes for scheduling.
| Twitter tool | Job | Today's common equivalent (inference) |
|---|---|---|
| Finagle | RPC client/server with resilience | gRPC + Envoy/Istio policies |
| Finatra | HTTP/Thrift service framework | framework on top of gRPC/HTTP |
| Zipkin | distributed tracing | OpenTelemetry + Jaeger/Zipkin |
| Aurora on Mesos | service scheduler | Kubernetes Deployments |
| Decider | runtime feature switches | feature-flag service |
Reliability: fail whale, capacity and the 2010 re-architecture Must-know
In plain words: Twitter's early outages came from one Rails monolith on one MySQL master; it rebuilt the stack so that a 25× spike was a non-event.
Common misunderstanding: "The fail whale was a capacity problem solved by more servers." Twitter wrote that it was "throwing machines at the problem" and that the Rails hosts served only 200–300 requests per second each; the fix was architectural (JVM services at 10–20K requests per second per host, sharded storage, isolation) (TPS post).
Definition: The Fail Whale was the error page users saw when the site failed: "In the worst case, the user sees a Fail Whale" (Finagle post). On 3 August 2013 (Japan time) "we hit a one-second peak of 143,199 Tweets per second" while "our users didn’t experience a blip" (TPS post). Tools named in the same post: Viz metrics and Zipkin through Finagle, and Decider, a runtime switch to turn features on for a percentage of traffic. Manhattan adds the stance that "rare events are no longer rare at scale" and monitors p999 and p9999 latencies.
1 2010 World Cup goal -> tweet burst on a temporally sharded single-master MySQL -> fail whale
2 2010-2013: JVM services, Gizzard/T-Bird, Snowflake, Finagle, Decider
3 2013 Castle in the Sky -> 143,199 TPS (about 25x the 5,700/s average) -> no outageWhat provides it: Cascading Failures, Load Shedding, Timeouts, Retries & Jitter, Capacity Planning & Disaster Recovery. Changes after the 2022 acquisition: the only X Engineering material used here is the 2023 recommendation post and repository; we make no claims about staffing or reliability after 2022.
Ranked home timeline: the-algorithm (2023) Must-know
In plain words: The For You timeline is a funnel: gather ~1,500 candidates from several sources, score them cheaply, score the survivors with a big neural network, filter, then mix in ads and other modules.
Common misunderstanding: "Ranking replaced the follow graph." Half of For You still comes from people you follow on average ("50% In-Network Tweets and 50% Out-of-Network Tweets on average", 2023 post), and the Following tab is still reverse-chronological (Home Mixer README).
Definition: Three stages: candidate sourcing, ranking with a machine-learning model, and heuristics and filters (2023 post). The repository names the pieces: candidate sources (Earlybird search index for in-network, UTEG on GraphJet, tweet-mixer, follow-recommendation-service), the light ranker ("It is intended to be a simplified version of the heavy ranker which can run on a greater amount of tweets", a logistic regression in Earlybird), the heavy ranker (a parallel MaskNet that outputs engagement probabilities combined "by doing a weighted sum"), and Home Mixer, built on Product Mixer, which runs feature hydration ("Fetch the ~6000 features needed for ranking"), filters and mixing with "Ads", who-to-follow modules and prompts. The pipeline "runs approximately 5 billion times per day and completes in under 1.5 seconds on average" (2023 post).
1 request For You for viewer v -> Home Mixer (Product Mixer pipelines)
2 candidate sourcing: Earlybird (in-network, light ranker) + UTEG + embeddings -> ~1500
3 feature hydration: ~6000 features
4 heavy ranker: P(fav), P(retweet), P(reply), P(negative_feedback_v2), P(report)... -> weighted sum
5 filters: visibility (block/mute/NSFW), author diversity, content balance, feedback fatigue, social proof
6 mixing: ads, who-to-follow, prompts -> response in < 1.5 s averageReal scenario: a viewer who blocks an author never sees them (visibility filtering); a viewer who keeps tapping "show less often" gets less of a topic (feedback-based fatigue); a thread is shown with its parent (conversations); an edited tweet already on the device is replaced (edited tweets). All named in the 2023 post.
What provides it:
| Stage | Component (repo) | Model / rule |
|---|---|---|
| In-network candidates | search-index (Earlybird) | light ranker, logistic regression |
| Out-of-network candidates | UTEG / GraphJet, tweet-mixer | graph traversal (~15% of Home, 2023 post) |
| Embedding candidates | SimClusters, TwHIN via representation-manager | nearest neighbours in embedding space |
| Ranking | heavy-ranker | parallel MaskNet, ~48M parameters (2023 post) |
| Filters | visibility-filters, Home Mixer heuristics | rules |
| Mixing | Home Mixer | ads, who-to-follow, prompts |
Fix / how to use it: the Go ranking package is a 120-line toy of this funnel; the generic design is in ML Systems Architecture.
ML: ranking signals, SimClusters, Real Graph and TwHIN embeddings Good to know
In plain words: Ranking uses predicted probabilities of actions (like, reply, report) and learned vectors that place users and tweets in a shared space so "similar" can be computed.
Common misunderstanding: "Likes are the main ranking signal." The heavy ranker predicts several engagements and weights them; negative feedback and reports carry negative weights (heavy-ranker README, weights dated 5 April 2023). The exact weights change at any time (same README).
Definition: Real Graph predicts "the likelihood of engagement between two users"; SimClusters finds 145k communities updated every three weeks (2023 post). TwHIN learns knowledge-graph embeddings over Twitter's heterogeneous information network of users, tweets and advertisers, and reports gains in "personalized ads rankings, account follow-recommendation, offensive content detection, and search ranking" (TwHIN paper abstract). In the 2017 ranked timeline the features were the tweet (recency, media, interactions), the author (your past interactions with them) and you (2017 post).
| Signal family (source) | Examples |
|---|---|
| Engagement labels (heavy-ranker README) | fav, retweet, reply, good profile click, video playback 50%, reply engaged by author, negative feedback, report |
| Tweet features (2017 post) | recency, media cards, total interactions |
| Author features (2017 post) | your past interactions, connection strength, origin of the relationship |
| Graph and embeddings (2023 post, TwHIN) | Real Graph score, SimClusters community, TwHIN vectors |
Ads. Ads appear in the mixing stage (2023 post, Home Mixer README); Aurora hosted "Twitter’s ad-serving platform" (Aurora post); TwHIN is used for ads ranking (paper). The ads auction itself is outside this chapter. Vector retrieval mechanics: Vector Search & pgvector.
What changed over time
| Date (post) | Change | Driver stated by Twitter |
|---|---|---|
| 2008 (search post) | Summize search on Rails + MySQL | acquisition |
| Apr 2010 (Gizzard) | Sharding framework extracted | several custom stores shared code |
| May 2010 (FlockDB) | Graph store on Gizzard + MySQL | follower lists too large for relational tables |
| Jun 2010 (Snowflake) | Uncoordinated 64-bit ids | moving off MySQL auto-increment |
| Oct 2010 (search post) | Earlybird replaces MySQL search | real-time indexing and performance |
| 2010–2013 (TPS post) | Rails monolith → JVM services, T-Bird | World Cup outages, 200–300 req/s per Rails host |
| Aug 2011 (Finagle) | One RPC stack | inconsistent failure handling across protocols |
| Jun–Dec 2012 | Zipkin, Twemcache, Blobstore, timelines talk | latency visibility, cache predictability, native photos |
| Apr 2014 (Manhattan) | Own distributed KV database | lower latency than open-source stores, self-service |
| Nov 2014 (full index) | Every public tweet searchable | long-standing product goal |
| Feb 2015 (Aurora) | Services on Aurora/Mesos | automation across tens of thousands of machines |
| Jun 2015 (Heron) | Heron replaces Storm | predictability, debugging, efficiency |
| 2016–2017 | Ranked timeline with deep learning | relevance |
| Nov 2018 (Kafka) | Kafka replaces EventBus | cost and community |
| Mar 2023 (algorithm post) | Ranking code open-sourced; Fanout Service no longer used | transparency |
Pattern (inference): Twitter repeatedly built an in-house system when open-source options lacked a property it needed (real-time Lucene, Storm-compatible predictability, low-latency KV), and later moved back to community software once it matured (Kafka), citing hiring and maintenance.
What you can copy
| Twitter subsystem | Generic chapter | What to take |
|---|---|---|
| Redis timeline cache + Fanout | Feeds: Fan-out & Fan-in | store ids only; append only to existing lists |
| Hybrid for celebrities | Feeds, Top-K & Heavy Hitters | a follower-count threshold, read-time merge |
| Snowflake | ID Generation at Scale | time-prefixed 64-bit ids, refuse on clock skew |
| Gizzard / T-Bird | Sharding & Consistent Hashing, Consistent Hashing | hash by id, forwarding table, idempotent writes |
| FlockDB | Graph Databases, Pagination | adjacency lists, cursor by position, no OFFSET |
| Manhattan | Consistency Models, Replication Topologies | eventual by default, CAS when needed |
| Blobstore | Object Storage & File Systems | virtual buckets, metadata separate from data |
| Twemcache / Pelikan / Redis | Caching, Redis | cluster per use case, throttle reconnects |
| Earlybird | Search Systems | in-memory real-time tier + archive tier |
| Heron, Kafka | Stream Processing, Kafka | back pressure, log-based pub/sub |
| Finagle, Zipkin | Service Communication, Observability | one client library with timeouts and tracing |
| Aurora/Mesos | Containers & Kubernetes | declarative scheduling |
| For You funnel | ML Systems Architecture | cheap model before expensive model |
| Rails → services | Strangler Fig Migration | carve out "core nouns" first |
Mechanics
The knobs that appear in the sources
| Knob | Value | Source |
|---|---|---|
| Timeline entry | tweet id 8 B, user id 8 B, bits 4 B | slide 9 |
| Insert command | RPUSHX (append only if list exists) | slide 10 |
| Pipeline size | 4k destinations | slide 8 |
| Snowflake time bits | 41 (ms, custom epoch, ~69 years) | README |
| Snowflake machine bits | 10 = 5 datacenter + 5 worker | README, IdWorker.scala |
| Snowflake sequence | 12 bits, 4096 per ms per machine | README |
| Snowflake epoch | 1288834974657 | IdWorker.scala |
| Snowflake target | 10k ids/s per process, 2 ms response | README |
| Blobstore fat file | ~256 MB preallocated with fallocate() | Blobstore post |
| Candidates per For You request | ~1500 | 2023 post |
| Features hydrated | ~6000 | Home Mixer README |
| Heavy ranker size | ~48M parameters, ten labels | 2023 post |
| Our assumption | 800 entries per cached timeline, 100,000-follower threshold | this page (inference) |
Messages and errors you will see
| Where | Text | Meaning |
|---|---|---|
| Snowflake IdWorker (2010) | Clock moved backwards. Refusing to generate id for %d milliseconds | wall clock went back; ids would collide or reorder |
| Our Go generator | clock moved backwards: refusing to generate id for 3 milliseconds | same rule, wrapped ErrClockMovedBackwards |
| Our Go generator | datacenter id 32 out of range 0..31 | only 5 bits available |
| Our PHP generator | datacenter and worker must be in 0..31 | same |
Redis RPUSHX on a missing key | integer reply 0 (Redis docs: "only if key already exists") | nothing written: user not cached (by design) |
| Laravel queue | job marked failed after the #[Tries(5)] attempts | fan-out batch kept failing |
Where the time goes
write: Write API -> durable tweet store -> enqueue fan-out ~ms (user sees "posted")
Fanout: followers in pages of 4k -> pipelined RPUSHX seconds for 1M followers (3.5 s p50, slide 35)
read: LRANGE (1 ms p50 / 4 ms p99, slide 33) + hydrate ids + merge heavy authors
rank: For You funnel < 1.5 s average, 220 s CPU per request spread over many machines (2023 post)Go
The Go code is a small, honest re-implementation of two mechanisms Twitter described: it is not Twitter's code, it keeps everything in memory, and every policy number that is not from a source is marked as an assumption. Module: docs/snippets/system-design/case-study-twitter/go (stdlib only, go test ./... passes).
Schema
The storage shape used by both Go and Laravel examples (PostgreSQL). A tiny version of the core query:
-- newest 50 tweets of one author: one index range scan on (author_id, id DESC)
SELECT id FROM tweets WHERE author_id = 7 ORDER BY id DESC LIMIT 50;-- Teaching schema for the case-study code (PostgreSQL syntax).
-- Tweet ids come from a Snowflake-style generator, so there is no sequence:
-- the id itself is time ordered and safe to sort on.
CREATE TABLE users (
id bigint PRIMARY KEY,
handle text NOT NULL UNIQUE,
follower_count bigint NOT NULL DEFAULT 0 -- maintained by the follow writer
);
CREATE TABLE tweets (
id bigint PRIMARY KEY, -- Snowflake id, not identity
author_id bigint NOT NULL REFERENCES users (id),
body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
-- user timeline: "newest tweets of one author" is one index range scan
CREATE INDEX tweets_author_id_id ON tweets (author_id, id DESC);
-- One row per edge, stored twice-indexed like FlockDB's forward/backward lists.
CREATE TABLE follows (
followee_id bigint NOT NULL REFERENCES users (id),
follower_id bigint NOT NULL REFERENCES users (id),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (followee_id, follower_id) -- "who follows X" for fan-out
);
CREATE INDEX follows_follower_followee ON follows (follower_id, followee_id); -- "whom does X follow"
-- Before: fan-out on read. Cost grows with how many accounts the reader follows.
SELECT t.id
FROM tweets t
WHERE t.author_id IN (SELECT f.followee_id FROM follows f WHERE f.follower_id = 42)
ORDER BY t.id DESC
LIMIT 800;
-- Hybrid read path: the heavy accounts this reader follows (merged at read time).
SELECT u.id
FROM follows f
JOIN users u ON u.id = f.followee_id
WHERE f.follower_id = 42
AND u.follower_count >= 100000;
-- Followers paged by keyset, 4000 at a time, for the fan-out worker.
SELECT follower_id
FROM follows
WHERE followee_id = 7 AND follower_id > 0
ORDER BY follower_id
LIMIT 4000;Before: fan-out on read
// Package before shows the design Twitter's 2012 talk contrasts with fan-out:
// build the home timeline at read time by querying every account the reader
// follows. It is correct, but every read costs O(following). Teaching code only.
package before
import "sort"
// Store keeps each author's own tweets (the "user timeline"), oldest first.
type Store struct {
Following map[int64][]int64 // reader -> accounts they follow
UserTimeline map[int64][]int64 // author -> tweet ids, oldest first
}
// HomeTimeline gathers every followed author's tweets, sorts by id (Snowflake
// ids are time ordered) and returns the newest n. reads counts how many
// per-author lookups one request needed.
func (s *Store) HomeTimeline(reader int64, n int) (ids []int64, reads int) {
for _, author := range s.Following[reader] {
reads++
ids = append(ids, s.UserTimeline[author]...)
}
sort.Slice(ids, func(i, j int) bool { return ids[i] > ids[j] })
if len(ids) > n {
ids = ids[:n]
}
return ids, reads
}After: hybrid fan-out with a capped, RPUSHX-style cache
// Package fanout is a teaching model of the hybrid home-timeline design that
// Twitter presented in 2012: on write, push the tweet id into each follower's
// cached timeline (a Redis list in production, appended with RPUSHX so only
// already-cached timelines grow, pipelined about 4k destinations at a time);
// for accounts with very many followers, skip the push and merge their own
// timeline in at read time. Everything here is in memory; it is not Twitter's
// code and the threshold policy is an assumption for the example.
package fanout
import (
"sort"
"sync"
)
// PipelineBatch is the number of destinations written per round trip.
const PipelineBatch = 4000
// Cache models a set of capped Redis lists keyed by recipient.
type Cache struct {
mu sync.Mutex
lists map[int64][]int64 // oldest first, like RPUSH order
cap int
}
// NewCache creates a cache whose lists are trimmed to cap entries.
func NewCache(capacity int) *Cache {
return &Cache{lists: make(map[int64][]int64), cap: capacity}
}
// PushIfCached appends only when the list exists (RPUSHX semantics) and trims
// to the newest cap entries (LTRIM key -cap -1). It reports whether it wrote.
func (c *Cache) PushIfCached(user, tweet int64) bool {
c.mu.Lock()
defer c.mu.Unlock()
l, ok := c.lists[user]
if !ok {
return false
}
l = append(l, tweet)
if len(l) > c.cap {
l = l[len(l)-c.cap:]
}
c.lists[user] = l
return true
}
// Warm stores a freshly materialised timeline (newest first input).
func (c *Cache) Warm(user int64, newestFirst []int64) {
c.mu.Lock()
defer c.mu.Unlock()
l := make([]int64, 0, len(newestFirst))
for i := len(newestFirst) - 1; i >= 0; i-- {
l = append(l, newestFirst[i])
}
if len(l) > c.cap {
l = l[len(l)-c.cap:]
}
c.lists[user] = l
}
// Read returns up to n ids newest first and whether the list was cached.
func (c *Cache) Read(user int64, n int) ([]int64, bool) {
c.mu.Lock()
defer c.mu.Unlock()
l, ok := c.lists[user]
if !ok {
return nil, false
}
out := make([]int64, 0, min(n, len(l)))
for i := len(l) - 1; i >= 0 && len(out) < n; i-- {
out = append(out, l[i])
}
return out, true
}
// Service wires the social graph, the per-author timelines and the cache.
type Service struct {
Cache *Cache
Followers map[int64][]int64 // author -> followers
Following map[int64][]int64 // reader -> authors
UserTimeline map[int64][]int64 // author -> own tweets, oldest first
// Threshold: authors with at least this many followers are not fanned
// out on write. Zero disables the hybrid path (push for everyone).
Threshold int
}
// WriteStats describes the cost of one tweet.
type WriteStats struct {
CacheWrites int // lists actually appended
Batches int // pipeline round trips
Skipped bool // author treated as high-follower: no push
}
func (s *Service) isHeavy(author int64) bool {
return s.Threshold > 0 && len(s.Followers[author]) >= s.Threshold
}
// OnTweet records the tweet and fans it out unless the author is heavy.
func (s *Service) OnTweet(author, tweet int64) WriteStats {
s.UserTimeline[author] = append(s.UserTimeline[author], tweet)
if s.isHeavy(author) {
return WriteStats{Skipped: true}
}
var st WriteStats
followers := s.Followers[author]
for start := 0; start < len(followers); start += PipelineBatch {
end := min(start+PipelineBatch, len(followers))
st.Batches++
for _, f := range followers[start:end] {
if s.Cache.PushIfCached(f, tweet) {
st.CacheWrites++
}
}
}
return st
}
// HomeTimeline returns the newest n ids for reader: the cached list (rebuilt
// from user timelines on a miss) merged with the timelines of followed heavy
// authors, deduplicated, newest first.
func (s *Service) HomeTimeline(reader int64, n int) []int64 {
cached, ok := s.Cache.Read(reader, n)
if !ok {
cached = s.rebuild(reader)
s.Cache.Warm(reader, cached)
if len(cached) > n {
cached = cached[:n]
}
}
merged := append([]int64(nil), cached...)
for _, a := range s.Following[reader] {
if s.isHeavy(a) {
tl := s.UserTimeline[a]
for i := len(tl) - 1; i >= 0 && i >= len(tl)-n; i-- {
merged = append(merged, tl[i])
}
}
}
sort.Slice(merged, func(i, j int) bool { return merged[i] > merged[j] })
out := merged[:0]
var last int64 = -1
for _, id := range merged {
if id != last {
out = append(out, id)
last = id
}
if len(out) == n {
break
}
}
return out
}
// rebuild materialises a timeline from the non-heavy authors the reader
// follows; heavy authors are merged at read time anyway.
func (s *Service) rebuild(reader int64) []int64 {
var ids []int64
for _, a := range s.Following[reader] {
if !s.isHeavy(a) {
ids = append(ids, s.UserTimeline[a]...)
}
}
sort.Slice(ids, func(i, j int) bool { return ids[i] > ids[j] })
return ids
}Snowflake-style id generator
// Package snowflake is a teaching re-implementation of the id layout that
// Twitter described for Snowflake in 2010 (41-bit millisecond time, 10-bit
// machine id split into 5-bit datacenter and 5-bit worker, 12-bit sequence).
// It is not Twitter's code.
package snowflake
import (
"errors"
"fmt"
"sync"
"time"
)
// TwEpoch is the custom epoch (milliseconds since the Unix epoch) used by the
// 2010 IdWorker.scala source.
const TwEpoch int64 = 1288834974657
const (
datacenterBits = 5
workerBits = 5
sequenceBits = 12
maxDatacenter = -1 ^ (-1 << datacenterBits) // 31
maxWorker = -1 ^ (-1 << workerBits) // 31
sequenceMask = -1 ^ (-1 << sequenceBits) // 4095
workerShift = sequenceBits
datacenterShift = sequenceBits + workerBits
timestampShift = sequenceBits + workerBits + datacenterBits // 22
)
// ErrClockMovedBackwards mirrors the refusal in the original service: never
// hand out an id whose time is earlier than the last one.
var ErrClockMovedBackwards = errors.New("clock moved backwards")
// Generator produces k-ordered 64-bit ids without talking to any other node.
type Generator struct {
mu sync.Mutex
datacenter int64
worker int64
lastMs int64
sequence int64
now func() int64 // milliseconds since Unix epoch; injectable for tests
}
// New validates the machine identity. In production the worker number came
// from ZooKeeper at startup (overridable by config); here the caller passes it.
func New(datacenter, worker int64) (*Generator, error) {
if datacenter < 0 || datacenter > maxDatacenter {
return nil, fmt.Errorf("datacenter id %d out of range 0..%d", datacenter, maxDatacenter)
}
if worker < 0 || worker > maxWorker {
return nil, fmt.Errorf("worker id %d out of range 0..%d", worker, maxWorker)
}
return &Generator{
datacenter: datacenter,
worker: worker,
lastMs: -1,
now: func() int64 { return time.Now().UnixMilli() },
}, nil
}
// Next returns the next id or ErrClockMovedBackwards.
func (g *Generator) Next() (int64, error) {
g.mu.Lock()
defer g.mu.Unlock()
ts := g.now()
if ts < g.lastMs {
return 0, fmt.Errorf("%w: refusing to generate id for %d milliseconds", ErrClockMovedBackwards, g.lastMs-ts)
}
if ts == g.lastMs {
g.sequence = (g.sequence + 1) & sequenceMask
if g.sequence == 0 { // 4096 ids used in this millisecond: wait for the next one
for ts <= g.lastMs {
ts = g.now()
}
}
} else {
g.sequence = 0
}
g.lastMs = ts
return (ts-TwEpoch)<<timestampShift | g.datacenter<<datacenterShift | g.worker<<workerShift | g.sequence, nil
}
// Parts is a decoded id.
type Parts struct {
Time time.Time
Datacenter int64
Worker int64
Sequence int64
}
// Decode splits an id back into its fields; ids are directly sortable by time.
func Decode(id int64) Parts {
ms := id>>timestampShift + TwEpoch
return Parts{
Time: time.UnixMilli(ms).UTC(),
Datacenter: (id >> datacenterShift) & maxDatacenter,
Worker: (id >> workerShift) & maxWorker,
Sequence: id & sequenceMask,
}
}A toy For You funnel
// Package ranking is a toy version of the funnel that the 2023 open-sourced
// "the-algorithm" repository documents for the For You timeline: candidate
// sourcing -> light ranker -> heavy ranker (weighted sum of predicted
// engagement probabilities) -> filters and heuristics -> mixing with ads.
// The scoring functions are supplied by the caller; this is not X's code.
package ranking
import (
"sort"
)
// Candidate is one tweet proposed by a candidate source.
type Candidate struct {
TweetID int64
AuthorID int64
InNetwork bool
Source string
}
// Source fetches candidates for a viewer (in-network search index,
// out-of-network graph traversal, embeddings ...).
type Source func(viewer int64) []Candidate
// Item is one entry in the served timeline.
type Item struct {
Kind string // "tweet" or "ad"
ID int64
Score float64
}
// Pipeline holds the funnel configuration.
type Pipeline struct {
Sources []Source
LightLimit int // candidates kept after the cheap model
Light func(Candidate) float64 // cheap score, runs on every candidate
Heavy func(Candidate) map[string]float64 // predicted engagement probabilities
Weights map[string]float64 // label -> weight (may be negative)
Blocked func(viewer, author int64) bool // visibility filtering
MaxPerAuthor int // author diversity
AdEvery int // insert an ad after every N tweets
Ads []int64
HeavyCalls int // instrumentation for tests and the lab
}
type scored struct {
c Candidate
score float64
}
// Run builds a timeline of at most size tweets (plus ads).
func (p *Pipeline) Run(viewer int64, size int) []Item {
// 1. candidate sourcing with de-duplication across sources
seen := map[int64]bool{}
var cands []Candidate
for _, src := range p.Sources {
for _, c := range src(viewer) {
if !seen[c.TweetID] {
seen[c.TweetID] = true
cands = append(cands, c)
}
}
}
// 2. visibility filtering before spending model time
kept := cands[:0]
for _, c := range cands {
if p.Blocked == nil || !p.Blocked(viewer, c.AuthorID) {
kept = append(kept, c)
}
}
// 3. light ranker: cheap score on everything, keep the top LightLimit
light := make([]scored, len(kept))
for i, c := range kept {
light[i] = scored{c, p.Light(c)}
}
sortDesc(light)
if len(light) > p.LightLimit {
light = light[:p.LightLimit]
}
// 4. heavy ranker: weighted sum of predicted probabilities
heavy := make([]scored, len(light))
for i, s := range light {
p.HeavyCalls++
var total float64
for label, prob := range p.Heavy(s.c) {
total += p.Weights[label] * prob
}
heavy[i] = scored{s.c, total}
}
sortDesc(heavy)
// 5. heuristics: author diversity
perAuthor := map[int64]int{}
var out []Item
tweets := 0
adIdx := 0
for _, s := range heavy {
if tweets == size {
break
}
if p.MaxPerAuthor > 0 && perAuthor[s.c.AuthorID] >= p.MaxPerAuthor {
continue
}
perAuthor[s.c.AuthorID]++
out = append(out, Item{Kind: "tweet", ID: s.c.TweetID, Score: s.score})
tweets++
// 6. mixing: blend non-tweet content
if p.AdEvery > 0 && tweets%p.AdEvery == 0 && adIdx < len(p.Ads) {
out = append(out, Item{Kind: "ad", ID: p.Ads[adIdx]})
adIdx++
}
}
return out
}
func sortDesc(s []scored) {
sort.SliceStable(s, func(i, j int) bool {
if s[i].score != s[j].score {
return s[i].score > s[j].score
}
return s[i].c.TweetID > s[j].c.TweetID
})
}The Go angle
sync.Mutexaround the generator is enough: Snowflake's guarantee is per process, uniqueness across processes comes from the (datacenter, worker) pair, which the original took from ZooKeeper at startup.time.Now().UnixMilli()reads the wall clock; Go's monotonic reading is not used for ids because the id must encode real time. That is exactly why the backwards-clock check exists.- In a real service the cache is
github.com/redis/go-redis/v9withPipelinedandRPushX/LTrim; the in-memoryCachekeeps the tests hermetic. - The fan-out loop is a natural worker pool: page followers by keyset (
follower_id > last), send one pipeline per page, bound concurrency so one celebrity under the threshold cannot starve others.
Laravel
The Laravel 13 side uses the Redis facade (any command is passed through; Redis::pipeline batches them), the query builder's chunkById, and queued jobs with the #[Tries] and #[Backoff] attributes, all as documented on laravel.com for 13.x.
Before
<?php
namespace App\Timelines;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* Before: build the home timeline on every request (fan-out on read).
* Correct and simple, but each read scans every followed author's tweets.
*/
final class PullHomeTimeline
{
/** @return Collection<int, int> tweet ids, newest first */
public function for(int $readerId, int $limit = 800): Collection
{
return DB::table('tweets')
->whereIn('author_id', function ($query) use ($readerId) {
$query->select('followee_id')
->from('follows')
->where('follower_id', $readerId);
})
->orderByDesc('id')
->limit($limit)
->pluck('id')
->map(fn ($id) => (int) $id);
}
}After: the fan-out job
<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
/**
* After (write path): push a new tweet id into followers' cached timelines.
* RPUSHX only appends to lists that already exist, so inactive users cost
* nothing; heavy authors are skipped and merged at read time instead.
* A retried job can append the same id twice: the read path de-duplicates.
*/
#[Tries(5)]
#[Backoff([1, 5, 10])]
final class FanoutTweet implements ShouldQueue
{
use Queueable;
public const TIMELINE_LENGTH = 800;
public const BATCH = 4000;
public function __construct(
public int $authorId,
public int $tweetId,
) {}
public function handle(): void
{
$followerCount = (int) DB::table('users')->where('id', $this->authorId)->value('follower_count');
if ($followerCount >= config('timelines.heavy_threshold', 100_000)) {
return; // hybrid: readers pull this author's timeline at read time
}
DB::table('follows')
->select('follower_id')
->where('followee_id', $this->authorId)
->chunkById(self::BATCH, function ($rows) {
Redis::pipeline(function ($pipe) use ($rows) {
foreach ($rows as $row) {
$key = "timeline:home:{$row->follower_id}";
$pipe->rpushx($key, $this->tweetId);
$pipe->ltrim($key, -self::TIMELINE_LENGTH, -1);
}
});
}, 'follower_id');
}
}After: the read path with read-time merge
<?php
namespace App\Timelines;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
/**
* After (read path): cached list + heavy authors merged at read time.
* On a cache miss the list is rebuilt from the database and kept for a day,
* so only recently active users occupy memory.
*/
final class HomeTimeline
{
public function __construct(
private readonly int $heavyThreshold = 100_000,
private readonly int $ttlSeconds = 86_400,
) {}
/** @return list<int> tweet ids, newest first */
public function for(int $readerId, int $limit = 50): array
{
$key = "timeline:home:{$readerId}";
if (Redis::exists($key)) {
// drop the 0 sentinel written for users who follow nobody yet
$cached = array_values(array_filter(array_map('intval', Redis::lrange($key, -$limit, -1))));
} else {
$cached = $this->rebuild($readerId, $key);
}
$heavyAuthors = DB::table('follows')
->join('users', 'users.id', '=', 'follows.followee_id')
->where('follows.follower_id', $readerId)
->where('users.follower_count', '>=', $this->heavyThreshold)
->pluck('users.id');
$fromHeavy = $heavyAuthors->isEmpty() ? [] : DB::table('tweets')
->whereIn('author_id', $heavyAuthors)
->orderByDesc('id')
->limit($limit)
->pluck('id')
->map(fn ($id) => (int) $id)
->all();
$ids = array_values(array_unique(array_merge($cached, $fromHeavy)));
rsort($ids); // Snowflake ids sort by time
return array_slice($ids, 0, $limit);
}
/** @return list<int> */
private function rebuild(int $readerId, string $key): array
{
$ids = DB::table('tweets')
->whereIn('author_id', function ($query) use ($readerId) {
$query->select('follows.followee_id')
->from('follows')
->join('users', 'users.id', '=', 'follows.followee_id')
->where('follows.follower_id', $readerId)
->where('users.follower_count', '<', $this->heavyThreshold);
})
->orderByDesc('id')
->limit(800)
->pluck('id')
->map(fn ($id) => (int) $id)
->all();
Redis::pipeline(function ($pipe) use ($key, $ids) {
$pipe->del($key);
if ($ids !== []) {
$pipe->rpush($key, ...array_reverse($ids)); // oldest first, like RPUSH order
} else {
$pipe->rpush($key, 0); // sentinel keeps the key alive so RPUSHX works
}
$pipe->expire($key, $this->ttlSeconds);
});
return $ids;
}
}Snowflake-style ids in PHP
<?php
namespace App\Support;
use RuntimeException;
/**
* Snowflake-style 64-bit id: 41 bits of milliseconds since a custom epoch,
* 5 bits datacenter, 5 bits worker, 12 bits sequence. Teaching code, not
* Twitter's. State lives in this object, so each PHP worker process needs
* its own unique (datacenter, worker) pair, e.g. assigned at boot.
*/
final class SnowflakeId
{
public const EPOCH_MS = 1288834974657;
private int $lastMs = -1;
private int $sequence = 0;
private ?int $offset = null;
public function __construct(
private readonly int $datacenter,
private readonly int $worker,
) {
if ($datacenter < 0 || $datacenter > 31 || $worker < 0 || $worker > 31) {
throw new RuntimeException('datacenter and worker must be in 0..31');
}
}
public function next(): int
{
$now = $this->nowMs();
if ($now < $this->lastMs) {
throw new RuntimeException(sprintf(
'Clock moved backwards. Refusing to generate id for %d milliseconds',
$this->lastMs - $now,
));
}
if ($now === $this->lastMs) {
$this->sequence = ($this->sequence + 1) & 0xFFF;
if ($this->sequence === 0) {
while ($now <= $this->lastMs) {
$now = $this->nowMs();
}
}
} else {
$this->sequence = 0;
}
$this->lastMs = $now;
return (($now - self::EPOCH_MS) << 22)
| ($this->datacenter << 17)
| ($this->worker << 12)
| $this->sequence;
}
/** @return array{ms: int, datacenter: int, worker: int, sequence: int} */
public static function decode(int $id): array
{
return [
'ms' => ($id >> 22) + self::EPOCH_MS,
'datacenter' => ($id >> 17) & 31,
'worker' => ($id >> 12) & 31,
'sequence' => $id & 0xFFF,
];
}
private function nowMs(): int
{
return intdiv(hrtime(true), 1_000_000) + $this->bootOffsetMs();
}
/** hrtime is monotonic; anchor it to wall-clock time once per process. */
private function bootOffsetMs(): int
{
return $this->offset ??= (int) floor(microtime(true) * 1000) - intdiv(hrtime(true), 1_000_000);
}
}The Laravel angle
- Dispatch after commit:
FanoutTweet::dispatch($author, $id)->afterCommit()so the job never sees an uncommitted tweet. chunkById(4000, ..., 'follower_id')pages by key, never by offset, the same reason FlockDB used a position cursor.- Retries can append an id twice (
RPUSHXis not idempotent); the read path de-duplicates witharray_unique, which is cheaper than making the write idempotent. - PHP-FPM workers are separate processes: the
SnowflakeIdinstance is per process, so each worker needs its own worker id, or ids should come from one small id service. - Put fan-out on its own queue (
->onQueue('fanout')) and scale those workers separately (Horizon), so a burst of tweets does not delay emails or webhooks.
Solving the classic problems
A celebrity tweets and the fan-out queue explodes
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Hybrid fan-out (Twitter 2012) | skip push above a follower threshold, merge at read | write cost bounded | read merges extra lists |
| Rate-limited push | push in the background at a fixed rate | one read path | followers see it late |
| Push to active followers only | RPUSHX on cached lists only | memory only for active users | rebuild on return |
Inactive users waste memory
Use RPUSHX so absent lists are never created, give rebuilt lists a TTL (our Laravel code uses one day) and rebuild on the next visit from the user timelines of followed authors. Twitter's slides show RPUSHX; the TTL and rebuild policy are inference.
Timeline shows tweets out of order or twice
Sort and merge by Snowflake id; de-duplicate on read because retried fan-out may append twice. Accept that ids are k-sorted within about a second, not strictly ordered.
Ids collide or go backwards after a clock step
Refuse to issue ids while the clock is behind the last issued timestamp (as IdWorker.scala does), run NTP in slew mode, and assign worker ids centrally (ZooKeeper in the original) so no two processes share one.
One storage master cannot absorb a spike
Hash writes across shards by id (T-Bird), absorb bursts with an asynchronous fan-out queue, and shed or delay non-essential work with runtime switches (Decider). See Load Shedding.
Ranking is too expensive for every candidate
Put a cheap model in front of the expensive one (light ranker before heavy ranker), filter blocked/muted content before scoring, and cap candidates (~1500 in 2023).
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Small product, < 1M users, few follows each | fan-out on read with a good index | cache the merged page briefly | simplest, no write amplification |
| Read-heavy feed, follower counts bounded (e.g. team apps) | fan-out on write | ids only, capped lists | reads dominate |
| Follower counts heavy-tailed (public social network) | hybrid | threshold per author, read-time merge | bounds the worst write |
| Relevance more important than recency | candidate sourcing + two-stage ranking | light ranker before heavy ranker | CPU budget |
| Need global ids on many shards | Snowflake-style 64-bit | central worker-id assignment | sortable, compact |
| Store must stay up during partitions | eventual consistency, CAS opt-in | read-repair, anti-entropy | availability first |
| Small team, mature open-source exists | adopt (Kafka over EventBus) | contribute upstream | cost and community |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Twitter's starting point: Rails on MySQL, home timeline as one SQL query over followed authors (our Before.php). This is the right design for a product with thousands of users. Add the (author_id, id DESC) index and Snowflake-style ids early: they cost nothing now and remove the auto-increment dependency that later blocked sharding (TPS post).
Modular monolith: boundaries without the network
Separate the "core nouns" (tweet, timeline, user, graph) as modules with their own tables and interfaces inside one Laravel app; move fan-out into a queued job. This mirrors the first services Twitter carved out (Tweet, timeline and user services, TPS post) without paying network costs yet.
Microservices: every arrow is a decision
1 client -> Write API -> Tweet service (Tweetypie) -> store (Manhattan)
2 Tweet service -> Kafka "tweet.created"
3 Fanout consumer -> Social Graph (Flock) -> Redis timeline cache (pipelined RPUSHX)
4 Ingester consumer -> Earlybird
5 client -> Timeline service -> cache + heavy-author merge -> Tweetypie/Gizmoduck hydrationEvery hop needs deadlines, retries with budgets and tracing (Finagle and Zipkin in Twitter's case). Fan-out consumers must tolerate duplicates (Idempotent Consumers).
Distributed data: replicas, caches, regions
The timeline cache is replicated and rebuildable; the source of truth (tweets in Manhattan, graph in Flock) is replicated across data centres with eventual consistency, and strong consistency only where a check-and-set is needed. Blobstore shows the cross-DC pattern: readable immediately in the receiving data centre, replicated asynchronously, reads routed to the origin until replication lands. Replica lag and caches together mean a user may briefly not see their own tweet in a follower's view; that is accepted.
Scaling path: 1x, 10x, 100x
| Load | Design |
|---|---|
| 1× (thousands of users) | monolith, pull query, one database |
| 10× (hundreds of thousands) | queued fan-out into Redis lists, read replicas, CDN for media |
| 100× (tens of millions) | hybrid fan-out, sharded tweet and graph stores, search cluster, stream processing, ranking funnel |
Lab
The Go parts are single-process and were run; the Redis and Laravel parts are expected, not run.
1. Run the tests (run).
$ cd docs/snippets/system-design/case-study-twitter/go
$ go test ./...
? academy/case-study-twitter/before [no test files]
? academy/case-study-twitter/cmd/lab [no test files]
ok academy/case-study-twitter/fanout
ok academy/case-study-twitter/ranking
ok academy/case-study-twitter/snowflake2. Compare policies on a synthetic heavy-tailed graph (run). The program builds 20,000 users following 30 accounts each with a Zipf-skewed choice; numbers describe this toy graph, not Twitter.
// Command lab compares write and read cost of three home-timeline policies on
// a synthetic follower graph with a heavy-tailed follower distribution.
// Numbers are from this toy graph only; they are not Twitter measurements.
package main
import (
"fmt"
"math/rand/v2"
"sort"
"academy/case-study-twitter/fanout"
)
const (
users = 20000
tweets = 2000
readers = 2000
)
func main() {
r := rand.New(rand.NewPCG(1, 2))
followers := map[int64][]int64{}
following := map[int64][]int64{}
// Zipf-like: a few authors get a large share of all follow edges.
z := rand.NewZipf(r, 1.2, 1, users-1)
edges := 0
for reader := int64(0); reader < users; reader++ {
seen := map[int64]bool{}
for k := 0; k < 30; k++ {
a := int64(z.Uint64())
if a == reader || seen[a] {
continue
}
seen[a] = true
edges++
followers[a] = append(followers[a], reader)
following[reader] = append(following[reader], a)
}
}
counts := make([]int, 0, len(followers))
for _, f := range followers {
counts = append(counts, len(f))
}
sort.Sort(sort.Reverse(sort.IntSlice(counts)))
fmt.Printf("graph: %d users, %d follow edges, top author has %d followers\n", users, edges, counts[0])
fmt.Printf("%-22s %12s %14s %16s\n", "policy", "writes/tweet", "max writes", "sources/read")
for _, p := range []struct {
name string
threshold int
pull bool
}{
{"fan-out on read", 0, true},
{"fan-out on write", 0, false},
{"hybrid (>=5000)", 5000, false},
{"hybrid (>=500)", 500, false},
} {
s := &fanout.Service{
Cache: fanout.NewCache(800),
Followers: followers,
Following: following,
UserTimeline: map[int64][]int64{},
Threshold: p.threshold,
}
if !p.pull {
for u := int64(0); u < users; u++ {
s.Cache.Warm(u, nil) // every user active and cached
}
}
total, maxW := 0, 0
for i := 0; i < tweets; i++ {
author := int64(z.Uint64())
if p.pull {
s.UserTimeline[author] = append(s.UserTimeline[author], int64(i))
continue
}
st := s.OnTweet(author, int64(i))
total += st.CacheWrites
maxW = max(maxW, st.CacheWrites)
}
sources := 0
for rd := int64(0); rd < readers; rd++ {
if p.pull {
sources += len(following[rd])
continue
}
sources++ // the cached list
for _, a := range following[rd] {
if p.threshold > 0 && len(followers[a]) >= p.threshold {
sources++
}
}
}
fmt.Printf("%-22s %12.1f %14d %16.1f\n", p.name, float64(total)/tweets, maxW, float64(sources)/readers)
}
}$ go run ./cmd/lab
graph: 20000 users, 410193 follow edges, top author has 19972 followers
policy writes/tweet max writes sources/read
fan-out on read 0.0 0 20.5
fan-out on write 8869.3 19972 1.0
hybrid (>=5000) 468.5 4997 7.6
hybrid (>=500) 29.7 498 13.4Read it like slide 17: pure push makes reads one lookup and the worst tweet ~20k writes; a threshold cuts the worst write by 4–40× at the cost of merging 7–13 sources per read.
3. RPUSHX only writes cached timelines (expected, not run).
$ redis-cli RPUSHX timeline:home:42 1001
(integer) 0 # no list yet: nothing written
$ redis-cli RPUSH timeline:home:42 900
(integer) 1
$ redis-cli RPUSHX timeline:home:42 1001
(integer) 2
$ redis-cli LTRIM timeline:home:42 -800 -1
OK4. Laravel fan-out (expected, not run). Seed 10,000 followers, dispatch FanoutTweet, run php artisan queue:work --queue=fanout; expect three chunkById pages (4000 + 4000 + 2000) and three Redis pipelines; with follower_count above timelines.heavy_threshold expect zero Redis writes and the tweet to appear through HomeTimeline::for() via the heavy-author query.
5. Clock skew (run as a test). TestClockBackwardsIsRefused sets the fake clock back 3 ms and expects ErrClockMovedBackwards.
Common misconceptions
| Belief | Reality (source) |
|---|---|
| Twitter copies full tweets into each timeline | entries are ids plus flag bits, 20 bytes (slide 9) |
| Every user has a timeline in memory | RPUSHX appends only to existing lists (slide 10) |
| Fan-out on write is instant | 3.5 s p50 to deliver to 1M followers (slide 35) |
| Celebrities are fanned out like everyone else | merged at read time (slides 18–28) |
| Snowflake ids are strictly ordered | k-sorted, k below 1 second (Snowflake post) |
| FlockDB is a graph traversal engine | optimised for adjacency lists and set arithmetic (FlockDB post) |
| Manhattan is strongly consistent | eventually consistent core, strong consistency opt-in (Manhattan post) |
| Twitter search was always Lucene | MySQL reverse indexes until October 2010 (search post) |
| Kafka was new to Twitter in 2018 | Kafka 0.7 was used earlier and dropped (Kafka post) |
| The For You timeline ignores follows | ~50% in-network on average (2023 post) |
| The fail whale was fixed by adding servers | fixed by re-architecture: JVM services, sharding, isolation (TPS post) |
Cheat sheet
| Topic | Remember |
|---|---|
| Core trade-off | push: O(n) write, O(1) read; pull: O(1) write, O(n) read (slide 17) |
| Timeline cache | Redis lists of ids, RPUSHX, pipelined 4k, replicated |
| Hybrid | high-follower authors merged at read |
| 2012 load | ~5K tweets/s, >300K timeline QPS, 30B deliveries/day |
| 2013 peak | 143,199 TPS, ~25× average |
| Snowflake | 41 time + 5 dc + 5 worker + 12 seq; epoch 1288834974657 |
| Clock | refuse when the clock moves backwards |
| Storage line | temporal MySQL → Gizzard/T-Bird → Manhattan |
| Graph | FlockDB: idempotent, commutative writes, cursor paging |
| Media | Blobstore: virtual buckets, fat files, one seek |
| Cache | Twemcache, Nighthawk, Haplo, Pelikan |
| Search | Earlybird (Lucene, real-time) + Blender; archive index 2014 |
| Streams | Heron (Storm API), Kafka over EventBus (cost, community) |
| RPC | Finagle + Zipkin; Aurora on Mesos |
| For You | ~1500 candidates → light → heavy → filters → mix, < 1.5 s |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why did Twitter precompute home timelines instead of querying on read? Must-know
Answer
Answer: Reads dominated: more than 300K timeline QPS against about 5K tweets per second in 2012, so paying O(n) on write for O(1) reads (slide 17) was cheaper overall.
2 — What does RPUSHX change compared with RPUSH? Good to know
Answer
Answer: It appends only if the list already exists, so fan-out writes only to cached timelines and never creates lists for users who are not cached (slide 10).
3 — Why do high-follower accounts break pure fan-out on write? Must-know
Answer
Answer: One tweet becomes tens of millions of appends; at 3.5 s p50 for one million followers the delivery lag and burst load become unacceptable (slides 18, 20, 35).
4 — How does the hybrid read path assemble a home timeline? Must-know
Answer
Answer: It unions the reader's cached list with the user timelines of followed high-follower accounts (home_timeline:raffi OR user_timeline:taylorswift13, slide 28), sorted by id.
5 — What are the fields of a Snowflake id and their widths? Important
Answer
Answer: 41 bits of milliseconds since a custom epoch, 10 bits machine id (5 datacenter + 5 worker), 12 bits sequence (README, IdWorker.scala).
6 — What does "k-sorted" mean for Snowflake? Good to know
Answer
Answer: Ids are ordered by time only within a bound k; Twitter aimed for k below one second, so ids from different machines within a second may interleave.
7 — Why did Snowflake become necessary when tweets moved to T-Bird? Important
Answer
Answer: Gizzard hashed tweets across MySQL shards, so a single MySQL auto-increment could no longer provide unique ids (TPS post).
8 — What property did Gizzard and FlockDB require of writes, and why? Important
Answer
Answer: Idempotent and commutative writes, so failed operations can be retried later and applied in any order while still converging.
9 — What consistency did Manhattan choose by default and what is opt-in? Important
Answer
Answer: Eventual consistency by default (availability first); strong consistency via a consensus-based service with LOCAL_CAS and GLOBAL_CAS.
10 — Name the stages of the 2023 For You pipeline. Good to know
Answer
Answer: Candidate sourcing (~1500 candidates), light ranker, feature hydration, heavy ranker (weighted sum of engagement probabilities), filters and heuristics, mixing with ads and other modules in Home Mixer.
11 — Why did Twitter move from EventBus to Kafka? Important
Answer
Answer: Cost (one process serves and stores; 68–75% resource savings in its evaluation) and community (features, fixes, hiring).
12 — Which claim on this page is labelled inference and why? Must-know
Answer
Answer: For example the 800-entry timeline length, the follower threshold value and the TTL rebuild policy: the sources we read do not state them, so they are our assumptions.
Glossary
| Term | Meaning |
|---|---|
| Home timeline | tweets from accounts a user follows; precomputed per reader |
| User timeline | one author's own tweets |
| Fan-out on write | copy a new item into each follower's feed at write time |
| Fan-out on read | build the feed at read time from followed authors |
| Hybrid fan-out | push for most authors, read-time merge for high-follower ones |
| Celebrity (high follower count) | an author whose follower count makes push too costly |
| Redis timeline cache | Redis lists holding timeline entries per recipient |
| RPUSHX | Redis command that appends only to an existing list |
| Haplo | Twitter's customised Redis (HybridList) timeline cache |
| Nighthawk | Twitter's sharded Redis cache clusters |
| Twemcache | Twitter's memcached 1.4.4 fork with random eviction |
| Pelikan | Twitter's unified cache framework |
| Snowflake id | 64-bit time + machine + sequence id |
| k-ordered / k-sorted | sorted within a bound k, not strictly |
| Gizzard | Twitter's sharding middleware with a forwarding table |
| T-Bird | tweet store built with Gizzard over MySQL |
| FlockDB | Twitter's adjacency-list graph store on Gizzard/MySQL |
| Manhattan | Twitter's multi-tenant, eventually consistent KV database |
| Blobstore | Twitter's photo and large-object store |
| Earlybird | Twitter's real-time Lucene-based search index |
| Blender | search front-end that fans out to Earlybirds and merges |
| Inverted index | term → list of documents containing it |
| Heron | Twitter's Storm-compatible stream processing engine |
| EventBus | Twitter's pub/sub on DistributedLog, replaced by Kafka |
| Finagle | Twitter's protocol-agnostic async RPC library for the JVM |
| Finatra | framework for services on TwitterServer and Finagle |
| Zipkin | distributed tracing system from Twitter, after Dapper |
| Mesos / Aurora | cluster manager / service scheduler used by Twitter |
| Kubernetes | container orchestrator; reported later target platform (unverified here) |
| Decider | Twitter's runtime feature switch system |
| Fail whale | Twitter's error page shown during outages |
| Candidate sourcing | first funnel stage that gathers possible tweets |
| Light ranker | cheap model that pre-scores many candidates |
| Heavy ranker | neural network scoring the survivors |
| Home Mixer | service that builds and mixes the home timelines |
| SimClusters | community embeddings (145k communities) |
| TwHIN | knowledge-graph embeddings over Twitter's heterogeneous network |
| Ranking signals | features and predicted engagements used for scoring |
| Capacity | headroom to absorb peaks such as 25× average |
| Inference | a statement this page derives rather than reads in a source |
References
Twitter / X engineering blog (originals at blog.twitter.com/engineering/..., now blog.x.com/engineering/...; cited via Internet Archive copies):
- Announcing Snowflake (1 June 2010): https://web.archive.org/web/20231210065147/https://blog.twitter.com/engineering/en_us/a/2010/announcing-snowflake
- Introducing Gizzard (6 April 2010): https://web.archive.org/web/20240117153117/https://blog.twitter.com/engineering/en_us/a/2010/introducing-gizzard-a-framework-for-creating-distributed-datastores
- Introducing FlockDB (3 May 2010): https://web.archive.org/web/20231207010815/https://blog.twitter.com/engineering/en_us/a/2010/introducing-flockdb
- The engineering behind Twitter's new search experience (31 May 2011): https://web.archive.org/web/20231129130752/https://blog.twitter.com/engineering/en_us/a/2011/the-engineering-behind-twitter-s-new-search-experience
- Finagle: a protocol-agnostic RPC system (19 August 2011): https://web.archive.org/web/20231210230000/https://blog.twitter.com/engineering/en_us/a/2011/finagle-a-protocol-agnostic-rpc-system
- Distributed systems tracing with Zipkin (7 June 2012): https://web.archive.org/web/20231210080828/https://blog.twitter.com/engineering/en_us/a/2012/distributed-systems-tracing-with-zipkin
- Caching with Twemcache (10 July 2012): https://web.archive.org/web/20240126143858/https://blog.twitter.com/engineering/en_us/a/2012/caching-with-twemcache
- Blobstore: Twitter's in-house photo storage system (11 December 2012): https://web.archive.org/web/20231211231132/https://blog.twitter.com/engineering/en_us/a/2012/blobstore-twitter-s-in-house-photo-storage-system
- New Tweets per second record, and how! (16 August 2013): https://web.archive.org/web/20231201193734/https://blog.twitter.com/engineering/en_us/a/2013/new-tweets-per-second-record-and-how
- Manhattan, our real-time, multi-tenant distributed database (2 April 2014): https://web.archive.org/web/20231206053655/https://blog.twitter.com/engineering/en_us/a/2014/manhattan-our-real-time-multi-tenant-distributed-database-for-twitter-scale
- Building a complete Tweet index (18 November 2014): https://web.archive.org/web/20231202124641/https://blog.twitter.com/engineering/en_us/a/2014/building-a-complete-tweet-index
- All about Apache Aurora (12 February 2015): https://web.archive.org/web/20240305000854/https://blog.twitter.com/engineering/en_us/a/2015/all-about-apache-aurora
- Flying faster with Twitter Heron (2 June 2015): https://web.archive.org/web/20231204203802/https://blog.twitter.com/engineering/en_us/a/2015/flying-faster-with-twitter-heron
- The infrastructure behind Twitter: scale (19 January 2017): https://web.archive.org/web/20231204184818/https://blog.twitter.com/engineering/en_us/topics/infrastructure/2017/the-infrastructure-behind-twitter-scale
- Using deep learning at scale in Twitter's timelines (9 May 2017): https://web.archive.org/web/20240114040848/https://blog.twitter.com/engineering/en_us/topics/insights/2017/using-deep-learning-at-scale-in-twitters-timelines
- Twitter's Kafka adoption story (28 November 2018): https://web.archive.org/web/20240217154341/https://blog.twitter.com/engineering/en_us/topics/insights/2018/twitters-kafka-adoption-story
- Twitter's Recommendation Algorithm (31 March 2023): https://web.archive.org/web/20231205175704/https://blog.twitter.com/engineering/en_us/topics/open-source/2023/twitter-recommendation-algorithm
Talks, papers and repositories by Twitter / X:
- Raffi Krikorian, Timelines at Scale, QCon San Francisco 2012 (InfoQ, slides 5–35 used): https://www.infoq.com/presentations/Twitter-Timeline-Scalability/
- El-Kishky et al., TwHIN: Embedding the Twitter Heterogeneous Information Network (KDD 2022): https://arxiv.org/abs/2202.05387
- the-algorithm README: https://github.com/twitter/the-algorithm
- Home Mixer README: https://raw.githubusercontent.com/twitter/the-algorithm/main/home-mixer/README.md
- Earlybird search README: https://raw.githubusercontent.com/twitter/the-algorithm/main/src/java/com/twitter/search/README.md
- Earlybird light ranker README: https://raw.githubusercontent.com/twitter/the-algorithm/main/src/python/twitter/deepbird/projects/timelines/scripts/models/earlybird/README.md
- Heavy ranker README: https://raw.githubusercontent.com/twitter/the-algorithm-ml/main/projects/home/recap/README.md
- Snowflake README (2010 branch): https://raw.githubusercontent.com/twitter-archive/snowflake/snowflake-2010/README.mkd
- Snowflake IdWorker.scala (2010 branch): https://raw.githubusercontent.com/twitter-archive/snowflake/snowflake-2010/src/main/scala/com/twitter/service/snowflake/IdWorker.scala
- Finatra README: https://raw.githubusercontent.com/twitter/finatra/develop/README.md
- Pelikan repository: https://github.com/twitter/pelikan
Framework documentation used for the code:
- Redis RPUSHX: https://redis.io/docs/latest/commands/rpushx/
- Laravel 13 Redis: https://laravel.com/framework/docs/13.x/redis
- Laravel 13 Queues: https://laravel.com/framework/docs/13.x/queues
- Laravel 13 Query Builder: https://laravel.com/framework/docs/13.x/queries