Skip to content

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 forGo to
The whole case in three tablesEverything in one minute
Why Twitter is a hard feed problemWhy it exists
Dated history from Twitter's own postsWhere it comes from
Step 1: what the product must doScope
Step 2: the numbers Twitter publishedEstimate
Step 3: the boxesHigh-level design
Step 4: one block per subsystemTimelines, Hybrid fan-out, Snowflake, Storage, Caching, Search, Real-time, Infrastructure, Reliability, Ranked timeline, ML
What changed and whenWhat changed over time
Which generic chapter each part maps toWhat you can copy
Knobs, sizes, error messagesMechanics
CodeGo, Laravel
Celebrity storms, inactive users, id collisionsSolving the classic problems
Push, pull or hybrid for your productChoosing
Monolith to distributed systemIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The subsystems and the source for each.

SubsystemWhat Twitter built or adoptedPrimary source (date)
Home timelineFan-out on write into a Redis timeline cache; Timeline Service reads itKrikorian, Timelines at Scale (QCon SF 2012)
High-follower accountsNot fanned out; their user timeline is merged at read timeSame talk, slides 18–28
IdsSnowflake: 64-bit, time + machine + sequence, k-sortedAnnouncing Snowflake (1 June 2010) + README
Tweet storageTemporally sharded MySQL, then Gizzard-hashed MySQL (T-Bird), later ManhattanNew Tweets per second record (16 Aug 2013); Manhattan (2 Apr 2014)
Social graphFlockDB on Gizzard + MySQLIntroducing FlockDB (3 May 2010)
MediaBlobstoreBlobstore (11 Dec 2012)
CacheTwemcache (memcached fork), Nighthawk (sharded Redis), Haplo (Redis for timelines), PelikanCaching with Twemcache (10 Jul 2012); Infrastructure behind Twitter: scale (19 Jan 2017); Pelikan repo
SearchEarlybird, real-time inverted index on Lucene; Blender front-endSearch post (31 May 2011); full index (18 Nov 2014)
Streams and pub/subStorm → Heron; EventBus (DistributedLog) → KafkaHeron (2 Jun 2015); Kafka adoption (28 Nov 2018)
RPC and tracingFinagle, Finatra, ZipkinFinagle (19 Aug 2011); Zipkin (7 Jun 2012); Finatra README
SchedulingApache Aurora on Apache MesosAurora (12 Feb 2015)
Ranked For You timelineCandidate sourcing → light ranker → heavy ranker → filters → Home MixerTwitter's Recommendation Algorithm (31 Mar 2023) + the-algorithm repo
EmbeddingsSimClusters, TwHIN2023 post; TwHIN paper (KDD 2022)

The numbers Twitter published.

NumberValueSource
Tweets per day (2012)about 400 millionKrikorian slides 21, 34
Tweet input rate (2012)~5K/s average, ~7K/s daily peak, more than 12K/s in large eventsslide 34
Timeline reads (2012)more than 300K QPS, 1 ms p50 / 4 ms p99slide 33
Timeline deliveries (2012)30 billion a day, ~300K per second, 3.5 s p50 to reach 1 million followersslide 35
Record peak (2013)143,199 tweets per second, about 25× the 5,700/s averageTPS post, Aug 2013
Cache (2012)over 20 TB in memory, almost 2 trillion queries a dayTwemcache post
For You pipeline (2023)about 5 billion runs a day, under 1.5 s average, 220 s CPU per run2023 algorithm post

The decisions in one line each.

DecisionChoicePrice paid
Precompute or compute on readPrecompute (fan-out on write) for most authorsWrite amplification; seconds of delivery delay for big accounts
CelebritiesRead-time merge (hybrid fan-out)Read path does extra lookups and a merge
IdsUncoordinated, k-sorted 64-bitNo strict global order; depends on clocks
StorageAvailability over consistency (Manhattan), strong consistency opt-inConflict resolution and repair machinery
PlatformBuild 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 onceAlso copy each new tweet id into every follower's list
Home read = query all followed authors and mergeHome read = read one precomputed list
Cheap writes, expensive readsExpensive writes, cheap reads
Cost grows with how many accounts you followCost 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 ​

  1. "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).
  2. "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.
  3. "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 ​

RequirementSource of the requirementKind
Post a tweet (with media)productfunctional
Home timeline of followed accounts, newest first (later ranked)Krikorian slides 3, 13; 2017 ranking postfunctional
User timeline (one author's tweets)slide 28 (user_timeline:)functional
Real-time search over all public tweetssearch posts 2011, 2014functional
Follow / unfollow with no follower limitFlockDB postfunctional
Timeline reads in single-digit millisecondsslide 33 (1 ms p50, 4 ms p99)non-functional
Survive event spikes (25× average)TPS post 2013non-functional
Favour availability over consistencyManhattan postnon-functional
Out of scope hereDMs, ads auction, trust and safety internalsboundary

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 ​

Write APIIngesterFanoutSocial GraphServiceEarlybirdsearch index (Lucene)terms: hello, worldRedis timeline cachelist per recipient: RPUSHXpipelined ~4k destinationsBlenderTimeline Serviceheavy authors:merged at readO(1) write, O(n) readO(n) write, O(1) readSource: Krikorian, Timelines at Scale, QCon SF 2012 (slides 6-28); boxes simplified

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 timeline

Real 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:

ConcernTwitter's choice (source)Generic alternative
Storage of the listRedis native list, later Haplo HybridList (slides 9–10; 2017 post)sorted set, wide-column row (Wide-Column & Key-Value)
Only active usersRPUSHX (slide 10)TTL-based eviction
Write efficiencypipelined 4k destinations (slide 8)per-follower RPC
Durabilityreplicated cache; source of truth is tweet storagewrite-through to a store
Hydrationids 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:

PolicyWrite cost per tweetRead costFreshness for followers
Pure pushone append per cached followerone list readseconds to minutes for huge accounts
Pure pullone appendone query per followed accountimmediate, but slow reads
Hybrid (Twitter 2012)one append per follower of normal authors; one append for heavy authorsone list read + one per followed heavy accountseconds 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)".

63 ................................................................. 0 (bit positions)0timestamp: 41 bitsms since epoch 1288834974657 (about 69 years)datacenter5 bitsworker5 bitssequence: 12 bits0..4095 per msshift 22shift 17shift 12shift 0id = (ms - epoch) << 22 | datacenter << 17 | worker << 12 | sequencek-sorted: ids from different machines created within ~1 s may interleaveClock moved backwards: refuse to issue ids until time passes the last one
   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
UUIDsall schemes found needed 128 bits
ZooKeeper sequential nodesperformance, and coordination would lower availability
Chosen: time + machine + sequenceuncoordinated, 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_CAS and GLOBAL_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 shard

What provides it:

DataStoreConsistency stanceSource
Tweets (2012)T-Bird: Gizzard over MySQLeventual, idempotent + commutative writesTPS post, Gizzard post
Tweets, DMs, accounts (2017)Manhattaneventual by default, CAS opt-inManhattan, 2017 posts
Social graphFlockDB on Gizzard/MySQLidempotent, commutative writesFlockDB post
Photos, video, large filesBlobstoreread-your-write in the receiving DC, async to othersBlobstore post
AnalyticsHadoop, over 500 PB in 2017batch2017 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:

CacheEngineUsed for (Twitter's words)
Twemcachememcached 1.4.4 forkusers, tweets, rendered tweets
Nighthawksharded Redisgeneral caching ("users, timelines, tweets and more")
Haplocustomised Redis, HybridListprimary cache for tweet timelines
Pelikannew framework, Twemcache/Redis compatibleunified backend

Fix / how to use it: patterns in Caching, Redis lists and pipelining in Redis.

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-rank

Real 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:

GenerationIndexThroughput (source)
2008MySQL B-tree reverse index20 TPS, 200 QPS
Oct 2010Earlybird1,000 TPS, 12,000 QPS
2011Earlybird + Blender2,200 TPS, 18,000 QPS
2014real-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 data

What provides it:

AspectEventBus (DistributedLog)Kafka (Twitter's evaluation)
Layersserving and storage separate (extra hop)one process serves and stores
Durabilityack after fsyncack after replication, OS flushes later
Replicationquorum writes in parallelleader then followers
Costmore machines68–75% fewer resources
Communityabout eight engineershundreds 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 agent

What 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 toolJobToday's common equivalent (inference)
FinagleRPC client/server with resiliencegRPC + Envoy/Istio policies
FinatraHTTP/Thrift service frameworkframework on top of gRPC/HTTP
Zipkindistributed tracingOpenTelemetry + Jaeger/Zipkin
Aurora on Mesosservice schedulerKubernetes Deployments
Deciderruntime feature switchesfeature-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 outage

What 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).

Candidate sourcesEarlybird search index(in-network, ~50%)UTEG / GraphJetSimClusters, TwHINembeddingsFollow Recs Service~1500 candidatesLight rankerlogisticregression(Earlybird)Heavy rankerparallel MaskNetP(fav), P(reply)...weighted sumFilters andheuristicsvisibility, authordiversity, balance,fatigueHome Mixermix ads,who-to-follow,prompts~5 billion runs per day, under 1.5 s average, ~220 s CPU per run (X/Twitter blog, 31 March 2023)Sources: blog post and github.com/twitter/the-algorithm READMEs
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 average

Real 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:

StageComponent (repo)Model / rule
In-network candidatessearch-index (Earlybird)light ranker, logistic regression
Out-of-network candidatesUTEG / GraphJet, tweet-mixergraph traversal (~15% of Home, 2023 post)
Embedding candidatesSimClusters, TwHIN via representation-managernearest neighbours in embedding space
Rankingheavy-rankerparallel MaskNet, ~48M parameters (2023 post)
Filtersvisibility-filters, Home Mixer heuristicsrules
MixingHome Mixerads, 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 ​

200820102011201220132014201520182023Rails monolith eraSummize search on MySQLtemporally sharded MySQL2010 World Cup outages(fail whale years)2010 data layerGizzard (Apr), FlockDB (May)Snowflake (Jun)Earlybird live (Oct)Finagle post (Aug 2011)2012 servicesZipkin (Jun), Twemcache (Jul)Blobstore (Dec)Timelines at Scale talk143,199 TPS peak (Aug 2013)2014-2018 platformManhattan (Apr 2014)full index (Nov 2014)Aurora/Mesos, Heron (2015)Kafka over EventBus (2018)Trend: monolith to JVM servicesMySQL to sharded MySQL to ManhattanStorm to Heron; EventBus to Kafkabuild in-house, later adopt the community tool2023 ranked For You timelinethe-algorithm open sourced (31 Mar 2023)Fanout Service (12 years old) no longer usedin-network candidates from Earlybird search index
Date (post)ChangeDriver stated by Twitter
2008 (search post)Summize search on Rails + MySQLacquisition
Apr 2010 (Gizzard)Sharding framework extractedseveral custom stores shared code
May 2010 (FlockDB)Graph store on Gizzard + MySQLfollower lists too large for relational tables
Jun 2010 (Snowflake)Uncoordinated 64-bit idsmoving off MySQL auto-increment
Oct 2010 (search post)Earlybird replaces MySQL searchreal-time indexing and performance
2010–2013 (TPS post)Rails monolith → JVM services, T-BirdWorld Cup outages, 200–300 req/s per Rails host
Aug 2011 (Finagle)One RPC stackinconsistent failure handling across protocols
Jun–Dec 2012Zipkin, Twemcache, Blobstore, timelines talklatency visibility, cache predictability, native photos
Apr 2014 (Manhattan)Own distributed KV databaselower latency than open-source stores, self-service
Nov 2014 (full index)Every public tweet searchablelong-standing product goal
Feb 2015 (Aurora)Services on Aurora/Mesosautomation across tens of thousands of machines
Jun 2015 (Heron)Heron replaces Stormpredictability, debugging, efficiency
2016–2017Ranked timeline with deep learningrelevance
Nov 2018 (Kafka)Kafka replaces EventBuscost and community
Mar 2023 (algorithm post)Ranking code open-sourced; Fanout Service no longer usedtransparency

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 subsystemGeneric chapterWhat to take
Redis timeline cache + FanoutFeeds: Fan-out & Fan-instore ids only; append only to existing lists
Hybrid for celebritiesFeeds, Top-K & Heavy Hittersa follower-count threshold, read-time merge
SnowflakeID Generation at Scaletime-prefixed 64-bit ids, refuse on clock skew
Gizzard / T-BirdSharding & Consistent Hashing, Consistent Hashinghash by id, forwarding table, idempotent writes
FlockDBGraph Databases, Paginationadjacency lists, cursor by position, no OFFSET
ManhattanConsistency Models, Replication Topologieseventual by default, CAS when needed
BlobstoreObject Storage & File Systemsvirtual buckets, metadata separate from data
Twemcache / Pelikan / RedisCaching, Rediscluster per use case, throttle reconnects
EarlybirdSearch Systemsin-memory real-time tier + archive tier
Heron, KafkaStream Processing, Kafkaback pressure, log-based pub/sub
Finagle, ZipkinService Communication, Observabilityone client library with timeouts and tracing
Aurora/MesosContainers & Kubernetesdeclarative scheduling
For You funnelML Systems Architecturecheap model before expensive model
Rails → servicesStrangler Fig Migrationcarve out "core nouns" first

Mechanics ​

The knobs that appear in the sources ​

KnobValueSource
Timeline entrytweet id 8 B, user id 8 B, bits 4 Bslide 9
Insert commandRPUSHX (append only if list exists)slide 10
Pipeline size4k destinationsslide 8
Snowflake time bits41 (ms, custom epoch, ~69 years)README
Snowflake machine bits10 = 5 datacenter + 5 workerREADME, IdWorker.scala
Snowflake sequence12 bits, 4096 per ms per machineREADME
Snowflake epoch1288834974657IdWorker.scala
Snowflake target10k ids/s per process, 2 ms responseREADME
Blobstore fat file~256 MB preallocated with fallocate()Blobstore post
Candidates per For You request~15002023 post
Features hydrated~6000Home Mixer README
Heavy ranker size~48M parameters, ten labels2023 post
Our assumption800 entries per cached timeline, 100,000-follower thresholdthis page (inference)

Messages and errors you will see ​

WhereTextMeaning
Snowflake IdWorker (2010)Clock moved backwards. Refusing to generate id for %d millisecondswall clock went back; ids would collide or reorder
Our Go generatorclock moved backwards: refusing to generate id for 3 millisecondssame rule, wrapped ErrClockMovedBackwards
Our Go generatordatacenter id 32 out of range 0..31only 5 bits available
Our PHP generatordatacenter and worker must be in 0..31same
Redis RPUSHX on a missing keyinteger reply 0 (Redis docs: "only if key already exists")nothing written: user not cached (by design)
Laravel queuejob marked failed after the #[Tries(5)] attemptsfan-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:

sql
-- 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;
sql
-- 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 ​

go
// 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 ​

go
// 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 ​

go
// 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 ​

go
// 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.Mutex around 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/v9 with Pipelined and RPushX/LTrim; the in-memory Cache keeps 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
<?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
<?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
<?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
<?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 (RPUSHX is not idempotent); the read path de-duplicates with array_unique, which is cheaper than making the write idempotent.
  • PHP-FPM workers are separate processes: the SnowflakeId instance 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 ​

SolutionHowAdvantageCost
Hybrid fan-out (Twitter 2012)skip push above a follower threshold, merge at readwrite cost boundedread merges extra lists
Rate-limited pushpush in the background at a fixed rateone read pathfollowers see it late
Push to active followers onlyRPUSHX on cached lists onlymemory only for active usersrebuild 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 ​

SituationRecommendationExtra techniqueReason
Small product, < 1M users, few follows eachfan-out on read with a good indexcache the merged page brieflysimplest, no write amplification
Read-heavy feed, follower counts bounded (e.g. team apps)fan-out on writeids only, capped listsreads dominate
Follower counts heavy-tailed (public social network)hybridthreshold per author, read-time mergebounds the worst write
Relevance more important than recencycandidate sourcing + two-stage rankinglight ranker before heavy rankerCPU budget
Need global ids on many shardsSnowflake-style 64-bitcentral worker-id assignmentsortable, compact
Store must stay up during partitionseventual consistency, CAS opt-inread-repair, anti-entropyavailability first
Small team, mature open-source existsadopt (Kafka over EventBus)contribute upstreamcost 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 hydration

Every 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 ​

LoadDesign
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/snowflake

2. 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.

go
// 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.4

Read 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
OK

4. 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 ​

BeliefReality (source)
Twitter copies full tweets into each timelineentries are ids plus flag bits, 20 bytes (slide 9)
Every user has a timeline in memoryRPUSHX appends only to existing lists (slide 10)
Fan-out on write is instant3.5 s p50 to deliver to 1M followers (slide 35)
Celebrities are fanned out like everyone elsemerged at read time (slides 18–28)
Snowflake ids are strictly orderedk-sorted, k below 1 second (Snowflake post)
FlockDB is a graph traversal engineoptimised for adjacency lists and set arithmetic (FlockDB post)
Manhattan is strongly consistenteventually consistent core, strong consistency opt-in (Manhattan post)
Twitter search was always LuceneMySQL reverse indexes until October 2010 (search post)
Kafka was new to Twitter in 2018Kafka 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 serversfixed by re-architecture: JVM services, sharding, isolation (TPS post)

Cheat sheet ​

TopicRemember
Core trade-offpush: O(n) write, O(1) read; pull: O(1) write, O(n) read (slide 17)
Timeline cacheRedis lists of ids, RPUSHX, pipelined 4k, replicated
Hybridhigh-follower authors merged at read
2012 load~5K tweets/s, >300K timeline QPS, 30B deliveries/day
2013 peak143,199 TPS, ~25× average
Snowflake41 time + 5 dc + 5 worker + 12 seq; epoch 1288834974657
Clockrefuse when the clock moves backwards
Storage linetemporal MySQL → Gizzard/T-Bird → Manhattan
GraphFlockDB: idempotent, commutative writes, cursor paging
MediaBlobstore: virtual buckets, fat files, one seek
CacheTwemcache, Nighthawk, Haplo, Pelikan
SearchEarlybird (Lucene, real-time) + Blender; archive index 2014
StreamsHeron (Storm API), Kafka over EventBus (cost, community)
RPCFinagle + Zipkin; Aurora on Mesos
For You~1500 candidates → light → heavy → filters → mix, < 1.5 s

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Home timelinetweets from accounts a user follows; precomputed per reader
User timelineone author's own tweets
Fan-out on writecopy a new item into each follower's feed at write time
Fan-out on readbuild the feed at read time from followed authors
Hybrid fan-outpush 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 cacheRedis lists holding timeline entries per recipient
RPUSHXRedis command that appends only to an existing list
HaploTwitter's customised Redis (HybridList) timeline cache
NighthawkTwitter's sharded Redis cache clusters
TwemcacheTwitter's memcached 1.4.4 fork with random eviction
PelikanTwitter's unified cache framework
Snowflake id64-bit time + machine + sequence id
k-ordered / k-sortedsorted within a bound k, not strictly
GizzardTwitter's sharding middleware with a forwarding table
T-Birdtweet store built with Gizzard over MySQL
FlockDBTwitter's adjacency-list graph store on Gizzard/MySQL
ManhattanTwitter's multi-tenant, eventually consistent KV database
BlobstoreTwitter's photo and large-object store
EarlybirdTwitter's real-time Lucene-based search index
Blendersearch front-end that fans out to Earlybirds and merges
Inverted indexterm → list of documents containing it
HeronTwitter's Storm-compatible stream processing engine
EventBusTwitter's pub/sub on DistributedLog, replaced by Kafka
FinagleTwitter's protocol-agnostic async RPC library for the JVM
Finatraframework for services on TwitterServer and Finagle
Zipkindistributed tracing system from Twitter, after Dapper
Mesos / Auroracluster manager / service scheduler used by Twitter
Kubernetescontainer orchestrator; reported later target platform (unverified here)
DeciderTwitter's runtime feature switch system
Fail whaleTwitter's error page shown during outages
Candidate sourcingfirst funnel stage that gathers possible tweets
Light rankercheap model that pre-scores many candidates
Heavy rankerneural network scoring the survivors
Home Mixerservice that builds and mixes the home timelines
SimClusterscommunity embeddings (145k communities)
TwHINknowledge-graph embeddings over Twitter's heterogeneous network
Ranking signalsfeatures and predicted engagements used for scoring
Capacityheadroom to absorb peaks such as 25× average
Inferencea 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):

Talks, papers and repositories by Twitter / X:

Framework documentation used for the code:

Built by Morteza Negahi