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.7 How do you handle real-time updates?
3 min read+10 XP
Figure: fold many events into one rescore per team per batch.
The update pipeline:
- Before the match, build an index player → teams that picked him (and as captain or vice). It's fixed once the contest locks.
- During the match, events update player points immediately (22 numbers).
- Each batch (10-30 s), collect players whose points changed, take the union of their teams, and rescore each affected team once, however many events touched it.
- Write in bulk (pipelined
ZADDs), spread across 20 shards: about 7 seconds for 13 million updates. - Publish "updated at" and refresh the top-100 cache.
In the chapter's code, the most popular player is in 66% of teams; at 20 million teams, one six changes about 13 million scores.
Alternatives to know:
- Store points per player, compute team scores on read for "my score" (11 lookups and a sum): cheap for one user, but ranking still needs the sorted set.
- Smaller contests (a few thousand teams, private leagues) can be rescored instantly; batch only the giant ones.
Memory code: "Many events, one rescore per team per batch."