Sub topic 8
Ranking the Candidate Feed
This chapter assumes you know how fan-out on write and fan-out on read produce a list of post references per user. It also assumes you know what a bounded feed cache is, and that you can read short Python and SQL snippets. Here we add a ranking stage on top of that list.
Why ranking is a separate stage
Earlier chapters produced a candidate feed: a bounded list of (timestamp, post_id) pairs, newest first. Showing it as is gives a reverse-chronological feed. That is simple, predictable and cheap, but it has well-known problems:
- A user who follows many accounts sees noisy posts from frequent posters bury rare, important ones.
- Posts published while the user was offline sink below the first page.
- Nothing in the list reflects what the user actually cares about.
Ranking reorders the candidates by an estimate of how useful each one is to this user right now. The key design point is that ranking is a read-time stage layered on the candidate feed. It does not replace fan-out. Fan-out decides which posts are eligible. Ranking decides the order.
| Question | Answered by |
|---|---|
| Which posts could this user see? | Fan-out and the feed cache (candidate generation) |
| In what order should they appear? | Ranking |
| Which posts must be hidden? | Filtering (blocks, deletes, privacy) |
The pipeline: candidates, features, score, filter
A typical ranking pipeline has four steps.
- Candidate generation. Read the precomputed timeline from the feed cache. Merge in recent posts from high-follower accounts, as in the hybrid design. Take a few hundred candidates, not the whole timeline.
- Feature fetching. For each candidate, load the signals the scorer needs.
- Scoring. Compute one number per candidate.
- Filtering and re-ordering. Remove ineligible posts, sort by score, apply diversity rules, and return a page.
Keeping the candidate list small matters. Scoring cost grows with the number of candidates, and the request has a latency budget. A common budget is a few hundred milliseconds for the entire feed request, so feature fetching and scoring often get a fraction of that.
What goes into a score
Features fall into a few groups.
| Group | Examples | Where it usually lives |
|---|---|---|
| Post | Age, media type, length, language | Post store or post cache |
| Engagement | Likes, comments, shares so far, click-through rate | Counters in a key-value store, updated asynchronously |
| Author | Follower count, posting frequency, account quality | Profile store |
| Relationship | How often the viewer interacts with this author, mutual follows | Precomputed affinity table |
| Viewer | Recent activity, time of day, device | Session or user store |
Engagement counters change constantly, so ranking reads them from a fast store and accepts that they may lag by seconds. Relationship affinity is expensive to compute, so it is usually produced by a batch or streaming job and stored per (viewer, author) pair.
Starting simple: a hand-built score
Before using a machine-learning model, many systems start with a formula. A common shape combines affinity, engagement and a time decay, so older posts fade.
import math
import time
HALF_LIFE_HOURS = 6.0
def score(post, affinity, now=None):
"""Heuristic score: affinity * engagement * freshness decay.
post: dict with 'created_at' (epoch seconds), 'likes', 'comments'
affinity: float in [0, 1], how much the viewer cares about the author
"""
now = now if now is not None else time.time()
age_hours = max(0.0, (now - post["created_at"]) / 3600.0)
decay = 0.5 ** (age_hours / HALF_LIFE_HOURS)
# log1p dampens runaway counts so one viral post does not dominate
engagement = math.log1p(post["likes"] + 3 * post["comments"])
return (0.2 + affinity) * (1.0 + engagement) * decay
def rank(candidates, affinities, now=None, limit=20):
"""candidates: list of post dicts. affinities: author_id -> float."""
scored = [
(score(p, affinities.get(p["author_id"], 0.0), now), p["post_id"])
for p in candidates
]
scored.sort(reverse=True)
return scored[:limit]
if __name__ == "__main__":
now = 1_000_000.0
posts = [
{"post_id": "a", "author_id": "u1", "created_at": now - 3600, "likes": 5, "comments": 0},
{"post_id": "b", "author_id": "u2", "created_at": now - 7200, "likes": 200, "comments": 40},
{"post_id": "c", "author_id": "u3", "created_at": now - 86400, "likes": 900, "comments": 100},
]
print(rank(posts, {"u1": 0.9, "u2": 0.3, "u3": 0.1}, now=now))Three details in this formula are worth copying even if you replace it later:
- Decay. A half-life makes the score halve every fixed period, so a day-old post needs far more engagement to outrank a fresh one.
- Dampened counts.
log1pstops a post with 100,000 likes from scoring 100,000 times higher than one with 1 like. - An affinity floor. The
0.2 +term means a post from an unfamiliar author still has a chance to appear.
Moving to a learned model
A formula has weights chosen by hand. A learned ranker fits them from data. The usual setup predicts the probability that the viewer will take an action on the post (click, like, comment, dwell for a few seconds). Several predictions are then combined:
final_score = w_like * P(like) + w_comment * P(comment) + w_hide * P(hide)
The weight for negative actions such as hide or report is negative. Product teams tune these weights, because they encode what the product values.
Training data comes from impression logs: each time a post was shown, what features did it have and what did the user do? Two points often cause trouble:
- Position bias. Posts near the top get more clicks because they are at the top. If you train on raw clicks, the model learns to favor whatever was already ranked high. Log the position and either include it as a training feature (and set it to a constant at serving time) or correct for it in the loss.
- Training/serving skew. If a feature is computed one way offline and another way online, the model degrades silently. Log the features that were actually used at serving time and train on those logs.
Two-stage ranking for large candidate sets
If candidates number in the thousands, running a heavy model on all of them is too slow. Systems split ranking into two passes.
| Stage | Candidates in | Model | Goal |
|---|---|---|---|
| Light ranker | 1000s | Cheap formula or small model, few features | Cut to the best 100–200 |
| Heavy ranker | 100–200 | Larger model, many features | Produce the final order |
The light stage uses only features that are cheap to load, such as those stored alongside the post reference in the cache. The heavy stage can afford per-author and per-viewer lookups.
Pagination changes when you rank
Cursor pagination from the earlier chapter relied on (created_at, post_id) being a stable total order. A score is not stable. Engagement counts change and time decay moves every post's score, so a post might be on page 1 now and on page 2 a minute later, or appear twice.
There are three common fixes.
- Snapshot the ranked list. On the first request, rank and store the ordered list of post IDs in a short-lived cache entry (for example 10 to 30 minutes). Pages are slices of that snapshot, and the cursor holds a snapshot ID and an offset. Pages are consistent, but a refresh is needed to see new posts.
- Rank within a stable window. Use the chronological cursor to choose a window of candidates (for example the next 200 posts older than the cursor), rank only that window, and return its best page. This keeps cursor semantics but ranking is local to the window.
- Carry a seen-set. The cursor includes a compact set of IDs already shown, and later pages exclude them. This grows with depth, so it is used with a cap.
The snapshot approach is the most common. Its cost is extra cache storage and a rule for what happens when the snapshot expires. The usual rule is to rebuild it and accept a small amount of reordering.
Filtering and diversity
Ranking by score alone creates visible flaws, so a post-scoring step adjusts the list.
- Hard filters. Drop posts the viewer has blocked, muted, already seen, or that were deleted. This step must run at read time, even though the timeline was built at write time, because those states change after fan-out. A later chapter covers deletes and blocks in detail.
- Author diversity. Without a rule, one prolific author can fill the first page. A common fix is to penalize each additional post from the same author within the page, for example multiplying its score by 0.7 for each earlier post by that author.
- Format diversity. Avoid showing ten videos in a row by applying a similar penalty on media type.
- Exploration. Reserve a few slots for posts the model is uncertain about, so it keeps collecting data on new authors and topics. Without this, the model only reinforces what it already knows.
def diversify(scored, author_of, penalty=0.7):
"""Greedy re-rank: each repeat of an author is down-weighted.
scored: list of (score, post_id) sorted by score descending.
author_of: post_id -> author_id
"""
remaining = list(scored)
result = []
seen = {}
while remaining:
adjusted = [
(s * (penalty ** seen.get(author_of[pid], 0)), s, pid)
for s, pid in remaining
]
adjusted.sort(reverse=True)
_, original, pid = adjusted[0]
result.append((original, pid))
remaining.remove((original, pid))
author = author_of[pid]
seen[author] = seen.get(author, 0) + 1
return resultThis loop is quadratic in the candidate count, which is fine for a few hundred candidates and too slow for thousands. That is another reason to keep the candidate list short.
Failure handling and fallbacks
The ranker is a dependency that can fail or slow down. A feed that returns an error because the feature store is down is worse than one that is merely less personalized.
- Timeouts per stage. Give feature fetching a hard deadline. If some features are missing, score with defaults for those features.
- Fallback order. If scoring fails entirely, return the candidates in reverse-chronological order. This is exactly what the candidate feed already is, so the fallback costs nothing extra.
- Cache the result. Because the snapshot approach stores a ranked list, a repeat request within the window skips scoring altogether.
- Observe it. Track the fraction of requests served from the fallback. A rising rate is an early signal of a feature-store problem.
Measuring whether ranking helps
A ranked feed is only better if it moves a metric you care about. Compare it against the chronological feed in an A/B test.
- Engagement metrics: clicks, likes, comments, session length.
- Guardrail metrics: hides, reports, unfollows, latency, and the number of users who stop opening the app.
- Long-term metrics: retention after weeks, because a feed that maximizes clicks can reduce satisfaction.
Offline metrics, such as how well predicted probabilities match logged outcomes, are useful for choosing models, but they do not replace an online test.
Summary of trade-offs
| Decision | Option A | Option B | Consider |
|---|---|---|---|
| Scoring | Heuristic formula | Learned model | Start with a formula; move when you have impression logs |
| Candidate count | Small (about 200) | Large (1000s) | Larger sets raise quality and latency together |
| Pagination | Snapshot of ranked list | Windowed ranking | Snapshots give consistent pages; windows keep cursors simple |
| Freshness of features | Real-time counters | Batch-updated | Real-time costs more infrastructure for small gains |
| Failure | Return error | Fall back to chronological | Almost always fall back |
Exercise
A ranked feed uses OFFSET-style paging, and users report seeing the same post on page 1 and page 2. Name the cause and give two ways to fix it.
Show answer
The score is recomputed on each request. Engagement counts change and time decay shifts every post's score, so the order differs between page requests and a post can move across the page boundary. Fixes: (1) rank once, store the ordered post IDs as a short-lived snapshot, and have the cursor hold a snapshot ID and offset; (2) rank only a stable window of candidates chosen by the chronological cursor; or (3) carry a capped set of already-seen IDs in the cursor and exclude them from later pages.
Exercise
Your feature store becomes slow, and feed requests start timing out. Describe how the ranking stage should behave and which metric you would watch.
Show answer
Give feature fetching a hard deadline and score with default values for any features that did not arrive. If scoring still fails, return the candidate list in reverse-chronological order, which the fan-out stage already produced. Track the fallback rate (the fraction of requests served without ranking), along with feature-fetch latency, because a rising fallback rate signals the feature store problem early.
Exercise
In the heuristic score function, why is math.log1p applied to the engagement count instead of using the raw count?
Show answer
Raw counts grow without bound, so a viral post with 100,000 likes would score about 100,000 times higher than a post with 1 like and always dominate the feed. log1p compresses large values, so engagement still raises the score but with diminishing returns, and affinity and freshness keep a meaningful influence.