35. Design a Leaderboard (Top-K)
1
The interview prompt2
35.1 What do you ask first?3
35.2 How big is this, really?4
35.3 What are the doors?5
35.4 What do we store?6
35.5 What does the whole system look like?7
35.6 How do sorted sets work for this?8
35.7 How do you handle real-time updates?9
35.8 How do you handle ties?10
35.9 How do you shard a leaderboard?11
35.10 What would you say in the last five minutes?12
Score yourself13
Variations to practise14
Sources15
Code lab35. 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:
| Need | Command | Cost |
|---|---|---|
| Set or change a team's score | ZADD lb t42 412.5 | O(log N) |
| Top 100 | ZREVRANGE lb 0 99 WITHSCORES | O(log N + 100) |
| My rank (0-based) | ZREVRANK lb t42 | O(log N) |
| How many score above X | ZCOUNT lb (412.5 +inf | O(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
pointswithORDER BY ... LIMIT 100is fine, and "my rank" isCOUNT(*) 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."