Lesson 9 of 15
37. Design a News Feed

37.8 How does ranking work?

3 min read+10 XP

A ranked feed is built in four stages:

candidates from the feed cache and celebrity pulls are scored by affinity, type and freshness, filtered by rules, then hydrated.

Figure: candidates → score → rules → hydrate.

  1. Candidates: the post IDs from the feed cache plus celebrity pulls (a few hundred).
  2. Score: a simple, explainable model is affinity × type weight × freshness:
    • affinity: how much you interact with this author (likes, comments, profile visits).
    • type weight: some post types tend to get more engagement.
    • freshness: halves every 12 hours (a decay, like Chapter 34's trends). Facebook's early feed ranking was publicly described in roughly this shape; modern feeds use machine-learned models predicting likes, comments and time spent, but the pipeline is the same.
  3. Rules: diversity (not five posts in a row from one author), remove posts already seen, demote low-quality or reported content.
  4. Hydrate: fetch post bodies and counts for the final 20 only.

In the chapter's code, a close friend's 3-hour-old photo ranks 2nd of 302 candidates; in plain time order it would be buried below newer posts from people the reader barely knows.

Keep ranking cheap at read time: precompute affinities offline, score a few hundred candidates per request, and cache the result for the session.

Memory code: "Gather a few hundred, score them, keep the best twenty."