Algorithms · Huge scale
Fan-out on write
How Twitter builds your timeline before you open the app. Do the work when someone posts, so reading is instant. Unless that someone has 100 million followers.
The problem
You open Twitter and your home timeline is just there. No spinner, no waiting while the app goes hunting. But your timeline is a mix of posts from everyone you follow, and none of those people wrote their posts in the order you'll want to read them.
In the 2012 talk "Timelines at Scale", Twitter engineer Raffi Krikorian described the key fact: people read their timelines far more often than anyone writes a tweet. Whatever Twitter does, reading has to be fast.
The obvious way
When you open the app, look up everyone you follow, fetch each one's recent posts, merge them, sort them, and show the result. It's simple and always fresh. But it makes every read do the heavy work, and reads are the most common thing that happens. Follow 500 accounts and each app-open means 500 lookups, repeated for every user, all day.
The clever idea
Think of a mailroom. The slow way: each morning you walk around the building asking every colleague if they wrote anything for you. The fast way: when someone writes a note, they drop a copy in the mailbox of everyone who subscribes. In the morning your mailbox is already full. That's fan-out on write.
Twitter kept each user's home timeline in an in-memory store (Redis), holding tweet IDs, so reading it is a quick lookup. There's a catch: an account with a huge follower count would trigger an enormous number of copies for one tweet. So for those accounts Twitter used a hybrid: skip the push, and merge their tweets into your timeline at read time.
Try it yourself
How the code does it
The obvious way writes cheaply, one save per post, but each read scans everything you follow. The push version flips this: every post is copied into each follower's inbox, so a read costs just one lookup.
Run it and compare the bars. Pure push has the worst write bar, because the star posts often and each of their posts is copied to every follower. Passing the star to on_write triggers the skip, and the read merge adds back one extra lookup. The hybrid's combined work comes out lowest of the three.
Trade-offs
You pay more work and memory at write time to make reads fast, and that only pays off when reads vastly outnumber writes. If almost nobody opened the app, or posts were rare and timelines rarely viewed, copying everything everywhere would be wasted effort. The hybrid also adds complexity: reads now have two paths to merge.
Where else you'll see it
Precomputing results for the common read shows up everywhere: cached search results, news feeds, materialized views in databases, and notification inboxes.
Suppose the star posted 10x more often. Which strategy's work grows the most?
- Fan-out on read
- Pure fan-out on write
- The hybrid
Show the answer
Pure fan-out on write. In pure fan-out on write, every star post is copied to ~199 inboxes. The hybrid saves it once, and fan-out on read also stores it once.
- Change READS to 100 and compare totals
- Change .2 to .5 for star posts
- Change STAR follows to 20 each
The code
Python, with what each line means beside it. It compares the clever way with collecting every followed account’s posts when you open the app.
import randomBring in the random toolsrandom.seed(7)Fix the dice so results repeatN, POSTS, READS, STAR = 200, 500, 5000, 0Set sizes: users, posts, reads, star follows = {u: set(random.sample(range(N), 10)) - {u} for u in range(N)}Each user follows ten random othersfor u in range(1, N): follows[u].add(STAR)Everyone else also follows the starfollowers = {u: [v for v in range(N) if u in follows[v]] for u in range(N)}Flip it: list each user's followersauthors = [STAR if random.random() < .2 else random.randrange(N) for _ in range(POSTS)]Pick an author per post; star posts oftenreaders = [random.randrange(N) for _ in range(READS)]Pick who opens the app each time def on_read():Define the obvious way: build on read write = POSTSWriting costs one save per post read = sum(len(follows[r]) for r in readers)Each read scans every followed account return write, readHand back both costs def on_write(skip=-1):Define the push way, optionally skipping someone inbox = {u: [] for u in range(N)}Give every user an empty timeline write = 0Start counting write work at zero for post, a in enumerate(authors):Go through each post and its author if a == skip:If the author is the skipped star write += 1Save the post once, nothing more else:Otherwise for f in followers[a]:Visit each follower of the author inbox[f].append(post)Drop the post into their timeline write += 1Count one unit of work read = sum(1 + (skip in follows[r]) for r in readers)Each read is one lookup, plus star merge return write, readHand back both costs results = {'read': on_read(), 'write': on_write(), 'hybrid': on_write(STAR)}Run all three strategiesshow([w for w, r in results.values()], 'Write work: read-time | write-time | hybrid')Chart write work for eachshow([r for w, r in results.values()], 'Read work: read-time | write-time | hybrid')Chart read work for eachfor name, (w, r) in results.items():Loop over the three results print(name, 'total work:', w + r)Print each one's total work- the slow read line 13Every read scans all the accounts you follow. Reads happen constantly, so this cost is paid over and over.
- celebrity skip lines 20–21The star's post is stored once, not copied to 199 inboxes. Followers will fetch it later, at read time.
- the fan-out lines 23–25One post becomes one write per follower. This is the up-front work that buys instant reads.
- the merge line 26A read is one inbox lookup, plus one extra fetch if you follow the skipped star.
Read more
- infoq.com: Fan-out on write
- Ask Bento: What is Redis and why is it fast?
- Ask Bento: How do caches go stale?
- Ask Bento: How does a feed rank posts?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.