Lesson 7 of 15
35. Design a Leaderboard (Top-K)

35.6 How do sorted sets work for this?

3 min read+10 XP

Step 5: Deep dives (10 minutes)

A Redis sorted set keeps members ordered by a numeric score, internally with a skip list plus a hash map, so:

NeedCommandCost
Set or change a team's scoreZADD lb t42 412.5O(log N)
Top 100ZREVRANGE lb 0 99 WITHSCORESO(log N + 100)
My rank (0-based)ZREVRANK lb t42O(log N)
How many score above XZCOUNT lb (412.5 +infO(log N)

In the chapter's code, a small sorted set of 5,000 teams answers top-3 and rank exactly as a full sort would. At 20 million members, log₂(20 million) is about 24 steps per operation, so each call is microseconds; the cost at scale is the number of calls, not each one.

Interviewer pushback:

  • "Could you do it in SQL?" → For small leaderboards, an index on points with ORDER BY ... LIMIT 100 is fine, and "my rank" is COUNT(*) WHERE points > mine. At 20 million rows with constant refreshes and updates, that count is too slow to run per request. A sorted set is built for it.

Memory code: "Add, rank, range and count, each in log time."