Sub topic 3
Building the feed at read time
This chapter covers the pull model, also called fan-out on read. It assumes you know basic HTTP APIs, relational tables and key-value stores, and can read short Python and SQL snippets. It also assumes you have seen the data model from the previous chapter: users, posts, and follow edges.
The idea
In a pull model, nothing is precomputed. When a user opens the app, the server builds the feed on the spot:
- Look up the list of accounts the user follows.
- Fetch the most recent posts from each of those accounts.
- Merge the results by time, newest first.
- Return the first page.
The write path is trivial. Publishing a post is one insert into the posts store. No follower is touched, so the cost of a write does not depend on how many followers the author has. The read path carries all the work.
Why the read cost grows with the follow count
Let F be the number of accounts a user follows. A naive read performs F lookups, one per author, then merges F short lists. The cost per read is roughly proportional to F.
Here is a rough estimate. Suppose 10,000 feed reads per second and an average of 200 followed accounts per user. That is 2,000,000 author lookups per second against the posts store. Each lookup is an indexed range read, so it is cheap on its own. The total is still large, and it is multiplied again by every refresh and every scroll to the next page.
Compare this with the write side. If users publish 500 posts per second, that is 500 inserts per second. The system is read-heavy by a wide margin, and the pull model puts the expensive operation on the more frequent request. That mismatch is the main weakness of the approach.
| Property | Pull model |
|---|---|
| Write cost | One insert per post |
| Read cost | Proportional to the number of followed accounts |
| Extra storage | None beyond the posts themselves |
| Freshness | A new post appears on the next read |
| Celebrity authors | No special cost at write time |
| Heavy readers | Expensive, especially users who follow thousands of accounts |
A reference implementation
The in-memory version below shows the algorithm without any database. Each author has a list of (timestamp, post_id) pairs stored oldest first, because appending to the end of a Python list is cheap. At read time, each list is reversed so that it is newest first, and heapq.merge combines the streams lazily.
import heapq
from collections import defaultdict
from itertools import islice
following = defaultdict(set) # user_id -> set of followed author ids
posts_by_author = defaultdict(list) # author_id -> [(timestamp, post_id)], oldest first
def publish(author_id, post_id, timestamp):
"""Write path: one append, independent of follower count."""
posts_by_author[author_id].append((timestamp, post_id))
def read_feed(user_id, limit=20):
"""Read path: merge the newest posts of every followed author."""
streams = []
for author_id in following[user_id]:
recent = posts_by_author[author_id][-limit:] # at most `limit` per author
streams.append(reversed(recent)) # newest first
merged = heapq.merge(*streams, reverse=True)
return list(islice(merged, limit))
following[1] = {2, 3}
publish(2, "a", 100)
publish(3, "b", 105)
publish(2, "c", 110)
print(read_feed(1, limit=2)) # [(110, 'c'), (105, 'b')]Two details keep this efficient.
First, each author contributes at most limit posts. The newest limit posts of the whole feed cannot include more than limit posts from any single author, so fetching more would be wasted work.
Second, heapq.merge is lazy. It pulls items from the input streams only as islice asks for them. With F streams, producing a page of limit items costs about F + limit * log F comparisons, not a full sort of every post.
The merge requires every input to be sorted in the same direction as the output. If one stream is out of order, the result is silently wrong, with no error. Timestamps from different servers can be slightly out of order, which is one reason to break ties and order by a post ID that is generated centrally.
The same read in SQL
In a relational store, the naive way to write this query uses an IN list:
SELECT post_id, author_id, created_at
FROM posts
WHERE author_id IN (:followed_author_ids)
ORDER BY created_at DESC, post_id DESC
LIMIT 20;This is correct, and it is acceptable for small follow lists. With hundreds of followed authors, the planner may gather every post from all of them and then sort. For a prolific account, that means scanning thousands of rows to return 20.
On PostgreSQL, a LATERAL join expresses the "top 20 per author, then merge" plan directly:
CREATE INDEX IF NOT EXISTS posts_author_recent
ON posts (author_id, created_at DESC, post_id DESC);
SELECT p.post_id, p.author_id, p.created_at
FROM unnest(:followed_author_ids::bigint[]) AS f(author_id)
CROSS JOIN LATERAL (
SELECT post_id, author_id, created_at
FROM posts
WHERE author_id = f.author_id
ORDER BY created_at DESC, post_id DESC
LIMIT 20
) AS p
ORDER BY p.created_at DESC, p.post_id DESC
LIMIT 20;The composite index lets each inner query read exactly 20 index entries for its author and stop. The outer query sorts at most 20 * F rows. This mirrors the Python version: a bounded fetch per author followed by a merge.
Where the time goes
A pull-model request has four cost centers. Knowing which one dominates tells you what to fix.
| Stage | Typical cost driver | Common fix |
|---|---|---|
| Follow-list lookup | Users who follow thousands of accounts | Cache the list, or store it in a key-value store keyed by user |
| Per-author fetch | Number of authors times round trips | Batch requests by shard, run them in parallel |
| Merge | Number of streams | Per-author cap, lazy merge |
| Post hydration | Fetching text, media, counts for the chosen IDs | Fetch IDs first, hydrate only the final page |
The last row is easy to miss. Merge on lightweight (timestamp, post_id) references and load the full post bodies only for the 20 items you return. Loading bodies for every candidate multiplies the data moved by F.
Techniques that make pull workable
Pull is not only a baseline to be dismissed. Several techniques make it viable at moderate scale.
Parallel, batched fan-out
Posts are sharded by author (a later chapter covers sharding). A feed service should not issue 200 sequential requests. It groups the followed authors by shard, sends one batched request per shard in parallel, and merges the replies. With 50 shards, a request becomes at most 50 parallel calls instead of 200 serial ones. Latency then follows the slowest shard, so tail latency becomes the concern.
Caching recent posts per author
Popular authors are read by many followers. A small cache keyed by author_id, holding that author's last 20 to 50 post references, absorbs most of the fetch load. Because it is keyed by author and not by reader, the cache is shared across all followers. A new post invalidates or updates a single cache entry, not one per follower. This is the main structural advantage of pull over push for the write side.
Capping the follow set
Some products read from only a bounded subset of follows, such as the 500 most recently active authors. This bounds F and therefore the read cost. The trade-off is that an infrequent poster may be missing from the feed, which changes what the product promises.
Time windows
A feed rarely needs posts older than a few days to fill the first pages. Restricting the per-author fetch to a window, for example the last 7 days, lets the store skip old data. Deeper pages can widen the window.
Pagination in a pull model
A feed needs paging because users scroll. Offset paging (OFFSET 40) breaks here. Between page one and page two, new posts arrive, every item shifts down, and the user sees duplicates. Use a cursor made of the last item's (created_at, post_id) instead. Each per-author query then adds the condition (created_at, post_id) < (:cursor_created_at, :cursor_post_id), so every author's stream resumes from the same point in time. A later chapter develops cursors fully. The point here is that the pull model supports them naturally, because the cursor is a position in a global order and no per-user state is stored.
Failure modes and edge cases
- Slow or failed shard. One shard that times out means a missing slice of the feed. Choose a policy deliberately: return a partial feed marked as incomplete, retry once, or fail the request. Most products return the partial result, because a feed missing a few authors beats an error page.
- Hot authors. A very popular account is read by every follower on every refresh, so its shard gets hammered. The per-author cache above is the standard mitigation.
- Heavy followers. A user who follows 10,000 accounts costs 50 times more than one who follows 200. Apply the follow-set cap or a per-request budget so that one user cannot degrade the shared store.
- Clock skew. If post timestamps come from application servers with drifting clocks, the merge order may look wrong. Use a server-generated, roughly time-ordered ID such as a snowflake-style ID, and use it as the tie-breaker.
- Deleted or blocked content. Because the feed is computed fresh, a deleted post vanishes on the next read, and a block can be applied by filtering authors before the fetch. This is a real advantage over precomputed timelines, which must be cleaned up after the fact.
- Inactive users. Pull costs nothing for users who never open the app. This matters for products where most accounts are dormant.
When pull is the right choice
Choose pull when one or more of these hold:
- The product is small or mid-sized, and the simplicity is worth more than the extra latency.
- Writes need to be cheap and predictable, or authors have very large audiences.
- Freshness and instant deletes matter more than read speed.
- Most users read rarely, so precomputing timelines would waste storage on feeds nobody opens.
Avoid pure pull when read latency targets are tight, follow counts are high, or reads outnumber writes by orders of magnitude. The next chapter takes the opposite approach, doing the work at write time, and the chapter after it combines the two.
Exercise
A user follows 400 accounts. Your feed service fetches the newest 20 posts from each followed author and returns a page of 20. A colleague proposes lowering the per-author fetch to 5 to save work. Explain why this changes correctness, and state when fetching only 20 per author is exactly correct.
Show answer
Fetching 20 per author is exactly correct because the newest 20 posts of the merged feed can include at most 20 posts from any single author. No author can contribute more, so nothing needed is left out. Lowering the fetch to 5 is only safe if no author could contribute more than 5 of the top 20. An author who posted 8 times in the last hour would have 3 of their posts wrongly cut off, and older posts from other authors would take their place. The feed would then be missing recent posts. The per-author fetch must be at least the page size, unless the product accepts an approximate feed.
Exercise
Why is heapq.merge preferable to concatenating all per-author lists and calling sorted, and what input requirement must you guarantee when using it?
Show answer
heapq.merge is lazy. It takes items from the input streams only as the consumer asks for them, so producing a page of 20 items costs about F + 20 * log F comparisons for F streams. Concatenating and sorting costs about N log N for N total candidate posts, even though only 20 are returned. The requirement is that every input stream is already sorted in the same direction as the requested output (newest first here, with reverse=True). The function does not check this, and an unsorted input produces silently wrong ordering.
Exercise
A read in the pull model takes 900 ms at the 99th percentile. Profiling shows the follow-list lookup and the merge are fast, and the per-author fetch dominates. Name two changes that reduce this cost and describe what each trades away.
Show answer
First, batch and parallelize the fetch by shard, so a request sends one parallel call per shard instead of one serial call per author. This lowers latency but makes the request depend on the slowest shard, so tail latency and partial-failure handling become the concern. Second, add a shared cache of each author's recent post references. This removes most database reads for popular authors, at the price of cache invalidation on new posts and deletes, and brief staleness if the cache is not updated promptly. Capping the number of followed authors read per request is a third option. It bounds cost but may omit infrequent posters.