Courses / System Design Interview / Chapter 31
Module 7 · Design Problems II: Rides and Social Feeds · Chapter 31 of 49
Design a Microblogging Service like Twitter
Builds on Back-of-the-Envelope Estimates, Unique IDs: Sequencers, UUIDs and Snowflake IDs, Distributed Caches, Distributed Message Queues, Publish-Subscribe Systems, Distributed Search and Sharded Counters. Next up: Design a News Feed.
Part 1 · Requirements and estimates
What the service must do
A microblogging service lets people post short messages and read a timeline of what the accounts they follow have posted. This chapter designs the posting, following and timeline parts, plus search and trending topics, for a service with 20 crore daily users.
The functional requirements are: post a short text with optional media links; follow and unfollow accounts; read a home timeline, which is the newest posts from the accounts you follow, paged; read a profile timeline of one account's posts; search posts and hashtags; and see the trending topics. Direct messages, ads, uploading photos and video, and a recommended 'for you' feed are out of scope. Ranking a feed by relevance and handling photos are left to later chapters, and video is covered in the video platform chapter.
The non-functional requirements are the shape of the traffic. A timeline must load in a couple of hundred milliseconds. The service must stay up, and a post may take a few seconds to reach followers, so we choose eventual consistency. Reads far outnumber writes. And follower counts are very uneven: most accounts have a handful of followers, while a few have crores, so a design that works for the average account can fail for the largest.
| Question to ask | Answer we assume |
|---|---|
| How many users? | 20 crore active a day |
| How often do they read? | 5 timeline loads a day each |
| How often do they post? | On average one post every ten days |
| How many followers? | 200 on average, with a very long tail |
| How long is a post? | Short text, about 300 bytes with its metadata |
| How fresh must a timeline be? |
Sizing the traffic
The script follows the habit from the estimates chapter: assumptions at the top, one result per line. It computes the read rate, the post rate and, most important for the design, the number of timeline inserts per second if every post is copied into every follower's timeline.
# Inputs are assumptions for a large microblogging service. dau = 20_00_00_000 # daily active users loads_per_user = 5 # times a user opens the home timeline posts_per_user = 0.1 # average posts per active user per day followers = 200 # average followers per account peak = 3 # busy hour against the daily average post_bytes = 300 # text, ids, counters, media links reads_s = dau * loads_per_user / 86_400 posts_s = dau * posts_per_user / 86_400 fan_s = posts_s * followers print(f"timeline reads per second, average: {reads_s:,.0f}") print(f"timeline reads per second, peak: {reads_s * peak:,.0f}") print(f"posts per second, average: {posts_s:,.0f}") print(f"reads for every post: {reads_s / posts_s:,.0f}") print(f"timeline inserts per second if every post is pushed: " f"{fan_s:,.0f}") print(f"post storage per year: " f"{dau * posts_per_user * 365 * post_bytes / 1e12:,.1f} TB") page_posts = 20 # posts returned in one timeline page ids_per_cache = 800 # post ids kept in one cached timeline id_bytes = 8 # one 64-bit post id peak_reads = reads_s * peak print(f"post bytes read per second at peak (20 posts a page): " f"{peak_reads * page_posts * post_bytes / 1e6:,.0f} MB") print(f"timeline cache for every active user: " f"{dau * ids_per_cache * id_bytes / 1e12:,.2f} TB")
Python 3.12.10. All inputs are assumptions.
timeline reads per second, average: 11,574 timeline reads per second, peak: 34,722 posts per second, average: 231 reads for every post: 50 timeline inserts per second if every post is pushed: 46,296 post storage per year: 2.2 TB post bytes read per second at peak (20 posts a page): 208 MB timeline cache for every active user: 1.28 TB
Output of the estimate.
Timelines are read 11,574 times a second on average and about 34,700 at the busy hour. Posts arrive at 231 a second, so there are 50 timeline reads for every post. Storing posts takes 2.2 TB a year at 300 bytes each, which is small. The expensive line is the fifth: copying every post to 200 follower timelines means 46,296 timeline inserts a second, and about three times that at the peak.
Two more lines size the other paths. A busy-hour timeline page carries 20 posts of about 300 bytes, which is 208 MB a second of post data read at the peak, so the post cache has to absorb most of it. And if every active user had a cached timeline of 800 post ids at 8 bytes each, the cache would hold 1.28 TB. That is large but ordinary for a sharded cache, and it is the reason the later lessons cap the length of a timeline and skip users who have not been seen for a month.
What the numbers decide
Reads for each post written: ≈ 50 (the read path is the common one)
Read it as steps
Pushing every post to every follower turns 231 posts a second into about 46,000 timeline writes.
The scene shows the same numbers one step at a time. It makes two points. Reads outnumber posts by about fifty to one, so the timeline read must be cheap, and one cheap read means the work of building the timeline is best done before it is asked for. And that early work is itself large: one post becomes 200 writes on average, and a post by a very large account becomes a crore.
The two points pull in opposite directions, and the fourth lesson resolves them. Doing the work on write makes reads cheap but makes big accounts expensive. Doing it on read makes posts cheap but makes every read expensive. The estimate does not pick a side, it shows that the choice is the heart of the problem.
Why does a timeline read need to be cheap?
- Reads outnumber posts about fifty to one, so a small cost per read is multiplied far more than a cost per post.
From the estimate, how many timeline inserts a second would pushing every post produce on average?
- About 46,296, from 231 posts a second times 200 followers. The peak is about three times that.
Part 2 · API and data model, post ids
The calls
The API is small, and two of its choices matter. Timelines are paged with a cursor that is itself a post id, and every call that changes data is safe to repeat. The sketch below is a design sketch and it is not run.
POST /v1/posts create a post
Idempotency-Key: 91ab-example
{ "body": "first post from the hostel", "reply_to": null }
201 Created { "id": 4194316288 }
GET /v1/timeline/home?limit=20&before=4194316288
GET /v1/users/{id}/posts?limit=20&before=...
PUT /v1/users/{id}/follow follow
DELETE /v1/users/{id}/follow unfollow
GET /v1/search?q=%23monsoon&limit=20
GET /v1/trends?region=inAPI sketch, not run.
before is the id of the last post the client already has, and the server returns the next older posts. A cursor like this stays correct when new posts arrive during scrolling, which a page number does not. Because ids rise with time, the cursor is both a position and a time.
Two more calls follow from the requirements. DELETE /v1/posts/{id} removes a post, and the service marks it deleted before it is cleaned up everywhere, so timelines and search stop showing it at once. The server also checks the body length and rejects an over-long post with a 400, since a limit enforced only in the app can be bypassed by anyone who calls the API directly. The limit is a number the product picks and the design does not depend on it.
Following uses PUT and DELETE, which are idempotent by their definition in HTTP: following twice leaves one follow, and unfollowing twice leaves none. Creating a post uses an idempotency key, so a retry after a timeout returns the post that already exists.
Ids that sort by time
A post needs an id that is unique, compact and sortable by time, so that 'newest first' is a sort on the id. The sequencer chapter covered the Snowflake-style layout, and this page reuses it so the code runs on its own: 41 bits of milliseconds since a chosen epoch, 10 bits of machine number and 12 bits of counter. Any machine can make ids with no coordination, and the ids from one machine are always rising.
import threading, time EPOCH_MS = 1_700_000_000_000 # our own epoch, in milliseconds MACHINE_BITS, SEQ_BITS = 10, 12 class IdGen: """41 bits of time, 10 of machine, 12 of sequence.""" def __init__(self, machine, clock=lambda: int(time.time() * 1000)): self.machine, self.clock = machine, clock self.last, self.seq = -1, 0 self.lock = threading.Lock() def next(self): with self.lock: now = self.clock() - EPOCH_MS if now < self.last: raise RuntimeError("clock moved backwards") if now == self.last: self.seq = (self.seq + 1) & ((1 << SEQ_BITS) - 1) if self.seq == 0: # 4,096 ids used this ms while now <= self.last: now = self.clock() - EPOCH_MS else: self.seq = 0 self.last = now return ((now << (MACHINE_BITS + SEQ_BITS)) | (self.machine << SEQ_BITS) | self.seq)
Python 3.12.10. Save this block and the next together as ids.py.
def decode(i): return (i >> (MACHINE_BITS + SEQ_BITS), (i >> SEQ_BITS) & ((1 << MACHINE_BITS) - 1), i & ((1 << SEQ_BITS) - 1))
Continues ids.py: split an id back into its three parts.
The generator refuses to run if the clock moves backwards, and it waits for the next millisecond if the 4,096 values of the counter are used up. The second script uses a scripted clock, so the output repeats, and makes seven ids on one machine, with several in the same millisecond.
from ids import IdGen, decode, EPOCH_MS ticks = iter([1000, 1000, 1000, 1001, 1002, 1002, 1005]) a = IdGen(machine=3, clock=lambda: EPOCH_MS + next(ticks)) ids = [a.next() for _ in range(7)] for i in ids: t, m, s = decode(i) print(f"{i:>16} ms {t} machine {m} seq {s}") print("sorted by id equals creation order:", ids == sorted(ids))
Save as ids_run.py. The clock is scripted, so the output repeats.
4194316288 ms 1000 machine 3 seq 0 4194316289 ms 1000 machine 3 seq 1 4194316290 ms 1000 machine 3 seq 2 4198510592 ms 1001 machine 3 seq 0 4202704896 ms 1002 machine 3 seq 0 4202704897 ms 1002 machine 3 seq 1 4215287808 ms 1005 machine 3 seq 0 sorted by id equals creation order: True
Output. The last line checks the order.
The tables
Reading the output, the first three ids share millisecond 1000 and differ in their sequence number. The next id has millisecond 1001, and each id is larger than the one before. Sorting ids is therefore the same as sorting by creation time, to the millisecond, which is all a timeline needs.
The post table uses the id as its primary key, and an index on author and id, newest first, answers the profile timeline. The script below inserts ten posts with ids from a scripted clock and reads them back in pages of three, using the last id of each page as the cursor.
import sqlite3 from ids import IdGen, EPOCH_MS db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE posts ( id INTEGER PRIMARY KEY, -- time-ordered id author_id INTEGER NOT NULL, body TEXT NOT NULL, reply_to INTEGER ); CREATE INDEX posts_by_author ON posts (author_id, id DESC); """) t = iter(range(5000, 5100)) gen = IdGen(machine=1, clock=lambda: EPOCH_MS + next(t)) for n in range(10): db.execute("INSERT INTO posts (id, author_id, body) VALUES (?,?,?)", (gen.next(), 42, f"post number {n}"))
Python 3.12.10. Save as posts_run.py, next to ids.py.
def page(cursor, limit=3): q = "SELECT id, body FROM posts WHERE author_id = 42 " args = [] if cursor: q += "AND id < ? " args.append(cursor) q += "ORDER BY id DESC LIMIT ?" return db.execute(q, args + [limit]).fetchall() cursor = None for _ in range(2): rows = page(cursor) print([b for _, b in rows]) cursor = rows[-1][0]
Continues posts_run.py: paging with the last id as the cursor.
['post number 9', 'post number 8', 'post number 7'] ['post number 6', 'post number 5', 'post number 4']
Output: two pages of three, newest first, with no overlap.
The follow relationship is a second table of pairs, follower and followed, with an index in each direction. Pushing a post needs 'who follows this author', and pulling a timeline needs 'who does this reader follow', so both directions are queried often. At this scale the pairs table is sharded by one side and a copy by the other is kept, a duplicate that is worth its cost because both questions are common.
Why can a timeline be sorted by post id alone?
- The id starts with the time in milliseconds, so a larger id is a newer post. The run printed ids that were in creation order.
Part 3 · High-level design
The write path and the read path
The design has a write path that runs when someone posts and a read path that runs when someone opens a timeline. They meet at the timeline cache and the post store. The post is first saved in the post store, which is the source of truth, so that it cannot be lost. Then an event goes onto a queue, and a pool of fan-out workers takes it from there.
A fan-out worker looks up the author's followers in the follow graph and adds the post id to each follower's cached timeline. The author's request does not wait for this. It returns as soon as the post is stored and the event is queued, and the copying finishes a little later. That delay is the eventual consistency we accepted, and the queue absorbs bursts, as in the message queue chapter.
The read path is short. The API reads the list of post ids from the reader's cached timeline, fetches the posts' contents from a post cache or the post store, and returns a page. Storing only ids in the timeline keeps each cached timeline small, and a post that is edited or deleted changes in one place, not in every copy.
One post, one read, one celebrity
Watch for an ordinary post being copied into follower timelines
Read it as steps
An ordinary post is pushed to follower timelines. A celebrity's post is fetched when a reader opens the timeline.
The scene walks an ordinary post, a read and a celebrity's post. The ordinary post is copied to about 200 timelines, and a later read needs only the cache. The celebrity's post is a different case: copying it into crores of timelines would flood the queue, so the post is not pushed at all. The API fetches it from the post store when a reader opens the timeline and merges it with the cached ids.
This mixed rule is the hybrid approach. It is the subject of the next lesson, which counts the writes each choice costs. The scene's numbers, such as 200 ids, are the assumption from the first lesson and not measurements.
Components and their jobs
The follow graph is read on every post and every timeline read, so it is cached and sharded. The timeline cache is the biggest memory user: each active user has a list of ids, kept to a fixed length such as the newest 800, as the last lesson explains. Users who have not opened the app for a month are not given a cached timeline at all. Their timeline is built on demand when they come back, which saves a large share of the writes.
A separate search service receives the same post events and builds a searchable index, so a post becomes findable within seconds. A trends service reads the same stream and counts hashtags in a sliding window. Both are consumers of one event stream, a use of the publish-subscribe pattern: adding a new consumer does not change the posting path.
A public repository named the-algorithm, published by a large microblogging company, describes its recommendation algorithm and a home timeline built from several candidate sources. Its README says that about half of the posts come from the in-network source, meaning accounts the user follows, and that a service called Home Mixer constructs and serves the timeline. The repository covers ranking at a scale this chapter does not model, and we claim nothing about that company's design beyond what it says.
Why does the author's request not wait for the copy to every follower?
- The copying can take longer than a request should. The post is stored and the event queued, so the request returns quickly.
Why do cached timelines hold post ids and not whole posts?
- Ids keep each timeline small, and an edit or delete changes one stored post instead of every copy.
Why give inactive users no cached timeline?
- Writing to timelines nobody reads wastes work. Their timeline is built on demand when they return.
Part 4 · Deep dive: fan-out on write or on read
Three strategies
There are three ways to build a home timeline. With fan-out on write, also called push, every new post is copied into the cached timeline of each follower. A read is one cache lookup, and a write costs one insert per follower. With fan-out on read, called pull, nothing is copied. A read looks up whom the reader follows, fetches the recent posts of each, and merges them. A write is one insert, and a read costs one lookup per followed account.
The hybrid strategy chooses by account. Ordinary accounts are pushed. Accounts above a follower threshold, which we can call big accounts, are pulled: their posts are not copied, and a reader's timeline is the cached ids plus the recent posts of the big accounts that reader follows. The threshold trades write cost against read cost.
The follower counts that decide this are not even. The script below generates a heavy-tailed follower count for each of ten lakh accounts. Most get a small number and a few get a very large one, capped at half the accounts. A Pareto distribution is a common model for such counts, and the shape parameter here is our assumption, so the output shows a pattern and not real data.
import random N = 10_00_000 # accounts rnd = random.Random(8) # Heavy-tailed follower counts: most accounts small, a few huge, # and nobody can have more followers than half the accounts. followers = [min(int(10 * rnd.paretovariate(1.1)), N // 2) for _ in range(N)] followers.sort(reverse=True) total = sum(followers) top = followers[:N // 100] print(f"accounts: {N:,} mean followers: {total / N:.1f}") print(f"median followers: {followers[N // 2]} max: {followers[0]:,}") print(f"top 1% of accounts hold {sum(top) / total:.0%} of all follows")
Python 3.12.10. Save this block and the next together as fanout.py.
accounts: 1,000,000 mean followers: 73.1 median followers: 18 max: 500,000 top 1% of accounts hold 49% of all follows
Output of the first block; the table comes with the next block.
Counting the writes
The second block counts, for each strategy, the timeline writes a day when every account posts once, and the lookups a reader makes per timeline read. A reader follows, on average, as many accounts as an account has followers, which is the total number of follows divided by the number of accounts. For a hybrid, limit is the follower count above which an account is pulled.
# Everyone posts once a day, so a day has N posts. A reader follows # total / N accounts on average. follows_per_user = total / N def hybrid(limit): """Accounts above `limit` followers are pulled at read time.""" big = [f for f in followers if f > limit] writes = total - sum(big) # pushed to follower timelines pulled = sum(big) / N # big accounts followed return len(big), writes, 1 + pulled # lookups per timeline read print(f"biggest post: {followers[0]:,} timeline writes if pushed") print(f"{'strategy':<22}{'big accts':>10}{'writes/day':>12}" f"{'lookups/read':>14}") print(f"{'push to everyone':<22}{0:>10}{total:>12,}{1:>14.1f}") for limit in (100_000, 10_000, 1_000, 200): n, w, r = hybrid(limit) print(f"{'hybrid above ' + format(limit, ','):<22}{n:>10}" f"{w:>12,}{r:>14.1f}") print(f"{'pull on read':<22}{N:>10}{N:>12,}" f"{1 + follows_per_user:>14.1f}")
Continues fanout.py: the cost of each strategy.
biggest post: 500,000 timeline writes if pushed strategy big accts writes/day lookups/read push to everyone 0 73,053,346 1.0 hybrid above 100,000 34 64,910,581 9.1 hybrid above 10,000 476 53,929,470 20.1 hybrid above 1,000 6185 40,158,698 33.9 hybrid above 200 36665 28,068,083 46.0 pull on read 1000000 1,000,000 74.1
Output of the second block. The first block printed the three lines above it.
The follower counts are very uneven: the median account has 18 followers, the largest has 5 lakh, and the top 1 percent of accounts hold 49 percent of all follows. Pushing everything costs 7.31 crore writes a day and one lookup per read. Pulling everything costs 10 lakh writes and 74.1 lookups per read. The hybrid rows lie between them.
The details are instructive. A threshold of 1 lakh followers pulls only 34 accounts and saves just 11 percent of the writes, from 7.31 crore to 6.49 crore. But it removes the worst bursts: no single post is copied more than 1 lakh times and not 5 lakh, and a reader pays about eight more lookups per read. A threshold of 1,000 followers saves 45 percent of writes and costs 33.9 lookups per read.
Choosing the threshold
The run shows there is no free setting. Lower thresholds mean fewer writes and more work at read time, and since reads outnumber posts about fifty to one, read cost counts for a lot. A sensible start is a threshold high enough to cap the burst, and then to adjust it using the measured read latency and the depth of the fan-out queue.
Read lookups are cheaper than they sound. The posts of a big account change slowly relative to how often they are read, so each big account keeps a short list of its latest posts in a cache shared by all its readers. A pull read does a few cache gets in parallel, merges, and returns. The cost is the merge and the extra latency of the slowest lookup, which is why the cost must be watched.
Three more rules reduce the work. Skip fan-out to inactive users, since their timelines are rebuilt when they return. Limit each cached timeline to a fixed length, so each write replaces an old id with a new one. And spread a huge fan-out across many workers by splitting the follower list into chunks, so one big post does not occupy one worker for minutes while ordinary posts wait behind it.
Pushing every post costs one insert per follower. What goes wrong for an account with 5 lakh followers?
- One post needs 5 lakh timeline writes, a burst that delays the posts behind it in the queue. The hybrid pulls such accounts instead.
From the run, what does a hybrid with a 1 lakh follower threshold change?
- It pulls 34 accounts, saves 11 percent of the daily writes and caps one post at 1 lakh copies. Readers do about eight more lookups.
Why skip fan-out for users who have not opened the app for a month?
- Nobody reads their timeline, so the writes are wasted. The timeline is built on demand when they come back.
Part 5 · Deep dive: search and trends
Searching posts
Search answers 'which posts mention this word or hashtag', newest first. It is a separate system from the timeline because its question is different: a timeline is a list per reader, while search is a lookup by content across all posts. The search chapter explains the structure in full, and here it is enough to name the parts.
Each post is split into tokens, and an inverted index maps each token to the list of post ids that contain it. A query for a token reads its list. A query for two tokens combines two lists. Because ids sort by time, each list is already in time order, so the newest matches come first, with no extra sorting. This is another gain from time-ordered ids.
Search has a freshness requirement of seconds, so the index has two tiers. A small in-memory tier takes the newest posts from the event stream and is searched first. A larger, older tier holds the rest in segments that are merged in the background. A query goes to both tiers and to every shard that holds posts, and the results are merged, a scatter-gather as in the search chapter.
Deletes need care. A deleted post must disappear from search quickly, so the search service receives a delete event and records a tombstone, a marker that hides the id until a later merge removes it. The timeline path does the same check when it hydrates ids into posts, and drops those that no longer exist.
Trending topics in a sliding window
A trend is a topic whose use rises faster than usual. The simplest building block counts hashtags over a recent sliding window, such as the last minute, and keeps the top few. Counting every hashtag over a moving minute is cheap if the window is cut into buckets: each post increments the current bucket, and when a bucket falls out of the window its counts are subtracted.
import heapq from collections import Counter, deque BUCKET_S, WINDOW_S = 10, 60 # ten-second buckets, a minute class Trends: def __init__(self): self.buckets = deque() # (start, Counter), oldest first self.total = Counter() # counts inside the window def add(self, ts, tag): start = ts - ts % BUCKET_S if not self.buckets or self.buckets[-1][0] != start: self.buckets.append((start, Counter())) self.buckets[-1][1][tag] += 1 self.total[tag] += 1 self._expire(ts) def _expire(self, now): while self.buckets and self.buckets[0][0] <= now - WINDOW_S: _, old = self.buckets.popleft() self.total.subtract(old) self.total += Counter() # drop zero and negative counts def top(self, k): return heapq.nlargest(k, self.total.items(), key=lambda kv: (kv[1], kv[0]))
Python 3.12.10. Save as trends.py: ten-second buckets in a one-minute window.
The class keeps a queue of buckets, oldest first, and a running total. top returns the k tags with the highest totals using a heap, so it does not sort all tags. The script below feeds in five simulated minutes at 20 posts a second. A new tag, #launch, takes 35 percent of posts from second 200.
import random from collections import Counter from trends import Trends rnd = random.Random(4) tags = ["#cricket", "#monsoon", "#exams", "#music", "#traffic"] tr, early = Trends(), Counter() for ts in range(0, 300): # 5 minutes, 20 posts a second for _ in range(20): tag = rnd.choices(tags, weights=[5, 4, 3, 2, 1])[0] if ts >= 200 and rnd.random() < 0.35: tag = "#launch" # a new topic bursts at 200 s tr.add(ts, tag) if ts < 200: early[tag] += 1 if ts in (190, 299): top3 = ", ".join(f"{t} {c}" for t, c in tr.top(3)) print(f"t = {ts:>3} s top 3: {top3}") # Growth: the window's count against what 60 s looked like before. usual = {t: max(1.0, early[t] * 60 / 200) for t in tr.total} growth = sorted(((c / usual[t], t) for t, c in tr.total.items()), reverse=True) print("by growth:", ", ".join(f"{t} {g:.1f}x" for g, t in growth[:3]))
Save as trends_run.py. Seeded random posts, so the output repeats.
Reading the result
At second 190 the window shows the steady favourites, #cricket, #monsoon and #exams, with counts near 338, 282 and 192. At second 299 the new tag leads with 430 and the old ones have fallen, as the window now holds mostly the burst. The counts are over a window of about a minute, so they do not add to 20 posts for every second exactly.
Counts alone favour tags that are always popular, which is why the last line of the output compares each count with what the tag did before. The ratio of #launch is 430 against a floor of one post, while the older tags are at 0.7 times their usual level. A real trends service ranks by growth over a baseline, with a minimum count so that three posts of a new word do not trend.
At full scale the counting is split. Posts are partitioned by hashtag across many counters, each keeping its own windows, and a combiner merges their top lists into a global one. A hot hashtag can overload one counter, so it is spread over several, as in the sharded counter chapter. Trends are also made per region and per language, which multiplies the number of windows kept.
Why is the window split into buckets?
- Expiring the oldest bucket subtracts its counts in one step. Without buckets every post would need to be tracked and removed one by one.
In the run, why does #launch lead at second 299 but not at second 190?
- It began at second 200, taking 35 percent of new posts. By 299 its count of 430 passes the older tags.
Why rank trends by growth and not by count?
- Always-popular tags have high counts all the time. Growth over a baseline finds what is new.
Part 6 · Caching timelines, failures and trade-offs
The timeline cache
The cache holds, for each active reader, a list of post ids, newest first, capped at a fixed length such as 800. A new post is added at the front and the oldest id falls off the end. A reader who scrolls beyond 800 posts is rare, and for them the service falls back to a slower path through the post store. The cap bounds the memory per user and the work per write.
The hybrid design means a read is a merge. The reader's cached ids are one sorted list, and each big account the reader follows contributes another sorted list of its latest posts. Merging sorted lists is a standard operation, and since every list is in descending id order, a k-way merge gives the combined timeline. The script below does this for three sources: a cached list of friends' posts and two big accounts.
import heapq import random rnd = random.Random(2) def posts(start, step, n): """Post ids for one author, newest first. Bigger id = newer.""" ids = [start + i * step + rnd.randint(0, 4) for i in range(n)] return sorted(ids, reverse=True) CACHE_CAP = 800 # ids kept per pushed timeline pushed = posts(7000, 8, 40)[:CACHE_CAP] # friends, filled on write star_a = posts(7150, 40, 6) # stars: read on demand star_b = posts(7200, 50, 4) def home(before=None, limit=8): streams = [[("friend", x) for x in pushed], [("star-a", x) for x in star_a], [("star-b", x) for x in star_b]] merged = heapq.merge(*streams, key=lambda s: s[1], reverse=True) rows = [s for s in merged if before is None or s[1] < before] return rows[:limit] page1 = home() for src, x in page1: print(f"{x} {src}") page2 = home(before=page1[-1][1], limit=3) print("next page after", page1[-1][1], "->", [x for _, x in page2])
Python 3.12.10. Ids are invented; a bigger id is a newer post.
7354 star-b 7353 star-a 7316 friend 7311 star-a 7305 friend 7302 star-b 7297 friend 7290 friend next page after 7290 -> [7281, 7274, 7272]
Output: the first page, then the cursor for the next.
The first page interleaves the three sources in id order, and the cursor is the last id on the page, 7290. The next page asks for ids below it and returns 7281, 7274 and 7272, with no overlap. This is the same cursor idea as in the API, and it works because the merge result is stable: a post is always in the same place relative to others.
Failures and what to do
The first failure is a slow fan-out. If the workers fall behind, timelines lag, and readers see old posts. The queue depth and the age of the oldest event are the signals to watch. The remedy is more workers, and, if a single huge post is the cause, splitting its follower list into chunks that run in parallel. Posts are never lost during the lag, because the post store holds them.
The second failure is a lost cache node. The timelines it held are gone. The service rebuilds a timeline on demand: a read that finds no cached list builds one by pulling recent posts from the accounts the reader follows, in the same way as a read of big accounts. This is expensive, so rebuilds are rate limited, and the cache is replicated for the most active users, as the cache chapter describes.
The third is deletes and blocks. Because timelines hold ids, a deleted post is dropped when the ids are turned into posts, and a blocked account's posts are filtered at the same point. That filtering happens at read time and does not need any change to the cached lists, which is the benefit of storing ids and not copies.
Trade-offs and extensions
The trade-offs are these. Push makes reads fast and writes costly. Pull does the opposite. The hybrid is a middle path whose threshold needs tuning. A short cache cap saves memory and makes deep scrolling slower. Time-ordered ids give cheap sorting, and they reveal roughly when a post was made, which is acceptable for posts. Eventual consistency lets the service stay fast and available, at the price of a few seconds before a post appears.
Extensions follow from the design. Replies are posts with a reply_to id, and a thread is a query over that column. Reposts and likes are counters, which the sharded counter chapter shows how to spread. A ranked 'for you' timeline adds a scoring step between the merge and the response, as a later chapter on ranked feeds describes. Media is stored as links to a blob store behind a CDN.
Why is the timeline cache capped at a fixed length?
- It bounds memory per user and keeps each write to one insert and one removal. A reader who scrolls past the cap uses a slower path.
In the merge run, why is the next page free of repeats?
- The cursor is the last id of the first page, and the next request asks only for ids below it.
What does a read do when the cache has lost a reader's timeline?
- It rebuilds one on demand by pulling recent posts from the accounts the reader follows, with rebuilds rate limited.
| Term | Meaning |
|---|---|
| Fan-out on write | Copy each new post into every follower's timeline when it is posted |
| Fan-out on read | Build the timeline when it is read, from the accounts followed |
| Hybrid |
All chapters · Previous: Design a Ride-Hailing Service like Uber