AI Hints
Home›System Design Tutorial›Case Study: Feeds and Notifications
System Design · Lesson 101 of 120

News Feed: Ranking and Cache

The final feed.

⏱ 2 min read▶ Video at 2:02:42🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Feeds today aren't just newest first. They're ranked, mixing recency with how interesting each post is likely to be for you. And the result must be cached, so it loads instantly.

News Feed: Ranking and Cache
From the video: News Feed: Ranking and Cache
  • Not just newest first
  • Ranked for you
  • Cached for speed

A simple ranking score

A simple ranking score combines engagement and age. More likes and comments raise the score, and older posts slowly sink. Run it. The two hour old post with forty likes comes first. The viral post from two days ago has sunk below it, despite having far more likes.

rank.pypython
posts = [
    ("new, no likes",     0,   1),
    ("2h old, popular",  40,   2),
    ("2 days, viral",   500,  48),
]

def score(likes, hours):
    return (likes + 1) / (hours + 2) ** 1.5

for name, likes, hours in sorted(posts, key=lambda p: -score(p[1], p[2])):
    print(f"{score(likes, hours):6.2f}  {name}")
Output
  5.12  2h old, popular
  1.42  2 days, viral
  0.19  new, no likes

The full feed design

Putting it together. A new post is saved, and sent to a fan out service through a queue. The fan out service adds the post ID to each follower's feed list in Redis. When a user opens the app, the feed service reads their list, merges in celebrity posts, ranks them, fetches the post contents from a cache, and returns the top twenty.

  1. Save post
  2. Queue
  3. Fan-out to Redis lists
  4. Merge + rank
  5. Return top 20
The full feed design
From the video: The full feed design

Summary

The feed is ranked by engagement and age, with lists kept in Redis, filled by a fan out service through a queue. Next, a notification system.

Key takeaways
  • Rank by engagement and age
  • Feed lists in Redis
  • Fan-out through a queue
Next up: Notification System — email, SMS, push