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.4 What do we store?
3 min read+10 XP
teams (database: who picked whom; written before the match, then frozen)
team_id, user_id, contest_id, players[11], captain, vice_captain, joined_at
player_points (small: 22 players per match)
match_id, player_id, points, as_of_event
leaderboard (Redis sorted sets, one per contest, sharded by team)
key: lb:{contest}:{shard}
member: team_id
score: composite(points, joined_at) (35.8)
finals (database, written once at the end, audited)
contest_id, team_id, final_points, final_rank, prize
Interviewer pushback:
- "Why a sorted set?" → It keeps members ordered by score with logarithmic time for update (
ZADD), rank (ZREVRANK) and range (ZREVRANGE), and counts by score range (ZCOUNT). That's exactly "update score", "my rank" and "top 100". A SQLORDER BY pointsover 20 million rows on every refresh would be far too slow.
Memory code: "Teams in the database, ranks in a sorted set, prizes in an audited table."