Sub topic 5
A Hybrid Approach for Accounts with Millions of Followers
This chapter assumes you know the two basic strategies from the previous chapters. Fan-out on read builds a feed by querying each followed account at request time. Fan-out on write copies each new post reference into every follower's timeline. You should also be comfortable reading short Python snippets.
Why pure push breaks down
Fan-out on write makes reads cheap, but the cost of a write grows with the author's follower count. An account with 20 million followers turns one post into 20 million timeline updates. That causes three problems:
- Write amplification. One user action becomes millions of cache writes, which can saturate queues and cache nodes.
- Delayed delivery. The last followers may see the post minutes after the first ones.
- Wasted work. Many followers are inactive. Their timelines are updated but never read.
Pure pull has the opposite problem. Every feed read queries every followed account, so reads are slow and expensive. Most accounts are small, and for them push is cheap and works well.
The core idea
A hybrid design chooses the strategy per author, not per system.
- Normal accounts use push. Their posts are copied into follower timelines when they are published.
- High-follower accounts, often called "celebrities", use pull. Their posts are stored once, in the author's own post list.
- At read time, the service takes the user's precomputed timeline and merges in recent posts from the celebrities that user follows.
The result is bounded write cost for every post and a bounded read cost. A read performs one timeline lookup plus a small number of celebrity lookups.
Choosing the threshold
The threshold is a tunable number, such as 100,000 followers. Pick it by comparing costs:
- Set it too low, and many accounts are pulled. Reads need more lookups.
- Set it too high, and large accounts still cause write spikes.
Some systems also use signals other than raw follower count. One example is pushing only to followers who were active in the last few days, and leaving inactive followers to pull. Whatever rule you use, the rule must be deterministic at read time. The reader needs to know which followed accounts are "pulled" so it knows which ones to query.
Publishing in the hybrid design
The publish path checks the author's status before fanning out. This example extends the earlier push code. It assumes the followers and feeds structures and FEED_LIMIT from the previous chapter.
from collections import defaultdict
FEED_LIMIT = 800
CELEBRITY_THRESHOLD = 100_000
followers = defaultdict(set) # author_id -> set of follower ids
feeds = defaultdict(list) # user_id -> [(timestamp, post_id)], newest first
author_posts = defaultdict(list) # author_id -> [(timestamp, post_id)], newest first
def is_celebrity(author_id):
return len(followers[author_id]) >= CELEBRITY_THRESHOLD
def publish(author_id, post_id, timestamp):
# Every post is stored in the author's own list.
author_posts[author_id].insert(0, (timestamp, post_id))
if is_celebrity(author_id):
return # pulled at read time, no fan-out
for follower_id in followers[author_id]:
feed = feeds[follower_id]
feed.append((timestamp, post_id))
feed.sort(reverse=True)
del feed[FEED_LIMIT:]The author's post list is the source of truth for pull. The code stores every post there, including posts that are also pushed.
Reading in the hybrid design
At read time, the service finds which followed accounts are celebrities, takes their recent posts, and merges them with the timeline. Each input is already sorted newest first, so a lazy k-way merge only reads as many items as the page needs.
import heapq
from itertools import islice
def read_feed(precomputed, celebrity_posts, limit=20):
"""All inputs are lists of (timestamp, post_id), newest first."""
merged = heapq.merge(precomputed, *celebrity_posts, reverse=True)
return list(islice(merged, limit))
pushed = [(105, "p5"), (101, "p1")]
celebs = [[(104, "c4"), (100, "c0")]]
print(read_feed(pushed, celebs, limit=3)) # [(105, 'p5'), (104, 'c4'), (101, 'p1')]The merge keeps the page in global timestamp order. It also pairs naturally with cursor pagination, which a later chapter covers. The cursor is the last (timestamp, post_id) returned, and each source resumes after it.
Common errors and gotchas
- Threshold crossings. An account that grows past the threshold already has its old posts pushed into timelines. New posts are pulled. This is fine, because the merge removes the need for a backfill. Deduplicate by
post_idin case a post appears in both sources. - Following too many celebrities. A user who follows thousands of pulled accounts makes reads expensive. Cap the number of lookups, or cache each celebrity's recent posts, since many readers request the same data.
- Hot keys. A celebrity's post list is read by millions of users. Cache it in memory and replicate it, or the shard holding it becomes a bottleneck.
- Dropping the author list. If you push without storing posts per author, you cannot switch an account to pull later.
Trade-offs
| Aspect | Pure push | Pure pull | Hybrid |
|---|---|---|---|
| Write cost | High for large accounts | Low | Bounded |
| Read cost | Low | High | Low to moderate |
| Complexity | Low | Low | Higher |
| Freshness for large accounts | Delayed | Immediate | Immediate |
The extra complexity is real. You now have two code paths, a threshold to tune, and a merge step to keep correct. Use hybrid when follower counts are heavily skewed, as they are on most social networks.
Exercise
A user follows 500 normal accounts and 3 celebrity accounts. Describe what happens on a feed read, and name the part of the read cost that grows if the user follows 3,000 celebrities instead.
Show answer
The service loads the user's precomputed timeline, which already holds posts from the 500 normal accounts. It then fetches recent posts from the 3 celebrity accounts and merges them with the timeline by timestamp, returning the top page. The number of celebrity lookups grows with the number of followed celebrities, so following 3,000 would make read cost and latency much higher. Mitigations are caching each celebrity's recent posts and capping the number of lookups.
Exercise
Why must every post be stored in the author's own post list, even when it is also pushed to followers?
Show answer
The author's list is the source of truth for pull. It lets an account switch from push to pull when it crosses the threshold, and it lets readers merge celebrity posts without a backfill.