Design a real-time leaderboard
Show live rankings of players by score, including each player's own rank.
Why interviewers ask it
It tests choosing the right data structure (a sorted set), and keeping a fast in-memory view in step with durable storage.
Functional requirements
- Update a player's score.
- Get the top N players; get one player's rank and the players around them.
Non-functional requirements
- Updates and reads in milliseconds.
- Millions of players.
From version 1 to the final design
- Version 1: an SQL table with ORDER BY score LIMIT 10.
- Version 2: a Redis sorted set for the top N and for ranks.
- Version 3: a separate set per period, tie-breaking, and a durable copy for recovery.
- Version 4: splitting the set, or approximate ranks, for very large numbers of players.
The design, step by step
- Score updates go to the game service, which saves them durably and updates a Redis sorted set.
- Top N: ZREVRANGE 0 N−1. A player's rank: ZREVRANK. Both run in logarithmic time.
- A separate sorted set per period (daily, weekly), with expiry.
- At very large scale: split by score range, or give approximate ranks.
Deep dives
- Sorted sets are skip lists: logarithmic updates and rank lookups.
- Ties: fold a timestamp into the score, so whoever reached it first ranks higher.
- Rebuild Redis from the database after a failure.
Common mistakes
- Recalculating ranks with SQL on every request.
- No durable copy, so a Redis restart loses the scores.
- Ignoring ties: decide how two players with the same score are ranked, for example by who reached it first.
Not true: Ranks: worked out by a SQL query on each request, which keeps a live leaderboard fast.
In fact: Sorting millions of rows for every request is far too slow. A Redis sorted set keeps the order up to date as scores change, so a rank lookup is quick.
In the interview
I'd use a Redis sorted set, with the player ID as the member and the score as the sort value. ZINCRBY updates a score, ZREVRANGE gives the top N, and ZREVRANK gives a player's rank. All three are logarithmic. Scores are also saved durably, so the set can be rebuilt. Each time period gets its own set.
Part of Unit 8: High-level design questions in the free System Design course.