Sub topic 3
Building the feed at read time
This chapter assumes you know how an HTTP API talks to a database, can read short Python and SQL snippets, and have seen the data model from the previous chapter: users, posts, and follow edges.
The idea
Fan-out on read is also called the pull model. The system stores each post once, under its author. When a user opens the app, the feed service builds the timeline on the spot. It looks up whom the user follows, fetches recent posts from each of those authors, merges them by time, and returns the newest page.
Nothing is precomputed. A write is cheap, and a read does all the work.
The query
The simplest version is one SQL query over the data model. It uses the keyset form from the pagination chapter, so each page starts after the last item the client saw.
SELECT post_id, author_id, created_at
FROM posts
WHERE author_id IN (:followed_author_ids)
AND (created_at, post_id) < (:cursor_created_at, :cursor_post_id)
ORDER BY created_at DESC, post_id DESC
LIMIT 20;This works well when the user follows a few dozen accounts and posts has an index on (author_id, created_at, post_id). The database can then read the newest rows of each author directly.
Merging in application code
When posts live in a key-value store or on several shards, you fetch one list per author and merge them yourself. Each list is already sorted newest first, so a k-way merge needs no full sort. Python's heapq.merge does this lazily, and islice stops after the page is full.
import heapq
from itertools import islice
following = {"ana": ["bo", "cy"]}
posts_by_author = {
"bo": [(105, "b5"), (101, "b1")],
"cy": [(104, "c4"), (100, "c0")],
"di": [(103, "d3")], # ana does not follow di
}
def read_feed(user_id, limit=20):
"""Fan-out on read: merge per-author lists at request time."""
streams = [posts_by_author.get(a, []) for a in following.get(user_id, [])]
merged = heapq.merge(*streams, reverse=True)
return list(islice(merged, limit))
print(read_feed("ana", limit=3)) # [(105, 'b5'), (104, 'c4'), (101, 'b1')]The merge does about limit × log(k) comparisons for k followed authors. The expensive part is fetching the k lists, not merging them.
Cost model
Let F be the number of accounts a user follows. Each feed read costs one follow-graph lookup plus up to F post lookups. Reads are the dominant traffic in a feed, so this cost is paid on every refresh.
| Property | Fan-out on read |
|---|---|
| Write cost | One insert per post |
| Read cost | About `F` lookups plus a merge |
| Read latency | Grows with `F` and with the slowest lookup |
| Extra storage | None beyond posts and follow edges |
| Freshness | New posts appear immediately |
| Celebrity posts | Cheap to write; no write amplification |
Read latency is set by the slowest of the parallel lookups. With 200 lookups at a 1% chance of being slow each, most requests hit at least one slow call. This is the tail-latency problem.
Where it breaks
Capacity estimates from the first chapter show the pressure. Suppose 10 million users open the feed 10 times a day, and each follows 300 accounts. That is 100 million reads a day, or about 1,200 per second on average and several times that at peak. At 300 lookups each, the post store faces hundreds of thousands of lookups per second, most of them returning posts the user has already seen.
Common mistakes when building this version:
- Fetching unbounded history. Asking each author for all posts, not the newest
limit, makes cost grow with account age. Cap every per-author fetch. - Sequential lookups. Calling authors one by one adds up the latencies. Issue them in parallel with a timeout, and decide whether to return a partial feed when one call is late.
- Offset pagination.
OFFSET 40skips rows by position, so a new post shifts every row and the next page repeats an item. Use the keyset cursor. - Merging without a tie-breaker. Two posts with the same timestamp can swap order between requests. Always sort on
(created_at, post_id). - Ignoring inactive authors. Querying hundreds of accounts that have not posted in months wastes lookups. Track a last-post time per author and skip stale ones.
When to choose it
Pull works when users follow few accounts, reads are rare relative to writes, or freshness matters more than speed. It also suits accounts with huge follower counts, because one post costs one write instead of millions. That last property is what the hybrid design reuses later.
Exercise
A user follows 500 accounts, and your feed service fetches each account's recent posts in parallel, then merges them. Name two ways the request latency can get worse as the user follows more accounts, and one change that limits each.
Show answer
First, more parallel lookups raise the chance that at least one is slow, so the request waits on the slowest call (tail latency). Limit this with per-call timeouts and by returning a partial feed. Second, more lists mean more data to transfer and merge. Limit this by capping each per-author fetch to the newest limit posts and skipping authors with no recent posts.