Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 5 · Concept · 25 min · revision 1

Push, pull and hybrid timelines

Compare fan-out on read, fan-out on write and hybrids on read cost, write amplification, storage and freshness, measure them on a seeded synthetic follow graph, and learn when each choice is the wrong one.

Contentsand lesson path

What you will learn

  • Compare fan-out on write, fan-out on read and hybrid strategies using follower distribution and read/write rates.

Prerequisites: Caching Strategies

01. Why it matters

When someone opens the feed, where do its posts come from? The feed can be assembled when it is read, by fetching the newest posts of every followed account and merging them. Or it can be built when posts are written, by copying each new post's id into a ready-made list for every follower. The first is called fan-out on read (or pull), the second fan-out on write (or push). Large feed designs use one or a mix, decided by numbers like those you estimated in lesson 1: feed opens outnumbered posts 16 to 1, the mean account had 73 followers, and the largest had 622,454.

This lesson compares them on four costs: work per read (and so latency), writes per post (write amplification), storage for the ready-made lists, and how quickly a post shows up (freshness).

Diagram · the two basic data flows
fan-out on read (pull)
  write:  post --> posts table (indexed by author, post id)
  read:   my follows --> newest posts of each followed account --> merge --> page

fan-out on write (push)
  write:  post --> posts table --> queue --> fan-out workers
                                               |--> timeline of follower 1
                                               |--> timeline of follower 2
                                               '--> ... one insert per follower
  read:   my timeline (post ids) --> post bodies --> page

02. Start simple: assemble the feed when it is read

The first design most teams build is one query. Posts are stored once, in a table indexed by author and post id, and the feed is a join with the follows table:

SQL · pull.sql, the read-time feed query (schema of lesson 3)
-- Fan-out on read: the newest 20 posts from every account that user :me follows.
-- posts has an index on (author_id, post_id); post ids grow with time.
SELECT p.post_id, p.author_id, p.body
FROM follows AS f
JOIN posts AS p ON p.author_id = f.followee_id
WHERE f.follower_id = :me
ORDER BY p.post_id DESC
LIMIT 20;

This is a good design, not a straw man: each post is written once. A new follow, an unfollow or a deleted post shows up on the next read from the primary database, because nothing was copied, and there is no fan-out pipeline to fall behind. For thousands or even a few hundred thousand users, it is often the right answer.

Its limit is the read. On the lesson 3 database, SQLite plans this query as one index search per followed account followed by a temporary sort of everything they found. Work per feed open grows with the number of accounts followed, so the slowest reads belong to those who follow the most. When posts are sharded by author, as in the social graph worked example, each open also touches many shards. With reads outnumbering writes 16 to 1, you pay that merge on the frequent operation.

03. Fan-out on write: build each feed in advance

Push moves the work to the rarer operation. A saved post puts an event on a queue. Fan-out workers read it, page through the author's followers, and insert the post id into each follower's timeline, a short list of recent post ids kept in a cache. A read then fetches one list and looks up the posts it names.

The costs move with it:

  • Write amplification: one post becomes one insert per follower, 73 on average in lesson 1, 622,454 for the largest account.
  • Storage: every follower holds a copy of every id, which is why timelines keep ids rather than whole posts and only the newest few hundred (lesson 3 measures it).
  • Freshness: a post reaches the last follower only when the workers get there, so delay depends on the queue and grows with the author's audience.
  • Graph changes: a new follow does not bring old posts into the timeline unless you backfill them, and an unfollow leaves ids behind unless you remove them or filter them out when reading.
  • Retries: the queue delivers at least once, so an insert must be safe to repeat, as in delivery guarantees and idempotent consumers.

04. Measuring both on a synthetic graph

The costs depend on the follower distribution and on who reads, so measure them. The script below builds a seeded, synthetic graph of 100,000 users in which a few accounts attract most follows, simulates one day of posts and feed opens (60% of users do not open the app that day), and counts each strategy's work. It needs Python 3.12 or later (for random.binomialvariate) and runs for about half a minute.

The columns: inserts are timeline writes; burst is the largest number of inserts caused by one post; reads counts sources read across all feed opens, where your own timeline is one source and each account pulled at read time is one more; p50 and p99 are sources read by a median and a 99th-percentile feed open.

Python · strategies.py
"""One simulated day of push, pull and hybrid fan-out on a SYNTHETIC follow graph.

Seeded, Python 3.12, stdlib only. The graph and the activity are invented: they
show how the strategies trade costs, not how any real network behaves.
"""
import itertools
import random
import statistics

USERS = 100_000
rng = random.Random(42)

# Who follows whom: each user picks followees in proportion to a heavy-tailed
# popularity score, so a few accounts collect very many followers.
popularity = list(itertools.accumulate(rng.paretovariate(1.5) for _ in range(USERS)))
follows = []  # follows[u] = set of accounts u follows
for u in range(USERS):
    k = min(int(rng.lognormvariate(4.0, 0.8)), 2_000)  # median about 55
    picked = rng.choices(range(USERS), cum_weights=popularity, k=k)
    follows.append(set(picked) - {u})
followers = [0] * USERS
for followees in follows:
    for a in followees:
        followers[a] += 1

# One day of activity: 60% of users do not open the app at all.
posts = [rng.binomialvariate(4, 0.1) for _ in range(USERS)]  # mean 0.4 per day
opens = [0 if rng.random() < 0.6 else 1 + int(rng.lognormvariate(1.6, 0.7))
         for _ in range(USERS)]


def day_cost(pushed) -> tuple[int, int, int, list[int]]:
    """pushed(author, reader) -> True if that edge is fanned out on write.

    Returns timeline inserts, the largest burst caused by one post, sources read,
    and the number of sources read for each feed open."""
    inserts, reads, per_open = 0, 0, []
    burst = [0] * USERS  # inserts caused by one post of each author
    for u in range(USERS):
        pulled = 0
        for a in follows[u]:
            if pushed(a, u):
                inserts += posts[a]
                burst[a] += 1
            else:
                pulled += 1
        if opens[u]:
            sources = 1 + pulled  # own timeline + every account pulled at read time
            reads += opens[u] * sources
            per_open += [sources] * opens[u]
    largest = max(b for a, b in enumerate(burst) if posts[a])
    return inserts, largest, reads, per_open


total_posts = sum(posts)
print(f"users {USERS:,}  follow edges {sum(followers):,}  posts {total_posts:,}"
      f"  feed opens {sum(opens):,}")
print(f"followers per account: median {statistics.median(followers):,.0f}"
      f"  max {max(followers):,}")
print()
print(f"{'strategy':<24}{'inserts':>10}{'per post':>9}{'burst':>7}{'reads':>11}"
      f"{'p50':>4}{'p99':>5}")
rules = {"push to everyone": lambda a, u: True,
         "pull everything": lambda a, u: False}
for t in (20_000, 5_000, 1_000):
    rules[f"hybrid, pull {t:,}+"] = lambda a, u, t=t: followers[a] < t
rules["per pair: opens >= posts"] = lambda a, u: opens[u] >= posts[a]
for name, rule in rules.items():
    inserts, burst, reads, per_open = day_cost(rule)
    q = statistics.quantiles(per_open, n=100)
    print(f"{name:<24}{inserts:>10,}{inserts / total_posts:>9,.0f}{burst:>7,}"
          f"{reads:>11,}{q[49]:>4,.0f}{q[98]:>5,.0f}")
for t in (20_000, 5_000, 1_000):
    print(f"accounts with {t:,}+ followers: {sum(f >= t for f in followers)}")
Terminal
python3 strategies.py
Expected output
users 100,000  follow edges 7,301,193  posts 39,695  feed opens 272,060
followers per account: median 40  max 64,811

strategy                   inserts per post  burst      reads p50  p99
push to everyone         2,874,691       72 34,666    272,060   1    1
pull everything                  0        0      0 20,277,044  55  335
hybrid, pull 20,000+     2,819,465       71 12,386    789,447   3    7
hybrid, pull 5,000+      2,738,265       69  4,620  1,269,031   4   14
hybrid, pull 1,000+      2,490,693       63    999  3,039,788   9   43
per pair: opens >= posts 1,143,919       29 13,987    275,368   1    1
accounts with 20,000+ followers: 6
accounts with 5,000+ followers: 27
accounts with 1,000+ followers: 392

Pure push writes 72 ids per post and lets every open read exactly one source, but one post caused 34,666 inserts in a burst. Pure pull writes nothing extra and pays for it on reads: 20.3 million source reads, 75 times as many, with a 99th-percentile open merging 335 accounts. The graph is invented, so read these as the shape of the trade, not a forecast.

05. Hybrid: push for most accounts, pull for a few

A hybrid pushes posts from ordinary accounts and pulls posts from accounts above a follower threshold, merging them into the timeline at read time. The System Design Primer's sample design suggests exactly this for highly followed users. Pulling only the 6 accounts with 20,000+ followers cuts total inserts by just 2%, yet it shrinks the largest burst from 34,666 to 12,386, and a 99th-percentile open now merges 7 sources instead of 1. A threshold of 1,000 caps every burst below 1,000 inserts but pulls 392 accounts, and reads grow to 11 times the push figure. The threshold trades burst size on the write side against merge work on the read side, so pick it from numbers like these and your freshness target, not from a rule of thumb.

The last row tests a different idea from a 2010 paper by Silberstein and colleagues, Feeding Frenzy. Under their cost model, the best choice can be made for each follower and author pair separately: push when the reader's view rate divided by the author's posting rate is at least the cost of a push divided by the cost of a pull. When the two cost about the same, push if the reader opens the feed at least as often as the author posts. That form is derived for feeds that show each author's newest posts; for one newest-first feed, the paper compares the reader's rate with the summed rate of all followed authors. The last row uses the simpler per-author form. Applied to the simulated day, it cuts inserts by 60% while reads stay close to pure push. Most of that saving comes not from celebrities but from not writing to the 60% of users who never open the app that day.

Treat that row with care: the rule saw the day's actual rates, which a real system only estimates from history, wrongly for the reader who returns after a month; that reader's timeline is rebuilt on demand (lesson 3). The two ideas combine well: a threshold caps bursts, and skipping inactive readers cuts total volume.

06. When each choice is the wrong one

Pull is wrong when reads far outnumber posts and readers follow hundreds of accounts spread over many shards. Every open pays a merge, and the p99 is set by the heaviest followers. It is right when the app is small enough that one indexed query meets the latency target: then it is simpler, always fresh, and you can move to push when measurements say so.

Push is wrong when audiences are huge and bursty enough to break the freshness target, when most followers rarely read (the writes and memory are wasted), or when the product needs a follow, unfollow or delete to take effect in every feed at once.

Hybrid is wrong when no account is big enough to justify a second read path. Two paths mean two sets of code, tests and failure modes, and a merge on every read. A workplace app whose largest channel has a few thousand members gains nothing from it. A hybrid is also wrong when its threshold was chosen once and never revisited: lesson 1 showed the largest audience growing with the network.

Change the read-to-write ratio and the answer moves. With feed opens rarer than posts, as in an archive that people check weekly, the pull column's cost falls with opens while push still writes every post to every follower, and pull or a per-pair rule becomes the better fit.

07. Check your understanding

Practice check · 3 questions

Choosing push or pull

Predict what the design does in each situation.

Q1. You use the per-pair rule from Feeding Frenzy, with pushing and pulling a post costing about the same. A breaking-news account posts 200 times a day, and one of its followers opens the app twice a day. What should happen for this pair?
Q2. Under fan-out on write, a user follows an account that posted 30 times last week. The design has no extra step for new follows. What does the user's feed show from that account?
Q3. A hybrid feed pushes posts from accounts under 20,000 followers and pulls the rest at read time. The fan-out queue falls 10 minutes behind. Which posts reach readers late?
Practice only: not graded, not saved, not evidence.

08. Apply it

Extend strategies.py for the design doc you started in lesson 1:

  1. Add a strategy that pushes only to readers who opened the app in the last 7 days. Simulate 8 days, decide activity from days 1 to 7, and charge a timeline rebuild (one source per followed account) the first time an inactive reader opens on day 8.
  2. Replace the per-pair rule's oracle with rates estimated from the previous day, and compare its inserts and reads with the oracle row.
  3. Write a selection criterion before looking at results, for example "largest burst under 5,000 inserts, so that one post drains in under 5 seconds at our worker capacity, and p99 sources per open under 20". Then pick the threshold that meets it with the fewest reads, and record the losing options and why they lost.

09. Review prompt

Without looking back, explain in your own words:

  1. Where the work goes in fan-out on read and in fan-out on write, and which of the two pays on the frequent operation in a read-heavy app.
  2. What a follower threshold buys and what it costs, using the burst and p99 columns.
  3. Why the per-pair rule saved more inserts than any threshold in the simulation, and why its row is optimistic.
  4. One situation in which each of pull, push and hybrid is the wrong choice.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check