Sub topic 5
A hybrid approach for accounts with millions of followers
This chapter assumes you have read the previous two chapters on fan-out on read and fan-out on write. You should also be comfortable with the data model (users, posts, follow edges) and with reading short Python snippets. Here we combine the two strategies so that one design handles both ordinary accounts and accounts with millions of followers.
Why neither strategy works alone
Fan-out on write makes reads cheap. Each follower has a precomputed timeline, and reading it is one lookup. The cost is paid at publish time, because the post reference is copied into every follower's timeline.
For most accounts this cost is small. Suppose a typical user has 300 followers. One post causes 300 small writes, which is trivial.
Now take an account with 100 million followers. One post causes 100 million timeline writes. If the write pipeline sustains 50,000 timeline inserts per second, finishing one post takes:
100,000,000 / 50,000 = 2,000 seconds, about 33 minutesThis creates three problems:
- Followers see the post at very different times. Some see it at once and others half an hour later.
- The burst competes with writes from everyone else, so ordinary users' posts are delayed too.
- Most of the work is wasted. Many of those 100 million followers are inactive and will never open their feed before the post scrolls away.
Fan-out on read has the opposite profile. Publishing is one write, but every read must query each followed author and merge the results. That makes reads slow and expensive for users who follow many accounts.
The hybrid approach uses each strategy where it is cheap:
- Push posts from ordinary accounts into follower timelines at write time.
- Skip the push for high-follower accounts. Pull their posts when a follower reads, and merge them into the precomputed timeline.
The reasoning rests on an asymmetry. A high-follower account is followed by many people, but each reader follows only a few such accounts. A reader's pull cost therefore stays small, while a push for that account would be enormous.
The overall flow
The diagram shows both paths. A post from an ordinary author goes through a fan-out worker into follower timelines. A post from a high-follower author is only stored. The reader combines both sources.
Choosing which accounts count as high-follower
The simplest rule is a follower-count threshold. An author with at least CELEB_THRESHOLD followers is pulled, and everyone else is pushed. Common starting points are in the tens of thousands to a few hundred thousand, tuned from measurements.
Follower count is only a proxy. The real cost of a push is followers multiplied by posts per unit of time. Consider two accounts:
| Account | Followers | Posts per day | Timeline writes per day |
|---|---|---|---|
| News bot | 200,000 | 500 | 100,000,000 |
| Singer | 5,000,000 | 1 | 5,000,000 |
The bot has fewer followers but causes 20 times more write load. A threshold on follower count alone would push the bot and pull the singer, which is the wrong way round for write cost. Better rules:
- Threshold on expected write amplification, which is followers times recent posting rate.
- Combine a follower threshold with a per-author rate limit on pushes.
- Make the decision per author and allow manual overrides for known outliers.
The rule needs two safeguards:
- Hysteresis. An account near the threshold can flip back and forth. Use a higher bar to become a pulled account (for example 100,000) and a lower bar to return to being pushed (for example 80,000).
- Slow reclassification. Re-evaluate on a schedule rather than on every follow event, and handle the transition explicitly (see the failure modes below).
A minimal implementation
The code below extends the earlier fan-out on write example. It uses in-memory structures so you can run it as shown. The threshold is set to 3 so the demo is small. In production it would be tens of thousands or more.
import heapq
from collections import defaultdict
from itertools import islice
FEED_LIMIT = 800 # max entries per precomputed timeline
RECENT_LIMIT = 200 # max recent posts kept per author
CELEB_THRESHOLD = 3 # demo value; use a much larger number in production
followers = defaultdict(set) # author_id -> set of follower ids
following = defaultdict(set) # user_id -> set of followed author ids
feeds = defaultdict(list) # user_id -> [(timestamp, post_id)], newest first
author_posts = defaultdict(list) # author_id -> [(timestamp, post_id)], newest first
def follow(follower_id, author_id):
followers[author_id].add(follower_id)
following[follower_id].add(author_id)
def is_high_follower(author_id):
return len(followers[author_id]) >= CELEB_THRESHOLD
def publish(author_id, post_id, timestamp):
# Always record the post in the author's own list.
recent = author_posts[author_id]
recent.append((timestamp, post_id))
recent.sort(reverse=True)
del recent[RECENT_LIMIT:]
# Push only for ordinary authors.
if is_high_follower(author_id):
return
for follower_id in followers[author_id]:
feed = feeds[follower_id]
feed.append((timestamp, post_id))
feed.sort(reverse=True)
del feed[FEED_LIMIT:]
def read_feed(user_id, limit=20):
pushed = feeds[user_id]
pulled = [
author_posts[a]
for a in following[user_id]
if is_high_follower(a)
]
merged = heapq.merge(pushed, *pulled, reverse=True)
return list(islice(merged, limit))
# Demo
for u in ("u1", "u2", "u3"):
follow(u, "star") # star reaches the threshold of 3 followers
follow("u1", "alice") # alice has one follower, so her posts are pushed
publish("alice", "a1", 100)
publish("star", "s1", 101)
publish("alice", "a2", 102)
publish("star", "s2", 103)
print(read_feed("u1", limit=3))
# [(103, 's2'), (102, 'a2'), (101, 's1')]Three points about this code:
- Every post is stored in
author_posts, whether or not it is pushed. The pull path depends on that list. heapq.mergeis lazy. It reads only as many items from each sorted input as needed to producelimitresults, so merging a few long lists stays cheap.- Every input to the merge must already be sorted newest first. If one is not,
heapq.mergesilently returns wrongly ordered output instead of raising an error.
The read path in a real system
In production, the two sources live in different places.
- The precomputed timeline is a bounded list in a cache such as Redis. The next-but-one chapter covers its structure.
- Each high-follower author's recent posts are a small list, often cached separately under a key such as
recent:{author_id}.
A read does these steps:
- Fetch the user's followed high-follower author IDs. This set is small, so it can be stored with the user's profile or derived from the follow graph and cached.
- Fetch the precomputed timeline and each author's recent list. Issue these requests in parallel.
- Merge them and cut the result to a page.
- Resolve post IDs into full post objects (text, media, counts) with a batched lookup.
The pulled lists benefit from caching more than anything else in the system. Every follower of an author reads the same recent:{author_id} list. That makes it one of the hottest keys in the system, and a very effective cache entry. Because it is hot, you may need to replicate it across several cache nodes and read from a random replica. Otherwise one node serves millions of requests.
Pagination with two sources
The merged stream still has a single total order, which is (timestamp, post_id) descending. This means the cursor from the pagination chapter works unchanged. The cursor is the last item returned, and the next request returns items strictly older than it.
Each source applies the cursor on its own:
- Precomputed timeline: skip entries that are not older than the cursor.
- Each pulled author list: skip entries that are not older than the cursor.
Then merge as before. Because the cursor is a value and not an offset, it does not matter that the two sources change at different rates between requests. A new post from a pulled author only appears at the top. It does not shift older items, so page 2 does not repeat page 1.
Deep pages need care. A pulled list capped at 200 posts may run out before the precomputed timeline does. If a cursor points past the end of a capped list, the reader falls back to a database query using the keyset SQL from the pagination chapter, restricted to that author. Otherwise high-follower posts would quietly vanish from deep scrolling.
Costs compared
| Aspect | Push only | Pull only | Hybrid |
|---|---|---|---|
| Write cost per post | Proportional to followers | One write | Proportional to followers, but only below the threshold |
| Read cost | One timeline lookup | One query per followed author | One timeline lookup plus a few list lookups |
| Delay before followers see a post | Grows with follower count | None | Short for everyone |
| Storage | Large (each post is copied many times) | Small | Moderate |
| Complexity | Low | Low | Higher: two code paths and a classification rule |
The hybrid costs more in engineering effort, since there are two code paths to keep consistent, but it bounds both the worst-case write and the worst-case read.
Failure modes and edge cases
An author crosses the threshold
Suppose an author grows from ordinary to high-follower. Posts made earlier were already pushed into follower timelines and they stay there. New posts are only pulled. A reader sees both, and because they are ordered by one key, the feed looks continuous.
The danger is duplicates in the opposite direction. If an author drops below the threshold and the system starts pushing again, the same post could sit in a timeline and in the author's recent list. Deduplicate by post_id in the merge step. Duplicates are adjacent in the merged order only when timestamps tie, so keep a seen-set for the page you build:
def dedupe(items):
seen = set()
for ts, post_id in items:
if post_id not in seen:
seen.add(post_id)
yield (ts, post_id)Followers who never read
Many followers are inactive. Even for ordinary authors, a push into an inactive user's timeline is wasted. A common optimization is to push only to users who were active in the last N days. When an inactive user returns, rebuild the timeline with the pull path and resume pushing. This reduces write volume for large-but-not-huge accounts and lets you raise the threshold.
The pull path becomes the bottleneck
A user who follows 2,000 high-follower accounts makes the read slow again. Mitigations:
- Cap the number of pulled authors merged per request, preferring the most recently active ones.
- Precompute a per-user "pulled authors" timeline for heavy followers, refreshed in the background.
- Treat very heavy followers as a special case and accept a slightly stale feed.
Hot keys and bursts
A breaking-news post from a huge account makes millions of users refresh in the same minute. They all read the same recent list. Replicate that key, add a short local cache (a few seconds) in the application tier, and use request coalescing so one cache miss triggers one database fetch.
Deletes and privacy
A deleted post from a pushed author leaves references in many timelines. A deleted post from a pulled author disappears once the author's recent list is updated. Because references are IDs, the read path should filter out posts that no longer resolve, or are hidden by a block or privacy rule, at the final batched lookup. The edge cases chapter covers this fully. For now, note that the hybrid design makes the final lookup step the single place where such filtering must happen.
Choosing the design in practice
Use the hybrid design when follower counts are heavily skewed, which is true of almost every public social network. A few accounts hold most of the followers. If your product has uniformly small audiences, such as a private team feed, plain fan-out on write is simpler and enough.
Start with push for everyone and add the pull path only when measurements show write bursts hurting latency. The threshold should come from data: record the distribution of follower counts, the time to complete a fan-out, and the queue depth of the fan-out workers.
Exercise
An account has 2 million followers and posts 3 times per day. Your fan-out workers insert 40,000 timeline entries per second. How long does one push take, and what would you do with this account under the hybrid design?
Show answer
One push is 2,000,000 / 40,000 = 50 seconds. Three posts per day is 6,000,000 timeline writes, so the daily load is modest, but each post still has a 50-second spread in delivery, and workers are busy during it. Whether to pull this account depends on the threshold and the delivery-time goal. If posts must reach followers within a few seconds, treat the account as high-follower and pull its posts. Otherwise push to active followers only. Either choice should come from the measured write amplification (followers times posts), not from follower count alone.
Exercise
A reader follows one pulled author and has a precomputed timeline. The reader requests page 2 using the cursor (103, "s2"). Describe how each source is filtered, and why a new post from the pulled author arriving between page 1 and page 2 does not appear twice.
Show answer
Both the timeline and the author's recent list drop every entry that is not strictly older than (103, "s2") in (timestamp, post_id) order. The remaining entries are merged and cut to the page size. The new post has a timestamp newer than the cursor, so it is filtered out of page 2. It appears only when the reader reloads from the top. Because the cursor is a value and not an offset, new items at the top do not shift older ones.