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

Non-functional requirements

From version 1 to the final design

  1. Version 1: an SQL table with ORDER BY score LIMIT 10.
  2. Version 2: a Redis sorted set for the top N and for ranks.
  3. Version 3: a separate set per period, tie-breaking, and a durable copy for recovery.
  4. Version 4: splitting the set, or approximate ranks, for very large numbers of players.

The design, step by step

  1. Score updates go to the game service, which saves them durably and updates a Redis sorted set.
  2. Top N: ZREVRANGE 0 N−1. A player's rank: ZREVRANK. Both run in logarithmic time.
  3. A separate sorted set per period (daily, weekly), with expiry.
  4. At very large scale: split by score range, or give approximate ranks.

Deep dives

Common mistakes

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.