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.5 What does the whole system look like?
3 min read+10 XP
Step 4: High-level design (10 minutes)
Figure: the final design. Writes are batched; the top 100 is cached; "my rank" asks every shard.
During the match, step by step:
- The live match feed sends events ("p0 hit a six"); player points are updated (a tiny table: 22 players).
- Every 10 to 30 seconds, score workers take all events since the last batch, find the affected teams (an index from player to teams, built before the match), compute each affected team's new score once, and write the scores to the sharded sorted sets in bulk.
- After each batch, a job rebuilds the top-100 cache by merging each shard's top 100 (35.9).
Reads:
- Top 100: served from the cache (or a CDN), refreshed each batch: the same answer for millions of users.
- My rank: the API reads the user's score from their shard, asks every shard how many teams are above that score (
ZCOUNT), and adds them up.
After the match: a final job recomputes every team's score from the full, verified event list, ranks them exactly with the tie rules, writes the finals table, and pays prizes. The live leaderboard is never used for money.
Interviewer pushback:
- "Why not update ranks instantly, ball by ball?" → 13 million writes per ball don't fit (35.2). A 10-30 s batch makes the write load predictable, and users accept a short, honest delay.
- "What if a Redis shard dies mid-match?" → Replicas take over. Worst case, rebuild that shard from the teams table and current player points: it's derived data, recomputable in a batch.
Memory code: "Batch the writes, cache the top, ask every shard for my rank, and pay from the final job."
Offer: "The interesting parts are the sorted set itself, the update bursts, ties, and sharding. Which would you like?"