System design interview: design a real-time leaderboard
A real-time leaderboard ranks players by score and answers two questions fast: who is in the top N, and what is my rank. The usual design keeps a sorted set in memory (a Redis sorted set is the standard example), writes every score change to a durable database as the source of truth, and only shards the ranking when one node can no longer hold or serve it.
By Evin JohnPublished 8 min read
1. Clarify the requirements
Leaderboards range from a weekend tournament table to a global all-time ranking. The scope changes the answer, so ask.
- Functional: add points when a player wins a match; show the top 10 or 100; show a player's own rank and score with a few players above and below; reset monthly; optionally a friends-only board.
- Non-functional: ranks update within a second or two of a match ending; reading the board is fast even at the end of a big event; scores are never lost, even if the ranking layer restarts.
- Out of scope unless asked: matchmaking, rewards payout, the game itself. Ask whether scores only go up; if they can fall, that changes nothing in a sorted set but matters for some shortcuts.
2. Estimate the scale
| Quantity | Assumption | Result |
|---|---|---|
| Score updates | 20 million daily players, 5 scored matches each | 100 million a day, about 1,200 a second on average; 10x at an event peak, about 12,000 |
| Board reads | 3 views per match | 300 million a day, about 3,500 a second on average |
| Members in this month's board | 50 million players who scored at least once | the size of the sorted set |
| Sorted set memory | about 100 bytes per member including index overhead | about 5 GB: fits on one in-memory node |
Both rates are well within one in-memory node's capacity, so the first design is a single primary with replicas. Sharding is a deep dive, not the starting point.
3. Define the API
POST /v1/scores (game service only)
{ match_id, user_id, points, achieved_at }
GET /v1/leaderboard/top?board=2026-12&limit=10
GET /v1/leaderboard/me?board=2026-12&around=4 -> my rank, score, 4 above, 4 below
GET /v1/leaderboard/friends?board=2026-12Include match_id so the write is idempotent: a retried request for the same match must not add points twice.
4. Sketch the data model
| Store | Contents | Role |
|---|---|---|
| scores table (relational or key-value) | board, user_id, points, achieved_at, updated_at | Source of truth; rebuilds the ranking after a loss |
| applied_matches | match_id (unique) | Rejects duplicate score writes |
Sorted set lb:{board} | member = user_id, score = packed points and time | Top N and rank queries |
| Profile cache | user_id -> name, avatar | Fills display fields for the IDs a query returns |
5. Why a sorted set, and how to break ties
With a relational table, the top 10 is cheap with an index on score, but "what is my rank" is SELECT COUNT(*) WHERE score > mine, which scans a large part of the index for a mid-ranked player. Caching ranks does not help when they change every second.
A sorted set keeps members ordered by score in a skip list plus a hash. In Redis, ZADD sets a member's score and ZINCRBY adds to it, ZREVRANGE 0 9 WITHSCORES returns the top 10 (newer Redis versions also accept ZRANGE with REV), ZREVRANK returns a member's zero-based position and ZREVRANGE with that position plus or minus a few gives the neighbours. Each is logarithmic in the set size plus the number of results.
Ties. Two players on 1,500 points need a stable order; a common rule is that whoever got there first ranks higher. Sorted-set scores are double-precision numbers, so pack both values into one integer that a double holds exactly:
T_MAX = 2 ** 32 # seconds; covers dates past the year 2100
def packed(points, achieved_at):
# higher points first; for equal points, earlier time first
return points * T_MAX + (T_MAX - 1 - achieved_at)
def unpack(score):
return score // T_MAX, T_MAX - 1 - score % T_MAX
# A double is exact for integers up to 2**53, so points must stay
# below 2**53 // T_MAX = 2**21, about 2.1 million per board.If points can exceed that, shrink the time part (minutes since the season started need far fewer bits), or keep the tie-break outside the score and sort equal scores by member ID, which some sorted sets do already.
6. The architecture
- Game
- Game servers (validate matches)
- Write path
- Score service
- Scores database
- applied_matches
- Ranking
- Sorted set primary
- Read replicas
- Read path
- Leaderboard API
- Profile cache
- Recovery
- Rebuild job from scores table
- ValidateThe game server confirms the match result; clients never call the score API directly.
- PersistInsert the match ID and add the points in one database transaction; a duplicate match ID ends here.
- RankApply the new total to the sorted set. Write the recomputed packed score with
ZADDrather thanZINCRBY, because incrementing a packed number would leave its time part stale. If that fails, a retry or the rebuild job repairs it from the database. - ReadTop N and "around me" queries hit replicas; the top 100 can also be cached for a second or two.
7. Deep dives
- Monthly resets. Use one key per period (
lb:2026-12). A new month starts an empty key; the old one stays readable for the results page and then expires. No mass delete at midnight. - Friends board. Friend lists are short, so fetch each friend's score (one batched call) and sort them in the service. Keeping a sorted set per user would multiply writes by friend count.
- Sharding by score range. Give each shard a band (0 to 999 points, 1,000 to 4,999 and so on). A player's rank is the number of players on higher shards plus their rank within their own shard, and the top 10 comes from the highest non-empty shard. The catch: players move between shards as they score, and bands fill unevenly, so choose them from the real score distribution.
- Sharding by hash. Spread players evenly by user ID. Top N becomes scatter-gather: ask every shard for its top N and merge. An exact rank needs a count of higher scores from every shard on each request, which costs one call per shard; many products show "top 5%" instead for players far down the list.
- Approximate ranks at huge scale. For a board with hundreds of millions of members, exact rank for everyone may not be worth it. A histogram of scores gives a percentile cheaply, while exact ranks stay for the top few thousand.
8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| In-memory primary lost | Recent rank updates missing after failover | Replay recent score changes or rebuild the board from the scores table; replicas plus append-only persistence shorten the gap |
| Duplicate match result | Points counted twice | Unique match ID checked in the same transaction as the score update |
| Event surge at season end | Many writes and reads on one key | Replicas for reads, short caching of the top N, batching of score updates per player |
| Database and sorted set disagree | A player sees a rank that does not match their score | Write the database first, update the set after, run a periodic reconciliation |
| Cheated score slips through | Fake player at the top | Server-side validation, anomaly checks on large jumps, admin removal that updates both stores |
9. Trade-offs to discuss
- Exact or approximate rank. Exact ranks for everyone cost cross-shard counts once you shard; percentiles are cheap and good enough below the top tier.
- Write-through or asynchronous ranking. Updating the set in the request path keeps ranks fresh to the second; going through a queue smooths surges at the cost of a short delay. See caching for the general pattern.
- Range or hash sharding. Range shards make rank cheap and balance poorly; hash shards balance well and make rank expensive. Pick from which query matters more.
10. How to talk through it in the interview
Fictional example
- Interviewer
- Fine for 50 million players. What if the board has two billion?
- Candidate
- Memory goes to roughly 200 GB, so I would shard. If exact rank for the top matters most, I would shard by score range: rank is the count of players on higher shards plus my position in my shard. For players outside the top few thousand I would show a percentile from a score histogram instead of an exact number.
- Interviewer
- And ties?
- Candidate
- Earlier achievement wins. I pack points and time into one integer that a double holds exactly, which limits points to about two million unless I shorten the time part.
- Show why
COUNT(*)for rank fails before proposing the sorted set. - Keep a durable store; an in-memory ranking alone is a single point of loss.
- Have one sharding scheme ready and say what it costs.
Practicing this design with Natively
Leaderboards are a common warm-up prompt, and the follow-ups (ties, resets, sharding) arrive quickly. Practise them in a mock call with Natively running: it writes down what both of you say, can offer a few talking points when a question lands, and leaves a transcript you can reread to find the follow-up you answered vaguely. Capturing your sketch of the score and ranking paths as a screenshot lets you ask what it is missing.
Questions people ask
How do you design a real-time leaderboard?
Keep the ranking in an in-memory sorted set, such as a Redis sorted set, so top N and a player's rank take logarithmic time. Write every score change to a durable database first so the ranking can be rebuilt, and use the match ID to ignore duplicate results.
Why not use a SQL database for leaderboard ranks?
The top 10 is easy with an index, but a player's rank needs a count of everyone above them, which scans a large part of the index for mid-ranked players. At tens of millions of players and constant updates that is too slow, while a sorted set answers it directly.
How do you break ties on a leaderboard?
Decide the rule first, often that the earlier achievement ranks higher, then pack points and time into one integer score. Because sorted-set scores are doubles, keep the packed number below 2 to the power 53 so it stays exact.
How do you shard a leaderboard?
Shard by score range so a rank is the count of players on higher shards plus the position within one shard, accepting uneven shard sizes. Or shard by user hash for even load and gather each shard's top N, which makes exact ranks for everyone more expensive.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
