Courses / System Design Interview / Chapter 32
Module 7 · Design Problems II: Rides and Social Feeds · Chapter 32 of 49
Design a News Feed
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Non-Functional Requirements: Availability, Scale, Latency and More, Back-of-the-Envelope Estimates, Content Delivery Networks, Distributed Caches, Rate Limiters and Design a Microblogging Service like Twitter. Next up: Design a Photo-Sharing Service like Instagram.
Part 1 · Requirements and estimates
What the feed must do
A news feed is the first screen of most social apps: a ranked list of posts from the people, pages and groups you follow. This chapter designs that list, with the focus on how it is ranked, how you page through it and how it stays fresh.
The functional requirements are: show a viewer a list of posts from the accounts they follow, best first; let them scroll to older posts without seeing the same post twice; let them react to a post and see the reaction at once; and show posts that include a photo or a short video. Creating the post itself, advertising, notifications and search are out of scope, and so is the upload path for media, which the next chapter covers.
The non-functional requirements decide the design. A feed page must come back fast enough that scrolling feels immediate, so we set a target of about 300 milliseconds at the 99th percentile for the server side. The feed may be a few minutes behind the newest post, but it must never be empty: a slow ranking service should make the feed less personal, not unavailable. Availability matters more than strict freshness here, and no viewer should see a post twice in one scroll.
One question separates this chapter from the microblog chapter. That chapter was about getting posts into followers' timelines. Here we assume the candidate posts already exist for each viewer and ask a different question: given hundreds of candidate posts for one viewer, which twenty should come first, and how do we hand them over page by page?
| Question to ask | Answer we assume |
|---|---|
| How many people use it? | 15 crore opened it in the last 30 days, 10 crore each day |
| How often is the feed opened? | 6 times a day per active user |
| How far does a viewer scroll? | Three pages of 20 posts per open |
Traffic and storage
Estimates come first, as in the estimates chapter. The scene shows the storage estimate for the feeds we keep ready for viewers; the script after it also covers traffic and the cost of ranking.
Posts scored per second: ≈ 35 lakh (the cost a stored list avoids)
Read it as steps
Fifteen crore stored feeds fit in under a terabyte, but ranking on every open would not.
The scene keeps the feed as a list of ids and scores, not whole posts. A post is stored once, and every feed that includes it points to it. That is what keeps the total small. The bottom half of the scene is the opposite: scoring 500 candidates on every open is a very large number, which the rest of the chapter works to avoid.
The estimate as code
The next script puts all the assumptions in one place so that you can change any of them and see the effect. It uses Python's digit grouping, so 10_00_00_000 reads as 10 crore.
# Every number below is an assumption of ours, stated so it can change. daily_users = 10_00_00_000 # 10 crore people open the app each day active_users = 15_00_00_000 # 15 crore, active in the last 30 days opens_per_day = 6 pages_per_open = 3 # first page plus two scrolls page_size = 20 # posts per page peak_factor = 3 # busiest second against the average day = 86_400 opens = daily_users * opens_per_day page_reqs = opens * pages_per_open print(f"opens per day {opens:>16,}") print(f"page requests/day {page_reqs:>16,}") print(f"page requests/s avg {page_reqs / day:>16,.0f}") print(f"page requests/s peak {page_reqs / day * peak_factor:>16,.0f}")
Python 3.12.10. Save this and the next block together as feed_estimate.py.
# A stored feed is a list of (post id, score) pairs per user. kept = 500 # entries kept per user entry = 8 + 4 # 8-byte post id, 4-byte score per_user = kept * entry total = active_users * per_user print(f"bytes per user feed {per_user:>16,}") print(f"all feeds {total / 1e12:>13.2f} TB") print(f"with 3 replicas {total * 3 / 1e12:>13.2f} TB") # Ranking cost if every open scored 500 fresh candidates. candidates = 500 scored_per_day = opens * candidates print(f"posts scored/day {scored_per_day:>16,}") print(f"posts scored/s avg {scored_per_day / day:>16,.0f}")
Continue in the same file.
opens per day 600,000,000 page requests/day 1,800,000,000 page requests/s avg 20,833 page requests/s peak 62,500 bytes per user feed 6,000 all feeds 0.90 TB with 3 replicas 2.70 TB posts scored/day 300,000,000,000 posts scored/s avg 3,472,222
Output of the script.
Reading the numbers
Traffic first. Six opens a day from 10 crore people is 60 crore opens, and with three pages per open that is 180 crore page requests a day, about 20,800 a second on average and 62,500 at the busiest second if we plan for three times the average. That is a lot of requests, but each one is cheap if the feed is already built.
The last two lines show why we cannot build it fresh each time. If every open scored 500 candidates, the ranking service would score about 35 lakh posts a second on average. Meta's 2021 post on its feed ranking says its systems score more than 1,000 posts per user per day, so the order of magnitude is real, and the post describes a cheap first pass that narrows the candidates to about 500 before the main scoring. Our 500 is our own assumption, not a figure from that post. The design therefore has to build a ranked list once, store it for a few minutes and serve pages from it.
Storage is the easy part. A feed of 500 entries is 6,000 bytes, all feeds are 0.9 TB and three replicas are 2.7 TB. The posts themselves, with captions and media references, are far larger but are stored once, not once per feed.
Why does each stored feed keep post ids and scores, not copies of the posts?
- A post is read by many feeds. Storing it once and pointing to it keeps the total small and means an edit or a delete is applied in one place.
Using the output, how many page requests a second must the feed service plan for at the busiest second?
- About 62,500: the average of 20,833 a second multiplied by the peak factor of 3.
What is the main cost that makes building a fresh ranked feed on every open unaffordable?
- Scoring. Ranking 500 candidates on each of 60 crore opens a day is 34.7 lakh scored posts a second on average in the run, so the ranked list is built once and reused.
Part 2 · API and data model
The feed API
The client needs very little: a way to ask for a page of the feed, a way to continue from where it stopped, and a way to react to a post. We shape the page response like a GraphQL connection, the pattern the Relay specification describes: a list of edges, each holding a node (the post) and a cursor, and a pageInfo object that says whether more pages exist and gives the endCursor to send back. We borrow the shape, not the protocol; the same fields work in a plain JSON API.
GET /v1/feed?first=20 HTTP/1.1 Authorization: Bearer <token> GET /v1/feed?first=20&after=WzAuNjcsIDEwM10= HTTP/1.1 Authorization: Bearer <token>
Ask for the first page, then the next one.
{
"edges": [
{"cursor": "WzAuODgsIDEwMl0=",
"node": {"id": "102", "author": "Chitra", "body": "New bike",
"media": "img/102.jpg", "reactions": 31}},
{"cursor": "WzAuNjcsIDEwM10=",
"node": {"id": "103", "author": "Bharat", "body": "Match tonight",
"media": null, "reactions": 12}}
],
"pageInfo": {"hasNextPage": true, "endCursor": "WzAuNjcsIDEwM10="}
}A page. The cursor is opaque to the client.
The client must treat a cursor as an opaque string and send it back unchanged. Clients treat it as opaque, which frees the server to change how a cursor is built without breaking any app already installed on a phone. The pagination lesson builds the cursor.
| Call | What it does | Notes |
|---|---|---|
GET /v1/feed?first=20&after=<cursor> | One page of ranked posts | first capped at 50; no after means the first page |
PUT /v1/posts/{id}/reaction | Set or change the viewer's reaction | Idempotent: sending it twice changes nothing |
DELETE /v1/posts/{id}/reaction | Remove it |
Tables
Four tables carry the feed. post holds what an author wrote and a key for any media, not the media bytes. follow records who follows whom. feed_item is the stored feed: one row per viewer and post, with the score from the last ranking. reaction has one row per viewer and post, so a viewer cannot like the same post twice.
import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE user (id INTEGER PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE follow ( follower INTEGER NOT NULL REFERENCES user(id), author INTEGER NOT NULL REFERENCES user(id), PRIMARY KEY (follower, author)); CREATE TABLE post ( id INTEGER PRIMARY KEY, -- time-ordered id author INTEGER NOT NULL REFERENCES user(id), body TEXT NOT NULL, media_key TEXT, -- object store key, not the bytes created_at INTEGER NOT NULL); CREATE TABLE feed_item ( -- the precomputed feed viewer INTEGER NOT NULL, post_id INTEGER NOT NULL, score REAL NOT NULL, PRIMARY KEY (viewer, post_id)); CREATE INDEX feed_by_score ON feed_item (viewer, score DESC, post_id DESC); CREATE TABLE reaction ( post_id INTEGER NOT NULL, viewer INTEGER NOT NULL, kind TEXT NOT NULL, PRIMARY KEY (post_id, viewer)); """)
Python 3.12.10 with its built-in sqlite3. Save this and the next block as feed_schema.py.
db.executemany("INSERT INTO user VALUES (?, ?)", [(1, "Asha"), (2, "Bharat"), (3, "Chitra")]) db.executemany("INSERT INTO follow VALUES (?, ?)", [(1, 2), (1, 3)]) db.executemany("INSERT INTO post VALUES (?, ?, ?, ?, ?)", [ (101, 2, "Chai at the station", None, 1000), (102, 3, "New bike", "img/102.jpg", 1060), (103, 2, "Match tonight", None, 1120)]) db.executemany("INSERT INTO feed_item VALUES (1, ?, ?)", [(101, 0.41), (102, 0.88), (103, 0.67)]) page = db.execute(""" SELECT p.id, u.name, p.body, f.score FROM feed_item f JOIN post p ON p.id = f.post_id JOIN user u ON u.id = p.author WHERE f.viewer = 1 ORDER BY f.score DESC, p.id DESC LIMIT 2""").fetchall() for row in page: print(row) print(db.execute("EXPLAIN QUERY PLAN SELECT post_id FROM feed_item" " WHERE viewer = 1 ORDER BY score DESC, post_id DESC" " LIMIT 2").fetchall()[0][3])
Continue in the same file: three posts, then page one of the feed.
(102, 'Chitra', 'New bike', 0.88) (103, 'Bharat', 'Match tonight', 0.67) SEARCH feed_item USING COVERING INDEX feed_by_score (viewer=?)
Output of the script.
The query joins feed_item to post and user to build a page. At scale you would not join across machines. You would read the ids from the feed store and then fetch the posts in one batched request, the fix for the N+1 pattern from the non-functional chapter: one request for twenty posts, not twenty requests for one each. The join above is the same idea on one database.
Part 3 · High-level design: feed generation, feed cache and ranking
Three stages
A feed request goes through three stages, and each one has a different cost. Candidate generation collects the posts that could be shown: recent posts from accounts the viewer follows, plus anything the system wants to consider. Ranking scores those candidates and orders them. Serving returns one page from the ordered list, fetching the full posts and their counts for display.
Candidate generation is the work of the microblog chapter: whichever way the posts reach the viewer, the output is a few hundred post ids, and this chapter starts from that list.
Ranking is the expensive stage. Meta's post on feed ranking describes it in passes: a lightweight first pass that selects about 500 of the most relevant posts, a main pass that scores each of those on its own, and a last contextual pass that applies rules such as variety in the type of content. We use the same shape with our own parts. A cheap score removes most candidates, the main scorer orders the rest, and a final pass adjusts the order, for example so that one author does not fill a whole screen.
Serving is cheap by design. The ranked list for a viewer is written to a feed cache with a lifetime of a few minutes. Every page request in that time reads its slice from the cache, so only the first open of a session pays for ranking. When the lifetime ends, or the viewer pulls to refresh, the next request rebuilds the list.
Watch for the first open reaching the ranker and the next page skipping it
Read it as steps
Where each part lives
The Feed API is stateless, so any number of copies can sit behind a load balancer. The feed cache is a distributed cache of the kind in the cache chapter, sharded by viewer id, so one viewer's list lives on one node and a page request needs one lookup. The ranking service is a pool of workers that read candidates and features, score them and write the ordered list. The post store is the database of posts and counts, read by id.
| Part | Scales by | If it fails |
|---|---|---|
| Feed API | Adding stateless servers | The load balancer sends traffic to the others |
| Feed cache | Sharding by viewer id | Rebuild lists on demand; expect a burst of ranking work |
| Ranking service | Adding workers | Serve the last stored list, or a plain recent-posts list |
| Post store | Replicas for reads, partitions for size | Serve cached posts; show older counts |
Two details deserve a sentence each. The cached list is per viewer, so the cache holds one entry for each active viewer, not one for each post; that is the 0.9 TB figure from the first lesson. And the post counts shown on a page, such as reactions, are read separately from the list, so they can be fresher than the ranking, which is only recomputed every few minutes.
When the cached list expires, a rush of viewers who opened the app at the same minute, say at the start of a match, could all miss together and send their ranking work at once. The cache chapter called this a stampede. The same defences apply: let one request rebuild while others wait, and let the old list be served while the new one is built.
Why is ranking done once per list and not once per page?
Part 4 · Deep dive: ranking
What a score combines
A ranking score puts one number on each candidate so the list can be sorted. Most feeds blend a few families of signals. Affinity is how close the viewer is to the author, measured by past reactions, messages and profile visits. Engagement is how other people responded to the post, such as likes and comments. Recency is how old the post is. Content type and the viewer's habits, for example whether they tend to watch videos, adjust the result.
A hand-written formula shows how they interact. Recency should fade smoothly, not cut off at a deadline, so we use exponential decay with a half-life: after one half-life a post counts half as much, after two a quarter. Engagement should help a post without letting a viral one bury everything, so we take a logarithm of the weighted count. Affinity multiplies the result, so a post from someone close beats an equally popular post from a stranger.
Meta's post on feed ranking says its systems use neural networks that predict how likely a viewer is to engage with a post, such as liking it. A learned model replaces our formula in a real system. Everything around the formula stays: candidates in, scores out, a sorted list stored for serving.
import math, random def make_posts(n=30, seed=7): rnd = random.Random(seed) posts = [] for i in range(n): posts.append({ "id": i + 1, "author": rnd.choice("ABCDEF"), "age_h": round(rnd.uniform(0.2, 36), 1), # hours old "likes": int(rnd.expovariate(1 / 40)), "comments": int(rnd.expovariate(1 / 6)), "affinity": round(rnd.uniform(0.1, 1.0), 2), # closeness }) return posts def score(p, half_life_h=6.0, comment_weight=3.0): decay = 0.5 ** (p["age_h"] / half_life_h) engagement = math.log1p(p["likes"] + comment_weight * p["comments"]) return p["affinity"] * (1 + engagement) * decay
Python 3.12.10. Save this and the next two blocks together as ranking.py. Thirty made-up posts and the score.
make_posts builds thirty posts with a fixed seed so that the run repeats. Each has an age in hours, likes, comments and an affinity between 0.1 and 1. The score function is the whole idea: affinity times one plus the log of weighted engagement, times the decay. Comments count three times a like because they take more effort, a weight we chose and you can change.
Tuning and the final pass
Every constant in the formula is a choice. The half-life says how much the viewer cares about freshness. A short one gives a feed that behaves like a timeline, and a long one lets a good older post stay near the top. The next block sweeps it.
for hl in (2, 6, 24): top = sorted(posts, key=lambda p: score(p, hl), reverse=True)[:10] ages = sorted(p["age_h"] for p in top) print(f"half-life {hl:>2}h: oldest in top 10 is {ages[-1]}h," f" median {ages[4]}h") def spread(items): """Greedy pass: do not show the same author twice in a row.""" out, rest = [], list(items) while rest: pick = next((p for p in rest if not out or p["author"] != out[-1]["author"]), rest[0]) rest.remove(pick) out.append(pick) return out def repeats(items): return sum(a["author"] == b["author"] for a, b in zip(items, items[1:])) print("same-author neighbours, ranked:", repeats(ranked)) print("same-author neighbours, spread:", repeats(spread(ranked)))
Continue in the same file: sweep the half-life, then spread authors.
half-life 2h: oldest in top 10 is 12.4h, median 4.4h half-life 6h: oldest in top 10 is 15.2h, median 4.4h half-life 24h: oldest in top 10 is 32.4h, median 6.7h same-author neighbours, ranked: 4 same-author neighbours, spread: 1
Output of the last block.
With a half-life of 2 hours the oldest post in the top ten is 12.4 hours old, and with 24 hours it is 32.4. The median age of the top ten moves from 4.4 to 6.7 hours. A product team would not pick the number by looking at ten posts. It would try values on a small share of real viewers and watch time spent and how often people come back, which is an online experiment. We do not run one here, and the numbers above come only from our made-up data.
The last pass is the contextual one. Scoring each post alone can put four posts from the same author in a row. The spread function walks the sorted list and takes the best post whose author differs from the one just placed. It cut same-author neighbours among thirty posts from 4 to 1 in the run.
Two cautions about any scoring formula. First, engagement can reward the wrong things: a post that makes people angry gets many comments. Production systems add signals for quality and for what viewers say they want, and they remove or demote content that breaks rules. Second, features must be available fast. A formula that needs data fetched from five services for every one of 500 candidates will not meet a 300 ms target, so the features are precomputed and stored next to each post.
Part 5 · Deep dive: pagination
Why offsets break
A feed is a list that keeps changing while someone reads it. Offset pagination asks for the next page by skipping a count of rows, LIMIT 4 OFFSET 4. It is easy to write, and it fails the moment something is inserted above the position the viewer has reached. The rows shift down, and the next page repeats posts the viewer has already seen.
Keyset pagination, also called cursor or seek pagination, avoids the problem. The client sends back the sort key of the last item it saw, and the server returns the items that come after that key. Inserts above the cursor do not move the position, because the position is a value, not a count. The sort key must be unique, so we use the score and the post id together; two posts with the same score are then ordered by id.
import base64, json, sqlite3 db = sqlite3.connect(":memory:") db.execute("CREATE TABLE feed (post_id INTEGER PRIMARY KEY," " score REAL NOT NULL)") db.execute("CREATE INDEX feed_rank ON feed (score DESC, post_id DESC)") db.executemany("INSERT INTO feed VALUES (?, ?)", [(i, round(i / 10, 1)) for i in range(1, 13)]) def page_offset(offset, size=4): q = "SELECT post_id FROM feed ORDER BY score DESC, post_id DESC" return [r[0] for r in db.execute(q + " LIMIT ? OFFSET ?", (size, offset))] def encode(score, post_id): raw = json.dumps([score, post_id]).encode() return base64.urlsafe_b64encode(raw).decode() def page_keyset(after=None, size=4): """Returns (post ids, cursor for the next page).""" q = "SELECT post_id, score FROM feed" args = [] if after: s, i = json.loads(base64.urlsafe_b64decode(after)) q += " WHERE (score, post_id) < (?, ?)" args = [s, i] q += " ORDER BY score DESC, post_id DESC LIMIT ?" rows = db.execute(q, args + [size]).fetchall() return [r[0] for r in rows], encode(rows[-1][1], rows[-1][0])
Python 3.12.10 with sqlite3. Save this and the next block as paging.py. Twelve posts and both kinds of page.
page_offset is the simple version. page_keyset takes a cursor, decodes it to a score and a post id and uses the row-value comparison (score, post_id) < (?, ?), which SQLite supports. It returns the ids and the cursor for the next page. The cursor is the score and id as JSON, encoded in base64 so that it looks like a meaningless string to the client.
def arrive(): """Three new high-scoring posts land between two page requests.""" db.executemany("INSERT INTO feed VALUES (?, ?)", [(100, 2.0), (101, 1.9), (102, 1.8)]) def reset(): db.execute("DELETE FROM feed WHERE post_id >= 100") def dupes(a, b): return sorted(set(a) & set(b)) first = page_offset(0) arrive() second = page_offset(4) print("offset page 1:", first) print("offset page 2:", second, "repeats:", dupes(first, second)) reset() first, cursor = page_keyset() arrive() second, cursor = page_keyset(cursor) print("keyset page 1:", first) print("keyset page 2:", second, "repeats:", dupes(first, second)) print("cursor handed to the client:", cursor)
Continue in the same file: three high-scoring posts arrive between the pages.
Building the cursor well
The new posts did not appear on page two in the keyset run, and that is right. They sit above the cursor, in a part of the list the viewer has passed. They show up when the viewer pulls to refresh, which asks for a new list from the top. This is the behaviour people expect from a feed: the scroll stays steady, and the new posts wait for a refresh.
A cursor needs three properties. It must be unique, which is why the post id breaks ties. It must be opaque, so the client does not build one itself and the server can change its format. The Relay connection specification says clients should treat the cursor as opaque. And it must be stable: it has to mean the same position until the list is rebuilt. In a feed ranked by a score that can change, a cursor that holds the score is only stable if the scores in the stored list are frozen. Our design stores the ranked list in the feed cache, so the scores are fixed until the list is rebuilt; a cursor from the old list is then rejected or restarts at the top.
Offset against keyset
| Property | Offset | Keyset with a stored list |
|---|---|---|
| Repeats a post when new posts arrive above | Yes | No |
| Skips a post when posts are removed above | Yes | No |
| Cost of page 50 | The database walks past about 1,000 rows | One index seek |
| Jump to page 50 directly | Yes | No, only next and previous |
| Needs a unique sort key | No | Yes |
Keyset pagination gives up random access, but a feed does not need it: nobody jumps to page 50 of their feed. Deep pages are also cheaper. Offset has to walk past every skipped row, while a keyset query seeks to the cursor in the index and reads a page from there.
A few rules finish the design. Cap the page size, so a client cannot ask for ten thousand posts in one call. Return hasNextPage so the client knows when to stop. Treat a cursor that fails to decode as a bad request and not a server error. And if the cursor is something a viewer could tamper with, sign it or keep it meaningless, so no one can use it to read the sort keys of other people's items.
In the run, which posts did the offset version repeat on page two?
- Posts 9, 10 and 11, which the viewer had already seen on page one, because three new posts pushed everything down by three.
Why are the new posts missing from the keyset page two, and is that a bug?
- They sit above the cursor. It is the intended behaviour: they appear when the viewer refreshes and the list is rebuilt from the top.
Part 6 · Freshness, media and failures
Staying fresh without rebuilding
A feed cached for a few minutes is stale by design. Three small mechanisms keep it from feeling stale. First, pull to refresh asks for a new list on demand, and the cost is limited by a rate limit per viewer, as in the rate limiter chapter. Second, the app can show a small count of new posts since the list was built, which is a cheap query for the number of followed authors' posts newer than the list's timestamp, and lets the viewer decide when to refresh. Third, the list's lifetime can differ by viewer: someone who opens the app every hour can have a longer lifetime than someone who is scrolling now.
Seen suppression is the other half of freshness. A viewer who opened the feed an hour ago should not get the same top posts again. The client reports which posts were shown, a stored set of recent post ids is kept for each viewer, and the ranker removes those from the candidates. The set only needs the last day or two of ids, which is small.
Media is a reference, not a payload. Each post carries a media key, and the client gets an address for a picture or video that a CDN serves, as in the cdn chapter. The feed response never contains image bytes. The server may also send which sizes exist, so the phone can ask for a small rendition on a slow network. How those sizes are produced is the subject of the next chapter.
The run for this lesson shows the most important failure rule. The ranking service gets a deadline of 150 milliseconds. If it answers in time, the viewer gets a fresh page. If not, the Feed API returns the last stored list for that viewer, and removes the posts they have already seen.
import asyncio, time STORED = ["p12", "p11", "p10", "p9"] # last saved list SEEN = {"p11"} # already shown async def ranker(delay): """Stand-in for the ranking service, slow by `delay` seconds.""" await asyncio.sleep(delay) return ["p14", "p13", "p12", "p11"] async def get_feed(delay, deadline=0.15): t0 = time.perf_counter() try: page = await asyncio.wait_for(ranker(delay), deadline) source = "fresh" except asyncio.TimeoutError: page, source = STORED, "stored" page = [p for p in page if p not in SEEN] ms = (time.perf_counter() - t0) * 1000 return source, page, ms async def main(): for delay in (0.02, 0.5): source, page, ms = await get_feed(delay) print(f"ranker {delay * 1000:>3.0f} ms: {source:<6} {page}" f" in {ms:.0f} ms") asyncio.run(main())
Python 3.12.10, standard library only. Save as deadline.py.
Failures and trade-offs
List the parts and say what each failure does. If the feed cache loses a node, those viewers' lists are rebuilt on their next open. The rebuild work arrives in a burst, so ranking needs headroom or a limit on how many lists it rebuilds at once. If the ranking service is down, serve the stored list; if there is none, fall back to the newest posts from followed accounts, a simple query on the post store that needs no model. If the post store is slow, serve counts from cache and show older numbers.
| Choice | What we picked | What it costs |
|---|---|---|
| Rank once per list, not per page | Lists stored for minutes | New posts wait for a refresh |
| Cursor over offset | Keyset with a stored list | No jumping to page 50 |
| Fallback to a stored list | Deadline of 150 ms | A less fresh order during trouble |
| Features precomputed | Stored beside each post | Features can lag the post's live counts |
Extensions follow the same structure. A Following tab that shows posts in time order needs no ranker, only the candidate query and a cursor on time and id. Ads are inserted after ranking, at fixed positions, by a separate system with its own budget and rules. Notifications about popular posts reuse the candidate generator with a threshold on score. Each extension adds a stage or a tab without changing the stored-list idea.
Finally, keep an eye on the feed's health. Useful measurements are the page latency at the 99th percentile, the share of requests served by the fallback, the age of the lists being served, and the rebuild rate of the cache. The fallback share is the early warning: if it rises, the ranker is in trouble before viewers say so.
All chapters · Previous: Design a Microblogging Service like Twitter