FOUNDING PRICING · 40% OFFfor the first 1,000 members · from ₹95/month
ArchitectureTwitter11 min read

How Twitter Built the Home Timeline: Fan-out on Write

How Twitter served home timelines around 2013: fan-out on write into Redis, why accounts with millions of followers hurt, and the hybrid of push and pull.

ShareXLinkedInWhatsApp
The stone art deco facade of 1355 Market Street in San Francisco seen from across the street, with pedestrians, a delivery truck and a vertical sign on the right edge of the building, which housed Twitter's headquarters when photographed in March 2015.
The stone art deco facade of 1355 Market Street in San Francisco seen from across the street, with pedestrians, a delivery truck and a vertical sign on the right edge of the building, which housed Twitter's headquarters when photographed in March 2015. Photo: Runner1928, CC BY-SA 4.0, via Wikimedia Commons.

Around 2012 and 2013, Twitter's engineers described in public how the home timeline was served: not by querying for tweets when you opened the app, but by copying each new tweet's ID into a stored list for every follower at the moment it was posted. It is the textbook example of fan-out on write, and it is the design most interviewers have in mind when they ask you to build a news feed.

This post describes that system as it was published at the time, mainly in Raffi Krikorian's QCon talk "Timelines at Scale" and Twitter's own engineering blog. Every figure below carries its date. None of it is a description of how the company's product works today.

A diagram of the two paths: on the write path a tweet goes through the write API and a queue to the fanout service, which asks the Flock social graph for the author's followers and inserts the tweet ID into each follower's list in the Redis timeline cache, and on the read path the Timeline Service fetches one precomputed list and Tweetypie turns the IDs into full tweets.

The problem and the scale in 2013

A home timeline is the merged, time-ordered stream of tweets from everyone you follow. The difficulty is the shape of the load, which is very uneven in two ways: people read far more often than they write, and a few accounts have vastly more followers than everyone else.

These are the numbers the sources gave. The first group comes from High Scalability's July 2013 write-up of the talk, which was recorded at QCon San Francisco 2012. The second comes from Twitter's engineering blog in August 2013.

FigureValueSource and date
Active users worldwide150 millionTalk write-up, July 2013
Timeline queries (home and search)about 300,000 per secondTalk write-up, July 2013
Tweets per day400 millionTalk write-up, July 2013
Tweets per secondabout 5,000 average, 7,000 at daily peak, over 12,000 in big eventsTalk write-up, July 2013
Timeline deliveriesabout 30 billion per dayTalk write-up, July 2013
Tweets per daymore than 500 million, about 5,700 per secondTwitter blog, August 2013
Record one-second peak143,199 tweets, on 3 August 2013 (Japan time)Twitter blog, August 2013

Divide the first group out and you get the central fact of the design. Reads arrive at roughly 300,000 per second and tweets at roughly 5,000 per second, so there are about sixty timeline queries for every tweet. And 30 billion deliveries for 400 million tweets is about 75 timeline inserts per tweet on average (that division is ours, not a figure from the talk).

Pull: assemble the timeline when someone asks

The obvious design does no work until a reader shows up. Store each tweet once, and when a user opens the home timeline, find everyone they follow, fetch recent tweets from each, merge them and sort by time. In SQL terms it looks something like this (an illustration, not Twitter's schema):

SELECT t.*
FROM tweets t
JOIN follows f ON f.followee_id = t.author_id
WHERE f.follower_id = :me
ORDER BY t.id DESC
LIMIT 50;

Writes are as cheap as they can be: one insert. Reads are expensive, and the expense grows with the number of accounts the reader follows. Worse, it is paid on the hot path, 300,000 times a second, by a user who is waiting. The talk write-up is blunt about this approach at Twitter's scale: computing timelines naively at read time had been tried and did not survive.

A side-by-side diagram: with pull, a tweet costs one write but every read does one lookup per followed account and then merges and sorts, and with push, a tweet costs one insert per follower in the background while every read is a single lookup of a stored timeline.
Pull pays at read time, push pays at write time

Push: fan out on write

The design Twitter described moves the work to the write side. When a tweet arrives, the system works out who should see it and puts it into each of their timelines straight away. Reading then needs no computation at all.

Step by step, as the 2013 write-up tells it:

  1. The tweet comes in through the write API. It is placed on a queue and the client's connection is released. The talk gave up to 145 milliseconds for this ingest step.
  2. A fanout process picks the tweet up in the background. It asks the social graph service, built on Flock, for the list of the author's followers.
  3. For each follower, it inserts the tweet's ID into that follower's home timeline, which lives in a Redis cluster. Inserts were pipelined in batches of 4,000 destinations.
  4. A tweet from someone with 20,000 followers therefore causes about 20,000 inserts.

The queue in step 1 matters. According to the write-up, Twitter's write path had been fully synchronous until about two years before the talk. Decoupling it means the person tweeting gets a fast response, and the slow, variable part happens asynchronously.

The Redis timelines are deliberately small. Each entry holds the tweet ID, the ID of the user who wrote it, and four bytes of flags that mark things like retweets and replies. The tweet text is not there. A timeline was capped at 800 entries at the time of the talk, and each one was stored on three different machines. The whole cluster used a couple of terabytes of RAM, and memory was the limit on how long timelines could be.

A large machine room seen from above, with long rows of server racks under a ceiling of strip lights.
Rows of server racks in a machine room at CERN. Illustrative of an in-memory cluster's hardware; not a Twitter facility. Photo: Florian Hirzinger - www.fh-ap.com, CC BY-SA 3.0, via Wikimedia Commons.

To save memory, only active users had a timeline in the cache. The write-up defines active as having logged in within the last 30 days. If such a user came back, or a cached timeline was lost, it was rebuilt the slow way: look up who the user follows, read those accounts' tweets from disk-backed storage, and load the result into Redis. In other words the pull design still existed, but only as the fallback for a cache miss.

A later talk by Yao Yue of Twitter's cache team, written up in September 2014, explains why Redis was used instead of memcached. A timeline is a long list that receives small appends. With a plain key-value cache, adding one ID means reading the whole list, modifying it and writing it back. Redis has list operations on the server, so an append sends only the new element. That write-up says Redis was first used at Twitter in 2010 for the timeline service, and that by 2014 timelines used about 40 terabytes of heap across more than 6,000 instances in one data centre.

The read path

Reading is now simple. The Timeline Service finds the Redis machine holding the user's list and reads it. It then turns IDs into full tweets, a step called hydration: it asks Tweetypie, the tweet service, for the tweet bodies and Gizmoduck, the user service, for author details, both of which sit in front of large memcached clusters. Some filtering also happens at this point.

The write-up gives the Timeline Service a median of 5 milliseconds and a 99th percentile of 100 milliseconds, as stated in the talk. The read is a lookup by key, so its cost does not depend on how many accounts you follow. The talk contrasted this with search, which made the opposite choice: indexing a tweet touches one machine, and a query scatters across the whole index and gathers the results.

The cost: accounts with millions of followers

Fan-out on write has one obvious weak spot. The cost of a tweet is proportional to the author's follower count, and follower counts are wildly skewed. The 2013 write-up lists Lady Gaga at 31 million followers, Katy Perry and Justin Bieber at 28 million each, and Barack Obama at 23 million.

One tweet from a 31-million-follower account meant 31 million inserts. At 4,000 per batch that is 7,750 batches (our arithmetic). Twitter's stated goal was to deliver a tweet within five seconds, and the write-up says a tweet from the largest accounts could take up to five minutes to reach every follower.

Slow delivery also causes a correctness problem, not just a delay. Followers receive the tweet at different moments. Someone who gets it early can reply, and that reply, coming from an account with few followers, fans out almost instantly. A third person who follows both may then see the reply before the tweet it answers. The write-up notes that tweets are sorted by ID on the way out, since IDs are roughly time-ordered, but that sorting cannot show a tweet that has not arrived yet.

The hybrid, and what was published later

The answer described in the talk was to stop treating every account the same way. For the small number of accounts with very large audiences, do not fan out at all. Store their tweets once, and when a follower reads their timeline, fetch the recent tweets of the large accounts they follow and merge them into the precomputed list.

A diagram in two parts: a bar comparison of 20,000 inserts for a 20K-follower account against 31,000,000 inserts for a 31M-follower account, and below it the hybrid flow in which ordinary accounts fan out into the reader's stored list, very large accounts are stored once with no fan-out, and the two are merged at read time into the home timeline.
Why very large accounts are merged at read time

This costs each read a little: one extra lookup per large account followed, and a merge. It saves an enormous amount on the write side. The write-up says Twitter expected to save tens of percent of its computing resources.

It is worth being exact about status. In the 2013 write-up this is presented as work under way, not as a finished system, and it gives no follower threshold for deciding which accounts skip the fan-out. Any specific cut-off you see quoted for Twitter is not from these sources.

Twitter's later posts confirm the broad shape lasted for some years. A January 2017 infrastructure post names Haplo as the primary cache for tweet timelines, backed by a customised Redis, written to by the Timeline Service and a Fanout Service. That is the last dated public description used here. The company has since been renamed and its product has changed, and this post makes no claim about the current system.

The computer science underneath

Fan-out on write versus fan-out on read. This is the choice at the centre of every feed design, and the lesson Design a News Feed: Fan-out, Celebrities and the Hybrid works through it with numbers. The rule Twitter's case teaches is to look at the ratio. If reads outnumber writes sixty to one, pay on the write side. If one writer has 31 million readers, that writer is an exception and needs the other strategy.

A precomputed timeline is denormalised data. The normalised truth is two tables: tweets and follows. The Redis list is a derived copy, arranged for one query. That buys read speed and costs storage, write work and the chance that the copy lags behind the truth, which is the trade described in denormalisation and its trade-offs. It also explains why the lists could live only in memory: they can always be rebuilt from the source.

Server-side data structures in a cache. The reason for Redis here was not raw speed. It was the ability to append to a list without a read-modify-write round trip. Distributed caches: how Redis and Memcached actually work covers that difference, along with replication and what happens when a cached key is missing.

Queues and asynchronous work. The author of a tweet waits only for the tweet to be accepted. Fan-out happens later, at whatever pace the workers manage. Message queues and async work explains this pattern and its price: the system is eventually consistent, and a backed-up queue shows up as late tweets.

Time-ordered IDs. Twitter's 2013 post explains that once tweets were spread over many MySQL databases, a single auto-increment counter was no longer available, so it built Snowflake to generate IDs. Because those IDs increase roughly with time, a timeline can be a list of bare IDs and still be sorted. See unique ID generation.

What an interviewer could ask from this

Why not just query for the timeline when the user opens the app? The query fans in across everyone the user follows and must sort the result, and it runs on every read. With reads far outnumbering writes, that puts the expensive operation on the most frequent path.

What exactly is stored in the precomputed timeline? Tweet IDs and a little metadata, not tweet bodies. Bodies are fetched from the tweet service at read time. This keeps the lists small and means a deletion is made in one place.

What breaks when a user with 30 million followers tweets? Thirty million inserts sit in the fanout queue. Delivery takes minutes instead of seconds, other tweets queue behind it, and replies can reach readers before the original.

How does the hybrid fix that? Large accounts are not fanned out. Their tweets are pulled and merged when a follower reads. Each read does slightly more work, and the largest writes disappear.

Why keep timelines only for active users? Memory is the limiting resource. A user who has not logged in for a month does not need a list kept warm. If they return, the list is rebuilt from the social graph and stored tweets, which is slow but rare.

Is this system strongly consistent? No. Followers see a tweet at different times, and a timeline is a cache that may lag. The design accepts that in exchange for fast reads.

Takeaways

  • Decide where to pay by looking at the read-to-write ratio. Twitter's published 2013 figures were roughly 300,000 timeline reads per second against 5,000 tweets per second, so it paid at write time.
  • A precomputed timeline is a denormalised, rebuildable cache of IDs. Keep it small, keep it in memory, and keep the source of truth elsewhere.
  • Skew breaks simple designs. One strategy for the many and another for the few very large accounts is cheaper than forcing one strategy on both.
  • Asynchronous fan-out keeps posting fast but makes delivery order and timing something you have to reason about.
  • Architecture write-ups have dates. This one describes Twitter as published between 2012 and 2017, not the system running today.

Sources

  1. InfoQ: Timelines at Scale, Raffi Krikorian, QCon San Francisco 2012 (talk page)
  2. High Scalability: The Architecture Twitter Uses to Deal with 150M Active Users, 300K QPS, a 22 MB/S Firehose, and Send Tweets in Under 5 Seconds (8 July 2013)
  3. Twitter Engineering: New Tweets per second record, and how! (16 August 2013), read via the Wayback Machine
  4. High Scalability: How Twitter Uses Redis to Scale, 105TB RAM, 39MM QPS, 10,000+ Instances (8 September 2014)
  5. Twitter Engineering: The Infrastructure Behind Twitter, Scale (19 January 2017), read via the Wayback Machine

Written by the Codevizag Academy team

An independent explainer built from the public sources listed above. Codevizag Academy is not affiliated with Twitter. Found a mistake? Write to support@codevizag.com.

More case studies

Understood it? Now prove it.

The lessons behind this case study are free, and 20 problems a month are judged on real test cases at no cost.

Start solving free