Sub topic 4
Pushing posts into follower timelines at write time
Fan-out on write, also called the push model, moves the work of building a feed from the moment a user reads to the moment an author posts. This chapter explains how the push path works, what it costs, and where it fails. It assumes you have read the chapters on requirements, the data model, and fan-out on read. You should also be comfortable with key-value stores, message queues, and short Python and SQL snippets.
The core idea
In a pull design, opening the app triggers a query: find everyone the user follows, fetch their recent posts, and merge them. That work happens on every read, and reads outnumber writes by a large margin.
In a push design, the system keeps one precomputed timeline per user. When an author publishes a post, the system looks up the author's followers and inserts a reference to the new post into each follower's timeline. A read then becomes one lookup: fetch the first page of the user's own timeline.
The trade is simple. You do extra work on the write path to make the read path cheap.
What a timeline stores
A timeline should not contain post bodies. Each entry is a small reference, typically a timestamp and a post ID. Three reasons:
- Storage. A 2 KB post copied to 500 followers costs 1 MB. A 16-byte reference costs 8 KB.
- Edits and deletes. If a post changes, you update one record in the post store instead of hunting down every copy.
- Bounded size. Fixed-size entries make it easy to cap each timeline at a known length.
At read time the service takes the page of references and "hydrates" them. It fetches the post bodies from the post store with one batched call, then attaches author names and counts.
The write path
Publishing a post does two things in order. It saves the post durably, then it triggers fan-out. The fan-out should run asynchronously, so the author's request does not wait for thousands of timeline writes.
Saving the post first matters. If the job were enqueued before the post exists, a worker could push a reference to a post that readers cannot yet fetch.
A minimal implementation
The first version keeps everything in memory. It stores (timestamp, post_id) pairs, newest first, and trims each timeline to a fixed length.
from collections import defaultdict
FEED_LIMIT = 800
followers = defaultdict(set) # author_id -> set of follower ids
feeds = defaultdict(list) # user_id -> [(timestamp, post_id)], newest first
def publish(author_id, post_id, timestamp):
"""Fan-out on write: copy the post reference into each follower's feed."""
for follower_id in followers[author_id]:
feed = feeds[follower_id]
feed.append((timestamp, post_id))
feed.sort(reverse=True)
del feed[FEED_LIMIT:] # keep the timeline bounded
followers["alice"].update({"bob", "carol"})
publish("alice", "p1", 100)
print(feeds["bob"]) # [(100, 'p1')]This version works, but it has three problems you would hit in production:
- Sorting the whole list on every insert costs O(n log n) per follower. New posts are almost always the newest, so a position-aware insert is cheaper.
- If the same job runs twice, the post appears twice in every timeline.
- It runs the whole fan-out as one loop. A single author with millions of followers would hold one worker for a very long time.
Making inserts idempotent
Queues usually deliver at least once. A worker can crash after writing half the timelines, and the queue then redelivers the job. The fan-out must therefore be idempotent: running it twice has the same effect as running it once.
The version below keeps each timeline sorted and rejects exact duplicates. It stores entries oldest first, so trimming removes the front.
import bisect
from collections import defaultdict
FEED_LIMIT = 3 # tiny on purpose, so the demo shows trimming
followers = defaultdict(set)
feeds = defaultdict(list) # user_id -> [(timestamp, post_id)], oldest first
def add_to_feed(user_id, entry, limit=FEED_LIMIT):
"""Insert one entry in sorted position. Returns False for a duplicate."""
feed = feeds[user_id]
i = bisect.bisect_left(feed, entry)
if i < len(feed) and feed[i] == entry:
return False
feed.insert(i, entry)
if len(feed) > limit:
del feed[0] # drop the oldest entry
return True
def fan_out_batch(post_id, timestamp, follower_ids):
for user_id in follower_ids:
add_to_feed(user_id, (timestamp, post_id))
def read_timeline(user_id, limit=20):
return list(reversed(feeds[user_id]))[:limit]
followers["alice"] = {"bob", "carol"}
for ts, pid in [(1, "p1"), (2, "p2"), (3, "p3"), (4, "p4")]:
fan_out_batch(pid, ts, sorted(followers["alice"]))
fan_out_batch("p4", 4, ["bob"]) # redelivered job: no duplicate
print(read_timeline("bob")) # [(4, 'p4'), (3, 'p3'), (2, 'p2')]In a real cache the same property comes from the data structure. A Redis sorted set, for example, uses the post ID as the member and the timestamp as the score. Adding the same member twice only updates its score, so a redelivered job changes nothing.
Splitting the work into batches
A job for one post should not loop over every follower inside one worker. Instead:
- The first worker reads the author's follower IDs in pages of, say, 1,000, using keyset pagination on the follow table.
- For each page, it enqueues a child job:
(post_id, timestamp, [follower ids]). - Many workers process the child jobs in parallel. Each one writes its batch into the cache.
This gives you three things. Work spreads across workers. A failure retries one batch, not the entire fan-out. Large authors cannot block small ones if you give child jobs their own queue or priority.
Estimating the cost
The push model multiplies each post into many writes. This is called write amplification. Here is a worked estimate.
| Quantity | Value | Result |
|---|---|---|
| New posts per day | 20 million | 20M |
| Average followers per author | 200 | 200 |
| Timeline writes per day | 20M × 200 | 4 billion |
| Average timeline writes per second | 4B ÷ 86,400 | about 46,000 |
| Feed reads per day (100M users, 10 loads each) | 1 billion | about 11,600 per second |
| Timeline storage (800 entries × 16 bytes × 100M users) | 12.8 KB per user | about 1.28 TB |
Two points stand out. First, the timeline write rate is about four times the read rate, so push moves load onto the write side. Each read costs one cache lookup, while each post costs hundreds of writes. Second, storage is bounded by the cap, not by how long users have been active. Doubling the cap doubles the storage.
The averages hide the peaks. Plan for a peak of two to three times the average, and for skew: a small share of authors produces most of the fan-out volume.
Strengths and weaknesses
| Aspect | Fan-out on write |
|---|---|
| Read latency | Low and predictable: one lookup plus hydration |
| Read cost | Very low per request |
| Write cost | High: one write per follower per post |
| Storage | Extra copy of a reference per follower, bounded by the cap |
| Freshness | Delayed by queue lag and worker speed |
| Worst case | An account with millions of followers |
| Wasted work | Writes to users who never open the app |
The last row deserves attention. Most registered users are not active on a given day. Pushing into every follower's timeline spends write capacity on timelines nobody reads.
Edge cases and failure modes
Accounts with huge follower counts
One post from an account with 30 million followers creates 30 million timeline writes. At 50,000 writes per second, spread perfectly, that takes 10 minutes. Followers see the post at very different times, and the burst delays everyone else's jobs in the same queue. Pure push does not handle this well. The next chapter covers the hybrid approach: skip push for these accounts and merge their posts at read time.
Inactive users
You can skip fan-out for users who have not opened the app in some window, such as 30 days. When such a user returns, rebuild the timeline with a pull query and then resume pushing. This cuts write volume noticeably, at the cost of one slow first load.
Cache misses and cold starts
A timeline can disappear from the cache through eviction, a node failure, or a new user joining. The read path needs a fallback: if the timeline is missing, build it with fan-out on read, write the result back, and serve it. Without this fallback, a cache restart produces empty feeds.
Partial fan-out and ordering
If a worker fails midway, some followers have the post and others do not. Idempotent retries fix this eventually, but for a while followers differ. Also, jobs complete out of order, so a later post can land in a timeline before an earlier one. Sorting by timestamp on insert, as the second implementation does, keeps the timeline order correct regardless of arrival order.
Follows that change during fan-out
A user who follows the author after the job read the follower list will miss that post. Handle this with a backfill: on a new follow, copy the author's recent posts (say the last 20) into the follower's timeline.
Deletes and edits
The timeline holds only references, so an edit needs no timeline update. A delete does need handling. Readers filter out posts that no longer exist during hydration, and a background job removes stale references. Later chapters cover deletes, unfollows, and blocks in more detail.
Common mistakes
- Fanning out inside the request. The author waits for thousands of writes, and a slow cache makes posting slow. Use a queue.
- Copying post bodies into timelines. Storage grows quickly and edits become hard.
- Assuming exactly-once delivery. Queues redeliver. Without idempotent inserts you get duplicate posts in feeds.
- Leaving timelines unbounded. Memory use grows with every post. Always trim to a fixed length.
- Trimming by position instead of by time. If out-of-order inserts add an old entry at the end, trimming the "last" items can remove the wrong ones. Keep entries sorted and trim the oldest.
- Treating the cache as the source of truth. Timelines are derived data. Keep the ability to rebuild them from posts and follow edges.
Where this fits
Fan-out on write gives fast, cheap reads and moves the cost to publishing. It works well when most authors have modest follower counts and reads dominate. It breaks down for accounts with very large audiences, which is why the next chapter combines it with fan-out on read.
Exercise
A service has 5 million new posts per day and an average of 150 followers per author. Estimate the average timeline writes per second, and the rate at a 3x peak. Then state how much the load drops if fan-out is skipped for the 40% of followers who are inactive.
Show answer
Writes per day: 5,000,000 × 150 = 750 million. Average per second: 750,000,000 ÷ 86,400 ≈ 8,700. At a 3x peak: about 26,000 per second. Skipping 40% of followers leaves 60% of the work: about 5,200 per second on average and about 15,600 at peak.
Exercise
A fan-out worker crashes after writing a post reference to 400 of 1,000 follower timelines, and the queue redelivers the job. Name the property the insert must have so followers do not see duplicates, and describe one way to get it.
Show answer
The insert must be idempotent. One way is to keep each timeline sorted and skip an insert if an identical (timestamp, post_id) entry already exists. In a Redis sorted set, use the post ID as the member, so adding it again only updates its score.
Exercise
Why do timelines store (timestamp, post_id) references instead of full post bodies? Give two reasons.
Show answer
References are small, so copying them to many followers costs little storage and the fixed entry size makes it easy to cap each timeline. They also keep one authoritative copy of each post, so edits and deletes happen in the post store, and readers pick up the change when posts are hydrated.