Design a Leaderboard

How to design a game leaderboard that shows the top 10 and any player's rank among 50 million, and what interviewers ask about it.

Case study25 minLesson 8 of 8
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A leaderboard records the best score of each player in a game and shows the top players, a player's own rank and the players just above and below them. It must answer rank queries immediately after each score update.

The difficulty is the rank. The obvious query, ORDER BY score DESC, works for a thousand players, but with fifty million players, finding a rank means counting everyone with a higher score. Interviewers ask it to see whether you know a structure that ranks in O(log n), can keep an in-memory ranking durable, and can split one global order across machines. The steps follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a leaderboard for an online game.

You

Is a player's score the best single match, or the total of all their matches? And which boards do we need: all-time, weekly, daily?

Interviewer

The best single match score. We need all three boards.

You

How many players are there, and how often do scores change?

Interviewer

There are 50 million players on the all-time board. About 10 million play each day, and each plays about 10 matches.

You

I will assume that scores are submitted by our game servers and not by the players' phones. A lost score is worse than a late one, so the ranking can live in memory but the scores must be durable. How should ties be broken?

Interviewer

The player who reached the score first ranks higher.

  • Functional: record a score and keep each player's best score on each board; show the top 10; show a player's rank together with the 5 players above and the 5 below.
  • Non-functional: a new score appears in the rankings within about a second; reads take under 50 ms; no accepted score is lost; the player who reached a score first wins a tie; the boards stay readable when one node fails.
  • Out of scope: cheat detection and rewards.

Estimate the scale

  • Score writes: 10 million players × 10 matches is 100 million matches a day. Dividing by 86,400 seconds gives about 1,200 matches a second, and a 5x peak gives about 5,800. Each match updates three boards, so the peak is 17,400 board writes a second.
  • Reads: assuming 3 views per match gives 300 million a day, about 3,500 a second and about 17,000 at peak. Each rank read needs 2 sorted-set operations.
  • Operations at peak: 17,400 board writes plus 17,000 × 2 = 34,000 read operations is 51,400 sorted-set operations a second. If one node performs about 100,000 such operations a second, one primary is about half busy, and read replicas add headroom.
Estimate: Memory for the all-time board

How much memory does the all-time board need in an in-memory sorted structure?

You know
  • 50 million players
  • About 100 bytes per entry, counting player id, score, and index and hash-map overhead

Show the working
  1. 50 × 106 × 100 B = 5 × 109 B = 5 GB
  2. The weekly and daily boards add a few GB more

Estimate 5 GB (anything from 1 GB to 20 GB is a good answer)

The boards fit in the memory of one machine, so sharding is about throughput and not size.

Your turn: Define the API

Who submits a score, and how does a client read the top 10 and its own rank? What should happen if the same score arrives twice?

Compare with a model answer

The game server submits each score together with a match id, so a retried request is ignored. The app reads the top entries and the entries around the player.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
POST /scores                                called only by game servers, with service credentials
  body: { "match_id": "m_9f2", "player_id": 42, "score": 4200, "ended_at": "..." }
  200 { "best": { "all_time": 5100, "weekly": 4200, "daily": 4200 } }
  200 the same body when the match_id was already applied
 
GET  /boards/{board}/top?limit=10           board is all_time, weekly or daily
  200 { "entries": [ { "rank": 1, "player_id": 7, "score": 9930 }, ... ],
        "as_of": "2026-11-14T18:00:01Z" }
 
GET  /boards/{board}/players/{id}?around=5
  200 { "rank": 48213, "score": 4200, "above": [ ...5 entries ], "below": [ ...5 entries ] }
  404 the player has no score on this board yet

The API decision to argue about is who may write a score. If phones post scores, anyone with a proxy can claim 99,999 points. The game server submits the score with a match_id, so a retry cannot count a match twice.

Your turn: Model the data

What is the durable record, and what answers "what is the rank of player 42" in milliseconds? Can one store do both jobs?

Compare with a model answer

Two stores are used. A database holds one durable row per player per board, and an in-memory sorted set per board answers rank queries in O(log n). The sorted sets can be rebuilt from the database rows.

Model the data

Durable rows and in-memory boards
-- source of truth: a database, partitioned by player_id
best_scores
  board_id     VARCHAR(24)    -- "all_time", "weekly:2026-W46" or "daily:2026-11-14"
  player_id    BIGINT
  score        INT
  reached_at   TIMESTAMP      -- used to break ties, the earlier time wins
  updated_at   TIMESTAMP      -- indexed, used to replay recent changes after a failover
  PRIMARY KEY (board_id, player_id)
 
matches_applied               -- records each match so that it is counted once
  PRIMARY KEY (player_id, match_id)   -- stored in the same partition as the player's rows,
                                      -- so one local transaction covers both tables
 
-- ranking: one in-memory sorted set per board
weekly:2026-W46   member = player_id, sort key = score combined with a tie-break (see deep dives)

A score update changes one player's row, which any database can do with a conditional update such as "set the score to 4,200 if it is higher". Finding a rank is a different kind of query: SELECT COUNT(*) WHERE score > 4200 has to walk every higher entry in the score index, which can be up to 50 million entries. An in-memory sorted set, such as the one in Redis, finds a rank in about log2(50 million), or roughly 26, steps. The sorted sets therefore hold the rankings as a view that can be rebuilt from the database.

Your turn: High-level design

Sketch the write path for a finished match and the read path for "my rank". Which store is written first?

Compare with a model answer

The path is game server, score service, database (deduplicated by match id), then the sorted sets. Reads use only the sorted sets. The database is written first, so a crash can only leave the sorted set behind.

High-level design

Writes go to the database first and then to the sorted sets, while reads use only the sorted sets, with the top 10 cached for one second.Player's app to Leaderboard API (top, around me); Player's app to Game servers (play); Game servers to Score service (POST /scores); Score service to Best scores DB (1. upsert if higher); Score service to Sorted sets (memory) (2. update boards); Leaderboard API to Sorted sets (memory) (rank, range).Player's appLeaderboard APIGame serversScore serviceSorted sets(memory)Best scores DBtop, around meplayPOST /scores1. upsert if higher2. update boardsrank, range
Writes go to the database first and then to the sorted sets, while reads use only the sorted sets, with the top 10 cached for one second.
A new best score, a read, a retry and a crashUse the arrows or ← → keys
  1. A new best score, a read, a retry and a crash, step 1Player's app to Leaderboard API; Player's app to Game servers; Game servers to Score service; Score service to Best scores DB; Score service to Sorted sets (memory); Leaderboard API to Sorted sets (memory).Player's appLeaderboard APIGame serversScore serviceSorted sets(memory)Best scores DB
    weekly best
    3,100

    1Player 42 finishes match m_9f2 with 4,200 points, and the game server posts the score.

  2. A new best score, a read, a retry and a crash, step 2Player's app to Leaderboard API; Player's app to Game servers; Game servers to Score service; Score service to Best scores DB; Score service to Sorted sets (memory); Leaderboard API to Sorted sets (memory).Player's appLeaderboard APIGame serversScore serviceSorted sets(memory)Best scores DB2 rows raised
    weekly best
    4,200

    2In one transaction the service records m_9f2 as applied and raises each board's row if 4,200 is higher. The weekly and daily rows rise, and the all-time row stays at 5,100.

  3. A new best score, a read, a retry and a crash, step 3Player's app to Leaderboard API; Player's app to Game servers; Game servers to Score service; Score service to Best scores DB; Score service to Sorted sets (memory); Leaderboard API to Sorted sets (memory).Player's appLeaderboard APIGame serversScore serviceSorted sets(memory)42: 4,200Best scores DB
    weekly best
    4,200

    3The service then sets player 42's weekly and daily entries in the sorted sets to 4,200, which takes about 26 steps each.

  4. A new best score, a read, a retry and a crash, step 4Player's app to Leaderboard API; Player's app to Game servers; Game servers to Score service; Score service to Best scores DB; Score service to Sorted sets (memory); Leaderboard API to Sorted sets (memory).Player's appLeaderboard APIGame serversScore serviceSorted sets(memory)rank 48,213Best scores DB
    weekly rank
    48,213

    4The app asks for player 42's weekly rank. The sorted set adds up counts stored in its index, without visiting the entries above 42, and returns rank 48,213.

  5. A new best score, a read, a retry and a crash, step 5Player's app to Leaderboard API; Player's app to Game servers; Game servers to Score service; Score service to Best scores DB; Score service to Sorted sets (memory); Leaderboard API to Sorted sets (memory).Player's appLeaderboard APIGame serversScore serviceSorted sets(memory)Best scores DBm_9f2 seen
    weekly best
    4,200

    5The game server times out and retries m_9f2. The database already has the match, but the service still sends the bests to the sorted sets, which repairs a crash between the two writes.

  6. A new best score, a read, a retry and a crash, step 6Player's app to Leaderboard API; Player's app to Game servers; Game servers to Score service; Score service to Best scores DB; Score service to Sorted sets (memory); Leaderboard API to Sorted sets (memory).Player's appLeaderboard APIGame serversScore serviceSorted sets(memory)failoverBest scores DB

    6The sorted-set primary crashes and a replica takes over, but it may be missing the last fraction of a second of updates.

  7. A new best score, a read, a retry and a crash, step 7Player's app to Leaderboard API; Player's app to Game servers; Game servers to Score service; Score service to Best scores DB; Score service to Sorted sets (memory); Leaderboard API to Sorted sets (memory).Player's appLeaderboard APIGame serversScore serviceSorted sets(memory)caught upBest scores DB

    7The score service replays the rows changed in the last few minutes from the database, and overlapping replays are safe.

1 / 7

Deep dives

How to compute a rank

There are three ways to answer "what is my rank?".

A database query. The database stores one row per player with an index on score, and the rank is COUNT(*) of the rows with a higher score, plus one. A rank near the bottom is expensive, because the database walks every higher index entry, which is 30 million entries for rank 30,000,000. This is acceptable for tens of thousands of players.

An in-memory sorted set. A sorted set keeps two structures in step: a hash map from player to score, and an index ordered by score, built as a skip list or a balanced tree. Every link in the index stores how many entries it jumps over. To find a rank, the lookup walks down from the top of the index and adds up those counts, so it never visits the entries it skips. Rank, top N and a range around a player take O(log n). The cost is that it lives in memory, so it needs a durable source, and one set is limited to one node's throughput.

Score-bucket counts. Instead of ordering players, you count how many players have each score value and keep the counts in a Fenwick tree. A player's rank is the sum of the counts of all higher scores, which takes O(log of the score range). It cannot tell you who the neighbours are. It suits very large boards where an approximate rank is acceptable.

Ways to answer "what is my rank?"
OptionGood atBad atPick it when
Database with ORDER BY and COUNTIt needs no new infrastructure.A rank near the bottom scans millions of index entries.The board has at most tens of thousands of players.
In-memory sorted set Usual defaultIt gives the exact rank, top N and neighbours in O(log n).It needs a durable source to rebuild from.The board has millions of players. This is the usual answer.
Score-bucket countsIt is small and easy to shard.It cannot list the neighbours by name.An approximate rank is acceptable below the top.

Why a sorted set finds a rank in O(log n)

A skip list is a sorted linked list with express lanes. Level 0 links every entry, and each higher level links a random half of the entries on the level below. Every link also records its span, the number of entries it jumps over. To find a rank, the lookup starts at the top level and moves forward while the next entry scores higher than the target, adding the span of each link it follows, and drops a level when the next entry would pass the target. For example, with players A 980, B 950, C 900, D 870, E 820 and F 760, suppose level 1 links the head, B, D and F with a span of 2 each. The rank of C is found by following the level 1 link to B, which adds 2, then dropping to level 0, where the next entry is C, which adds 1, so its rank is 3. With 50 million players a rank takes roughly 50 steps.

Updating a score removes the old entry and inserts the new one, each in O(log n).

Sharding the sorted set

At the estimated scale sharding is not needed, because the boards take 5 GB and the peak load is about 51,000 operations a second, which one primary with read replicas can handle. Say this first in an interview. Sharding becomes necessary at roughly 10x this load.

Shard by player id. A hash of the player id picks the shard, so writes spread evenly. Queries then have to combine results from all shards. For the top 10 with, say, 8 shards, you take each shard's top 10 and keep the best 10 of those 80 entries, which is exact because every player in the global top 10 is also in the top 10 of their own shard. For a rank, you ask every shard how many scores are higher than 4,200 (O(log n) on each) and add the answers. The neighbours are found the same way, from each shard's 5 entries on each side of the score. The cost is 8 parallel calls per rank lookup, which is as slow as the slowest one.

Shard by score range. Each shard owns a band of scores. A rank is then the number of players in all higher shards (a small stored counter) plus the player's rank inside their own shard, so a lookup touches only one shard. The problems are that the shard with the top scores is the hottest, the bands need rebalancing as scores grow, and a player who crosses a boundary moves shards.

I would shard by player hash. An even load matters more than saving parallel calls, and the merged top 10 is computed only once a second and cached.

Keeping the in-memory board durable

The persistence features of an in-memory store (a log flushed every second, snapshots, asynchronous replicas) can each lose the most recent writes. The better design makes the database the only source of truth and treats the sorted set as a copy that can be repaired.

  • After a failover, replay the rows whose updated_at falls in the last few minutes. Setting a score only if it is higher gives the same result when applied again and in any order, so overlapping replays are safe.
  • After losing every copy, rebuild the board from the database. At an assumed 500,000 inserts a second, 50 million entries take 100 seconds.

Daily and weekly boards

Each period gets its own sorted set, named after the period, such as weekly:2026-W46, so a new period starts with an empty set and needs no cleanup job. When a period ends, copy its final top results to the database and let the set expire. Scores are assigned to a period by the match's ended_at time, and the boundaries use one clock, usually UTC.

Breaking ties

To make the earlier player win a tie, put the time into the sort key. Pack one number with the score in the high bits and (220 − 1 − seconds into the week) in the low bits, so that an earlier time gives a bigger number. A week has 604,800 seconds, which fits in 20 bits (220 = 1,048,576), and so do scores up to a million. For example, score 4,200 reached 190,800 seconds into the week gives 4,200 × 1,048,576 + (1,048,575 − 190,800) = 4,404,876,975. Every packed number fits in 40 bits, which is below the 53 bits that a 64-bit float stores exactly, and that matters because some sorted sets store scores as floats. The all-time board needs about 30 bits for the seconds, since 230 seconds is about 34 years, so 50 bits in total, which still fits.

Bottlenecks and failures

At 10x the load there are about 58,000 matches a second at peak and about 514,000 sorted-set operations a second, which is too much for one primary, so you shard each board by player into, say, 8 sorted sets. Each match updates three rows, so the database takes about 174,000 conditional updates a second, which works because it is partitioned by player. Every rank read goes to every shard, so each shard still sees about 360,000 operations a second (340,000 reads and 22,000 writes), and each shard needs several read replicas.

Component that failsWhat happensWhat you do
A sorted-set primaryWrites to that board pause, and the promoted replica may be missing the most recent updates.Replay the recent rows from the database, and keep serving reads from the replicas.
All copies of a sorted setRank queries cannot be answered.Show the cached top 10 and rebuild the set from the database, which takes about 100 seconds.
The databaseNew scores cannot be stored durably.The game servers queue the scores and retry them, and match ids make the retries safe. Reads keep working from memory.
A score service instanceA request can fail between the database write and the sorted-set write.The game server retries, and the retry sends the bests to the sorted sets again. The service must not return early for a match that was already applied.

What a strong answer sounds like

The answers differ in whether they notice that rank is the hard part, and in how well they handle failure and scale.

LevelWhat the answer does
JuniorStores scores in a table and uses ORDER BY and COUNT, and moves to an in-memory sorted set only after the interviewer asks about 50 million players.
Mid-levelChooses a sorted set from the start, explains why counting rows is too slow, and adds a match id so that retries are safe.
SeniorShows that one node is enough at the estimated scale, explains how the board recovers after a failover, handles ties, and shards by player with a correct merge when the load grows.
Rank among millionsStrong answer
Interviewer

How do you show a player their rank?

You

I keep the board in an in-memory sorted set. Each link in its index stores how many entries it skips, so the rank is a sum along about 26 levels and not a count of 48,000 rows. The board is 5 GB, so one primary holds it.

Interviewer

What changes at 500 million players?

You

I would shard by player. The top 10 is an exact merge of each shard's top 10, and a rank is the sum of a parallel count of higher scores on every shard. If that is too slow, I would keep exact ranks for the top entries and use score-bucket counts for an approximate rank below them.

Follow-up questions

How would you build a friends-only leaderboard?

A sorted set for each player's friends would be far too much data to keep up to date, because one score change would have to be written into every friend's set. Instead, read the scores of the player's few hundred friends in one batch and sort them when the request arrives.

Why not use a heap for the top 10?

A heap returns the top k entries cheaply, but it cannot tell you the rank of an arbitrary player, and changing the score of an arbitrary player needs extra bookkeeping to locate the entry. The sorted set answers all of these with one structure.

What if a score must be removed after a ban?

Delete the player's row in the database and remove the member from each sorted set. Every player below moves up automatically, because ranks are computed and not stored.

How does a player see their new rank right after a match?

The write path updates the sorted sets before the score service answers the game server, so a read that starts after the response sees the new score. If reads go to replicas, a replica can be a fraction of a second behind, so the app can read from the primary for a short time after the player's own match.

Self-review: leaderboard0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure