Sub topic 4
Pushing posts into follower timelines at write time
This chapter assumes you know basic HTTP APIs, relational and key-value stores, caching, message queues, and can read short Python and SQL snippets. It also assumes you have read the chapter on building the feed at read time, because fan-out on write is the answer to that approach's main weakness.
The idea
Fan-out on read computes a feed when the user opens the app. It queries every followed account, merges the results, and sorts them. Read cost grows with the number of accounts a user follows.
Fan-out on write moves that work to publish time. When an author posts, the system copies a small reference to the post into the timeline of every follower. A timeline is a precomputed list stored per user. Reading a feed then becomes one lookup on one key.
This trades write cost for read speed. A feed system usually has far more reads than writes, so the trade is often a good one.
What gets stored
Store references, not full posts. Each timeline entry is a (timestamp, post_id) pair. The post body lives once in the post store.
This has three benefits:
- Timeline entries stay small, so many fit in memory.
- Editing a post changes one record, not millions of copies.
- Deleting a post means removing one record. Readers drop entries whose post no longer exists when they hydrate the feed.
Hydration is the step where the reader takes the post_id values from a timeline and fetches the full post data, author profile, and counters.
A minimal implementation
The following code keeps each timeline bounded at 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 boundedThe del feed[FEED_LIMIT:] line keeps only the newest 800 entries. Without it, memory grows without limit for active accounts. Most users never scroll past a few hundred items, so the cap costs little.
The in-memory sort is fine for a demo. In production you would use a structure that keeps order cheaply, such as a Redis sorted set, where adding an entry and trimming by rank are both efficient operations.
Doing the work asynchronously
The author should not wait for every follower's timeline to update. A realistic flow looks like this:
- The API writes the post to the post store.
- It enqueues a fan-out job containing the author ID and post ID.
- It returns success to the author.
- Workers read the follower list in batches and write to each timeline.
Batching matters. An author with 100,000 followers produces 100,000 timeline writes. Splitting them into jobs of, say, 1,000 followers lets many workers run in parallel and lets a failed batch retry on its own.
Costs and limits
Write amplification is the number of timeline writes caused by one post. It equals the author's follower count. The cost of one post is therefore not constant.
| Aspect | Fan-out on write |
|---|---|
| Read latency | Low, one key lookup |
| Write cost | One write per follower |
| Storage | Follower count times posts retained, bounded by the feed limit |
| Freshness | Delayed by queue lag |
| Inactive users | Timelines are built for people who may never return |
A quick estimate shows the scale. Suppose 10 million posts per day, and the average author has 200 followers. That is 2 billion timeline writes per day, or about 23,000 per second on average, with higher peaks. Now take one account with 50 million followers. A single post triggers 50 million writes, which can take minutes and delay everyone else's fan-out jobs behind it.
This is the main failure mode. Accounts with very large follower counts make write cost unpredictable. The next chapter covers the hybrid approach that handles them.
There are two smaller mitigations worth knowing now. First, skip fan-out to users who have not been active recently, and rebuild their timeline with a read-time query when they return. Second, use separate queues or priority levels so one large job cannot block ordinary ones.
Summary of the trade-off
Choose fan-out on write when reads dominate, most authors have modest follower counts, and low read latency matters. Expect extra storage, a queue to operate, and slightly stale feeds while jobs drain.
Exercise
An author with 2,000 followers publishes one post. Your timelines store only (timestamp, post_id). How many timeline writes does the post cause, and what happens to the stored timeline entries if the author deletes the post?
Show answer
It causes 2,000 timeline writes, one per follower. On deletion, the post record is removed from the post store once. The timeline entries remain until they are trimmed or filtered, so the reader must skip entries whose post_id no longer resolves during hydration.
Exercise
Your queue delivers a fan-out job twice. Why can this corrupt a timeline built with the plain list code above, and how would you prevent it?
Show answer
The list code appends the entry each time, so the follower sees the same post twice. Prevent it by making the write idempotent, for example by using a sorted set keyed by postid, or by checking whether the postid is already present before inserting.