"Design a leaderboard" is a small question with a trap in it. The obvious answer is a table with a score column and ORDER BY score DESC. It works for a thousand players, and the interviewer wants to find out whether you can say why it stops working and what replaces it.
The real problem is two operations that fight each other: updating one player's score, thousands of times a second, and asking "what is my rank?" among hundreds of millions, which needs the whole ordering. A database can do either well. Doing both on every request is the problem.
The tool that fits is an in-memory sorted structure, and the caching lesson covers the Redis behind it. This page is about when a single sorted set is enough, when to shard it, and how to handle the product details (time windows, ties, friends, cheating). If you are asked for a ranked social feed instead, see Design Reddit.
Clarify the requirements
Functional requirements:
- A player's score is updated when they finish a match.
- Show the top 100 players for a game.
- Show a player's own rank and the players just above and below.
- Leaderboards for the current day, week and all time.
- A friends-only leaderboard.
Out of scope, said aloud: matchmaking, in-game economy, anti-cheat detection itself (we only say where it plugs in), regional leaderboards (mention as the same design repeated per region).
Non-functional requirements: these decide the architecture.
- Rank queries are fast, in single-digit milliseconds, since the player sees them right after a match.
- Updates appear within a second or two. Players check the board after finishing.
- Correct ordering with a stated tie rule. Two players with the same score need a defined order.
- Scores are not lost. A cache restart must not erase the leaderboard.
- Tournament spikes. The end of a season or a tournament round can multiply update rates by ten.
Estimate the scale
Assume 500 million registered players, 50 million daily active. Each plays about 10 matches a day, and each views a leaderboard about 20 times a day.
Writes: 50M × 10 = 500 million score updates a day, or 5,800 per second on average. A tournament peak of 10x gives 58,000 per second.
Reads: 50M × 20 = 1 billion a day, about 11,600 per second. Most are "top 100" and "my rank".
Memory: a sorted-set entry holds a player ID, a score and the structure's overhead, about 100 bytes. 500M × 100 B = 50 GB for the all-time board. A daily board holds only the 50M players who played: about 5 GB.
Rank cost: finding a rank in a sorted set is a tree walk, about log2(500M) ≈ 29 steps. It is cheap. The data size and the update rate matter far more than the rank query.
"58,000 updates a second sounds large, but a single in-memory sorted set can sustain on the order of 100,000 operations a second. What does not fit comfortably on one node is 50 GB with replicas and headroom. So the question is memory and fault tolerance first, throughput second."
You can reproduce the update and read rates in the capacity estimator, where the size is the sorted-set entry.
API and data model
POST /v1/games/{g}/scores { playerId, matchId, score } (from the game server)
GET /v1/games/{g}/leaderboard?window=day|week|all&top=100
GET /v1/games/{g}/players/{p}/rank?window=... -> { rank, score, above[], below[] }
GET /v1/games/{g}/friends?playerId=...Redis: lb:{game}:all ZSET member = playerId, score = encoded score
lb:{game}:day:2026-12-02 ZSET (expires after 2 days)
lb:{game}:week:2026-W49 ZSET
Store: score_events (match_id PK, player_id, score, ts) -- durable, source of truth
best_scores (game_id PK, player_id CK, score)The non-obvious choice: scores reach the sorted set through a durable event, not a direct write by the game. The sorted set is a fast view that can be rebuilt from the events, so losing a cache node loses nothing.
High-level design
We simulate the update and read path: a score API writes to the leaderboard sorted set in Redis and publishes each score as an event, and writers consume those events into the durable score store.
- The score API updates the Redis sorted set and answers rank queries from it.
- Each score is also published to Kafka, and writers store it durably in DynamoDB.
Describe this diagram
Components
- players (Client)
- score api (Service)
- leaderboard (Redis)
- score events (Kafka)
- score writers (Service)
- score store (DynamoDB)
Connections
- players sends to score api
- score api sends to leaderboard
- score api sends to score events
- score events sends to score writers
- score writers sends to score store
Run it, then try raising the write share to mimic a tournament. Watch which tier saturates first.
The write path: the game server reports a finished match. The API validates it, runs ZADD with a "greater than" rule so a lower score never replaces a higher best, and publishes the event. Writers store it in the durable store.
The read path: ZREVRANGE 0 99 returns the top 100, and ZREVRANK plus a small range returns a player's rank and neighbors. Both are logarithmic and run in memory.
The recovery path: if Redis loses a board, a job replays best_scores into a fresh sorted set, and reads fall back to a slightly stale cached copy meanwhile.
The interesting problem: ranking 500 million players
One sorted set answers every question exactly, until it does not fit. Here are the choices as it grows.
Approach A: a single sorted set per leaderboard
All 500M players in one key, replicated to a standby.
Good: exact rank, exact top-K and trivial code. The 58,000 writes a second are within one node's capacity.
Bad: 50 GB in one process makes restarts and replica syncs slow, a single key cannot spread across nodes, and a failure takes the entire board down. It is the right answer up to roughly tens of millions of entries, and a brittle one beyond.
Approach B: shard by player ID
Hash each player to one of S sets. Writes spread evenly across shards.
Good: capacity and write throughput scale with S, and failures are partial.
Bad: every global question now needs all shards. The top 100 is the merge of the top 100 from each shard (S × 100 items). A player's exact rank is the sum, over all shards, of the number of players with a higher score, which is S ZCOUNT calls. It works, and each rank query costs S round trips.
Approach C: shard by score range
Partition the score space into buckets (for example 0 to 999, 1,000 to 4,999, and so on), each in its own sorted set, and keep a small table of how many players are in each bucket. A player's rank is the number of players in all higher buckets, plus their rank within their own bucket.
Good: a rank query touches one shard plus one tiny table of counts. The top-K is read from the highest bucket (and the next if needed). The few top players, who matter most, sit in a small, hot, cheap set.
Bad: a player moves between shards when their score crosses a bucket, which is a delete in one set and an insert in another, so it must be idempotent and recoverable. Bucket sizes must follow the real score distribution, which skews heavily, and counts are slightly stale if they are maintained asynchronously.
The recommended answer: start with A, and say when you would leave it. At 500M players use C for exact ranks, or combine it with an approximation, below. State the principle: shard by the thing your queries need ordered.
Time windows, ties and friends
Windows. Daily and weekly boards are separate sorted sets whose key includes the period, as in the data model above, and each expires a day or two after its period ends. Every score event updates all three, so one write is three ZADD calls in a pipeline. A rolling "last 7 days" is harder, and is better approximated by seven daily sets merged at read time for the top entries.
Ties. Sorted sets order equal scores by member name, which is arbitrary. Decide a rule, usually earlier achievement wins, and encode it into the score: store score × 2^20 + (2^20 − secondsSinceSeasonStart) as one number. Check that it fits in a double's 53-bit integer precision.
Friends. A friends board is small. Fetch each friend's score from the sorted set (one ZMSCORE call for a few hundred friends), sort in the service and return it. There is no need for a per-user sorted set.
Bottlenecks and failures
A tournament spike. Update rates jump tenfold. Buffer scores in the stream and let writers batch durable writes, while the Redis update stays synchronous. If one node saturates, shard the board as in B or C before the event, not during it.
A Redis node fails. Fail over to a replica, which may lag by a few updates, and replay the last minutes of events from the stream to close the gap. The durable store lets you rebuild a whole board.
Hot keys. The top-100 request is the same for everyone. Cache the result in the API for a second, or in a CDN, and serve it to millions from one copy.
Cheating. A client that reports its own score will be lied to. Only trusted game servers may submit scores, with a signed match ID. Reject impossible values, and keep events so that a banned player's scores can be removed and the boards repaired.
What if the durable store is down? Redis continues serving, and the stream holds the backlog. The boards stay correct for reads, and the durability gap closes when writers recover. Alert on the backlog age.
Trade-offs to name aloud
- A single sorted set versus sharding: simple and exact until memory and failure blast radius say otherwise.
- Exact rank only for the top: a percentile for the rest saves most of the complexity.
- Events as the source of truth: a rebuildable cache and a replayable history, paid for with a stream and writers.
- Encoding the tie-break into the score: one number to sort, with a precision budget to watch.
What interviewers listen for
- A working answer: Redis sorted sets for the ordering,
ZADD,ZREVRANGEandZREVRANK, and a database for persistence. - A strong answer: sizes memory and update rate, explains why
ORDER BYfails, shards when needed with the cost of each scheme, and plans time windows and ties. - A standout answer: also shards by score range with bucket counts, uses percentiles beyond the top, rebuilds boards from an event log, handles tournament spikes before they happen and defends against forged scores.
Check your understanding
Common mistakes
Proposing a database sort. Say why it fails, in one sentence with the update rate and the rank query, and move to the in-memory structure.
Sharding first. At tens of millions of entries a single sorted set is fine. Showing that you start simple and know the threshold is a strength.
Treating Redis as the database. A cache restart that loses all scores is an incident. Keep the events and the best scores durably.
Forgetting ties. An undefined order changes between calls and players notice. State the rule.
Trusting the client. A leaderboard that accepts scores from the player's device is a leaderboard of cheaters.
Practice
A season ends and all players' seasonal scores reset to zero while the all-time board stays. Describe a safe way to roll over, with no downtime and no lost scores.
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Think about keys that include the period, and what has to happen at the boundary.
Show a strong answer
Use period-specific keys. The season board is lb:{game}:season:12. When season 13 starts, new scores go to lb:{game}:season:13, so there is nothing to reset. The old key is kept for a while so players can view final standings, then expires.
Switch writes by timestamp, not by clock on the server. Each score event carries the match's end time, and the writer picks the season from it. A match that finished at 23:59:58 and was processed at 00:00:03 still counts in the old season.
Archive before expiry. Write the old board's final top 10,000 to durable storage for rewards and history, and compute the percentile table at the same moment.
Keep the all-time board untouched. Every event still updates it, so the rollover does not affect it.
The pattern worth keeping: make the period part of the key and the event, so a rollover is a new key, not a mass delete.
A streamer's fans flood the 'my rank' endpoint for their favorite player, 30,000 requests a second for one player ID. What do you do?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Look at what is the same across those requests and how long it stays correct.
Show a strong answer
It is a hot key. All requests read the same player's rank and neighbors. Cache the response in the API for one second, keyed by player, so 30,000 requests become one read per second per API instance.
Accept a second of staleness. A rank that is one second old is fine. For the owner's own view, bypass the cache so they see their update at once.
Collapse concurrent misses. When the cached value expires, let only one request recompute it and make the others wait for that result, so expiry does not release a burst of identical reads.
Rate-limit abusive clients. If a script is polling, a per-client limit protects the service without hurting normal users.
The pattern worth keeping: a very popular read of slowly changing data belongs in a short cache, with request collapsing at expiry.
Key takeaways
- Rank and top-K need an ordered, in-memory structure. Use a sorted set, not
ORDER BY. - Size memory first. 500M entries is about 50 GB, which drives sharding more than throughput.
- Shard by what you query in order: by score range for exact rank, with counts per bucket.
- Exact rank for the top, a percentile for everyone else.
- Events are the truth. The leaderboard is a rebuildable view.
- Put the period in the key, define ties and trust only game servers.
Further reading
- Redis documentation, "Sorted sets":
ZADD,ZRANK,ZRANGEand their complexity. - W. Pugh, "Skip Lists: A Probabilistic Alternative to Balanced Trees", Communications of the ACM (1990): the structure behind sorted-set ordering.
- Martin Kleppmann, "Designing Data-Intensive Applications", O'Reilly (2017), the chapter on partitioning.