Sub topic 8
Ranking the Candidate Feed
This chapter assumes you know how fan-out on write builds a bounded timeline of (timestamp, post_id) references, and that you can read short Python snippets. The chapter shows how a ranking stage can sit on top of that timeline without changing how it is stored.
Why rank at all
A reverse-chronological feed is simple and predictable. It also buries good posts. A user who follows 500 accounts may open the app after eight hours and see a wall of low-value items first.
Ranking reorders a set of candidate posts by predicted usefulness to one user. The candidate feed is the set of posts that fan-out has already gathered for that user. Ranking does not replace fan-out. It runs after it.
The pipeline: candidates, features, score, order
Ranking splits into stages, each with a different cost.
- Candidate generation. Read the user's pushed timeline, then merge in pulled posts from high-follower accounts (the hybrid read from the previous chapters). Fetch a few hundred candidates, not the whole feed.
- Hydration. Look up post content and metadata for each
post_id. The timeline stores only references, so this step loads author, age, media type, and engagement counts. - Scoring. Compute a score for each candidate for this user.
- Re-ordering and filtering. Sort by score, remove duplicates, and apply rules such as "no more than two posts in a row from one author".
Candidate generation is deliberately cheap and broad. Scoring is expensive and narrow. Keeping the candidate set to a few hundred items is what keeps scoring within a latency budget of tens of milliseconds.
A simple scoring function
Production systems often use a trained model. A hand-written score is a good starting point and a useful baseline to compare against.
A common baseline combines three signals:
- Recency. Newer posts score higher, with the value decaying over time.
- Affinity. How much this user interacts with this author (likes, replies, profile visits).
- Engagement. How much other users have reacted to the post.
import math
import time
HALF_LIFE_HOURS = 6.0
def score(post, affinity, now=None):
"""Return a ranking score. Higher is better.
post: dict with 'created_at' (unix seconds), 'likes', 'comments'
affinity: float in [0, 1] for the viewer/author pair
"""
now = now if now is not None else time.time()
age_hours = max(0.0, (now - post["created_at"]) / 3600)
recency = 0.5 ** (age_hours / HALF_LIFE_HOURS)
engagement = math.log1p(post["likes"] + 2 * post["comments"])
return recency * (1.0 + 2.0 * affinity) * (1.0 + engagement)
def rank(candidates, affinities, limit=20, now=None):
scored = [
(score(p, affinities.get(p["author_id"], 0.0), now), p["post_id"])
for p in candidates
]
scored.sort(reverse=True)
return [post_id for _, post_id in scored[:limit]]
if __name__ == "__main__":
now = 1_700_000_000
posts = [
{"post_id": "a", "author_id": "u1", "created_at": now - 3600, "likes": 2, "comments": 0},
{"post_id": "b", "author_id": "u2", "created_at": now - 7200, "likes": 80, "comments": 20},
{"post_id": "c", "author_id": "u3", "created_at": now - 600, "likes": 0, "comments": 0},
]
print(rank(posts, {"u1": 0.9, "u2": 0.1}, limit=3, now=now))The recency term halves every six hours. The log1p call keeps a viral post from drowning everything else, because the score grows slowly with likes. Run the script and you will see the older, heavily engaged post b outrank the fresh post c that nobody has reacted to yet.
Common errors
- Ranking the whole timeline. Scoring 800 items per request, for every user, multiplies CPU cost with no visible gain. Rank a bounded candidate set.
- Unstable order between pages. If scores change between requests, a post can appear on page 1 and again on page 2, or vanish. The cursor chapter's keyset approach assumes a fixed sort key. With ranking, either cache the ranked list for a session, or put the score snapshot into the cursor.
- Cold start. New posts have no engagement and new users have no affinity data. Give them a neutral default, or the ranker will never surface them.
- Feedback loops. Ranking by engagement shows popular posts, which gets them more engagement. Add diversity rules and some exploration so new authors get shown.
- Training on what was shown. A model trained only on clicks from the ranked feed learns the old ranker's biases. Log impressions as well as clicks.
Where ranking sits in the architecture
Ranking reads the feed cache but does not change it. The cache keeps chronological references, which are cheap to store and easy to trim. Ranked output is computed per request, or cached briefly per user session. Storing ranked order in the timeline itself would mean rewriting every follower's feed whenever an engagement count changes, which destroys the cost advantage of fan-out on write.
Exercise
A user reports seeing the same post on page 1 and page 2 after you added a scoring step. The cursor still holds the last item's (createdat, postid). What is the likely cause, and how can you fix it?
Show answer
The cursor assumes pages are ordered by (createdat, postid), but ranked pages are ordered by score, and scores change between requests as engagement and age change. The next page is cut from a different ordering than the previous one, so items can repeat or be skipped. Fix it by caching the ranked candidate list for the session and paging through that snapshot, or by encoding the last score and post_id in the cursor and reading from a score snapshot.
Exercise
Why does the timeline keep chronological references instead of storing ranked order for each user?
Show answer
Ranking inputs such as engagement counts change constantly. Storing ranked order would require rewriting every follower's timeline on each change, which removes the benefit of fan-out on write. Keeping chronological references and ranking at read time on a small candidate set keeps writes cheap.