Design a leaderboard
Read first: Caching, Partitioning and sharding
Keep players in a structure ordered by score so a top-ten read touches a handful of nodes and an update costs a logarithmic rewrite. Sorting tens of millions of rows on every view does not finish. A cached top ten that ignores a score crossing the boundary shows the wrong names until the TTL happens to end.
A leaderboard is a sorted view of a number you already have. The ways it fails are both about that order. Recomputing it from scratch on every read burns the whole population to paint ten names. Caching the ten names and letting them go stale paints the wrong ten. The fix is to pay a small cost on the write, keep the order, and refresh the cached board when a score actually crosses it.
Requirements
The user is a player who just finished a match, wants to see the top ten, and wants to know their own rank. A second, smaller view is the top ten among friends.
Functional requirements:
- Apply the result of a match to a player’s season score, once.
- Read the top K of a board. K is 10 or 100, not the whole population.
- Read one player’s rank and score.
- Read a friends board for a list of about a hundred ids.
Non-goals:
- Anti-cheat, replay files, and matchmaking. The server that records the match is the authority for the score. The client does not get to POST a new total.
- A social graph. Friends are an id list from another service.
- Exact rank for every player pushed to every client in real time. The player who opened the board asks. Everyone else does not.
Estimation
Assumptions:
- 30 million players have a score this season.
- 5 million daily active players.
- Each plays 5 scored matches a day, so 25 million score events a day.
- Each daily player opens a board 12 times, so 60 million board reads a day.
- Peak is 5× the average, for a Friday night. The 5× is an assumption.
- A player record in the sorted structure is 64 bytes: ids, score, a tie-break, and tree overhead rounded up. That 64 is an assumption so the memory math is visible.
updates / day 5e6 * 5 = 25e6
average 25e6 / 86,400 ≈ 289 / s
shortcut 25e6 / 1e5 = 250 / s
peak, 5× ≈ 1,450 updates / s
reads / day 5e6 * 12 = 60e6
average 60e6 / 86,400 ≈ 694 / s
peak, 5× ≈ 3,470 reads / s
memory 30e6 * 64 B = 1.92e9 B ≈ 1.9 GB
A day is 86,400 seconds. The shortcut says 250 updates a second and the real day says about 289. Either way the write rate is modest, and 1.9 GB fits in memory on one machine. Say so. This is not a storage-capacity problem. It is an algorithm problem that becomes a capacity problem if you pick the wrong algorithm.
Friends, used later: assume 100 friends on the list you are asked to sort. That number stays small even when the global board does not.
High-level design
Match results come in with a match id. The score service applies each match once and updates a balanced tree ordered by score, with a map from player id to that player’s node so an update does not have to search by scanning. The top ten is a cached projection of the high end of the tree. A player’s own rank is a count of how many nodes sit strictly above them, which the tree can answer if each subtree remembers its size. Friends are a point read of those ids and a sort in memory.
flowchart LR
player[Player]
api[Score API]
tree[Ordered score tree]
cache[Top ten cache]
rank[Rank lookup]
friends[Friends scores]
player --> api
api --> tree
tree --> cache
api --> rank
api --> friends
One season is one tree. Last season is a frozen snapshot you stop updating. Partitioning is optional at 1.9 GB and 1,450 writes a second. It becomes real when a single tree’s write rate no longer fits, and the deep dive says what remains correct after you split.
Deep dive
The top ten that sorts on every read
The wrong read path is “load the players, sort by score, take ten” or the same plan hiding in a query that cannot use an ordered index. Comparison count is about N log₂ N. log₂ of 30 million is about 25, because 2^10 is about a thousand, 2^20 is about a million, and 30 million is a little under 2^25.
comparisons 30e6 * 25 = 7.5e8
one core 2e8 comparisons / s (assumption, a tight loop, not a spec sheet)
one full sort 7.5e8 / 2e8 = 3.75 s
peak reads 3,470 * 3.75 s ≈ 13,000 core-seconds per wall second
Each reader waits seconds, and the cluster would need on the order of 13,000 cores to keep the sorts from piling up. The constant on the comparison rate can be off by 10× and the design is still absurd. You do not sort the population to paint ten rows.
An index or a tree already ordered by score does not do that work on the read. The write pays it. Moving one player from an old score to a new score is a delete plus an insert along a path of about 25 nodes. At peak:
write hops 1,450 * 25 ≈ 36,000 / s
top-ten reads 3,470 * 10 ≈ 35,000 node visits / s
That fits one process with the 1.9 GB tree resident. The top ten is the rightmost (or leftmost) K nodes, not a scan of 30 million. This is the whole trade. Update cost is logarithmic in N. Read cost of the board is proportional to K. Full recompute makes the read proportional to N log N, and N is the thing that grew.
A database with a real ordered index on score can serve LIMIT 10 from the end of that index. That is the same idea as the tree. The failure is the plan that sorts the heap or the files because nobody created the order, or a cache fill that sorts once and then keeps the result long after it is wrong. “We will just query it” is not an answer until you know the plan is an ordered top-K.
The top ten that is stale
Keep a cache of the ten names, the tenth score, and the generation of the tree you read. Caching with a TTL alone is the second failure.
A concrete board, tenth place at 4,200:
| Place | Player | Score |
|---|---|---|
| 8 | Imani | 4,280 |
| 9 | Jules | 4,240 |
| 10 | Nia | 4,200 |
Omar finishes a match and the tree applies 4,350. Omar belongs in the top ten, and Nia may fall off. For the next 30 seconds a TTL cache still shows Nia and hides Omar. Omar opens the board, does not see the result, and the support ticket is correct. The cache is not approximately right. It names the wrong people.
The refresh rule uses the boundary you stored:
- A new score strictly below the cached tenth does not touch the cache. The board cannot have changed.
- A new score at or above the tenth, or any update to a player who is already in the ten, recomputes the top ten from the tree and swaps the cache. That recompute is K nodes, the cheap read above, not the 3.75 second sort.
- A score decrease is the case a heap of size K cannot repair. If Nia drops from 4,200 to 4,000, someone outside the cache has to enter. A structure that only stored ten rows does not know who. The full tree does. Scores that only ever increase can live in a heap of size K. Penalties, corrections, and season edits decrease. Keep the tree.
TTL is still useful as a backstop if an invalidation is lost. It is not the correctness path. Invalidation is. A player who wants read-your-writes on their own score should read that score from the primary. The board they see should be the generation that includes their match if the match crossed the boundary, which it will if you refresh before you ack the match result that changed the ten.
Tie-break with a total order the tree owner assigns: higher score first, then earlier server sequence, then player id. A phone clock is a bad tie-break. Two devices with skewed clocks will swap places between reads. Clocks on the client do not order this board. The process that updates the tree does.
Rank, friends, and a split tree
Rank is “how many players have a strictly better key.” An order-statistic tree stores subtree sizes and answers in the same logarithmic walk as an update. The top-ten cache cannot answer “you are 482,211th.” If the product needs rank, the tree is the product, and the cache is only the board widget.
Friends are the opposite shape. One hundred ids, fetched by primary key, sorted in the request. One hundred log one hundred is noise next to the global tree. Materializing a board per player is the expensive twin of a news feed. At 100 friends and 1,450 updates a second you would write 1,450 × 100 = 145,000 friend-board rows a second, and a popular player makes their own spike. Pull the hundred scores on read. Push only if a friends list is huge and the read budget says so. It is not, under these assumptions.
When one tree no longer fits, partition by player id for the writes. Global top ten stays correct if each shard keeps its own ordered tree and a merger reads K from each shard and merges. Four shards produce 40 names. The best 10 of those 40 are the global best 10. That merge is wrong for rank if you add the ranks. Rank across shards is a sum of counts: each shard returns how many of its players beat score S, and you add P numbers. You do not scan 30 million rows, and you do not add “rank 10 on each shard” to get rank 40.
Apply a match id once. An increment replayed after a timeout adds the points twice. Store the match id on the player’s recent set, or as a row that is unique on match id, and treat a repeat as success with the old score. Idempotency here is “this match has been applied,” not “the client told us their new total.” A replica that lags will show an old rank. The player’s own score read goes to the primary or uses a version check, the same read-your-writes choice as any other replicated store.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Full ordered tree | Top K, rank, and score decreases stay correct | About 1.9 GB resident, and every update rewrites a path |
| Sort on every read | No extra structure | Seconds per read and tens of thousands of cores at peak |
| Cache the top ten with a TTL only | Very fast board reads | The wrong names until the TTL expires |
| Refresh the cache when a score crosses the tenth | The board matches the tree after a crossing update | Every crossing pays a small recompute before you ack |
| Heap of size K, scores only increase | Tiny memory | A decrease, or a request for rank, has no answer |
| Pull friends on read | Writes stay one update per match | The read fetches about 100 scores |
| Merge top K from shards | The global board survives a split | Rank becomes a sum of counts, a second query shape |
Failure modes
Dependency down. The tree process is down. Stop applying matches into a side cache that will later merge blindly, or you will double-apply when it returns. Queue match ids durably and let the board serve the last generation with a timestamp, or fail the board read. A wrong top ten presented as live is worse than a board that says it is paused. Friends can still be answered from the last durable scores if you accept staleness there.
Retry storm. Match-end clients retry the score post. Without the match id, Omar’s 4,350 becomes 8,700 and the board is fiction. With the match id, retries are a lookup. Bound them anyway. A sticky client at the end of every match is enough to double your 1,450 writes a second.
Hot partition. The global tree is one structure, and at these rates that is fine. It becomes a hot key if you also store the top ten as a single row that every match rewrites, including matches that do not cross the boundary. Do not do that. Update the player’s node. Rewrite the cached board only on a crossing. If you shard, a merger that recomputes by sorting full shard dumps has reintroduced the N log N read. Merge K per shard.
Consistency. The stale cache is the consistency bug the user sees: Nia still in tenth, Omar invisible, for the whole TTL. Replica lag on the player’s own score is the other one. A read-your-writes miss looks like a lost match. Cross-shard rank computed by adding per-shard ranks is a logic bug, not a lag bug, and it is wrong even when every shard is fresh.
Durability. The match-applied row and the score update commit together. Crash between “I applied the match” and “I changed the score” and a retry will skip a match that never landed, or land it twice, depending on which write you do first. One transaction. The cache is a projection. Losing it costs a recompute from the tree, which is cheap. Losing the tree costs a rebuild from the match log, which you should be able to do for the season. The cache is not the source of truth.
In the interview
First five minutes: 30 million players, about 1.9 GB, 289 updates a second average, peak near 1,450. Top ten comes from an ordered structure. The number that scares you is 3.75 seconds and about 13,000 cores if you sort on read. The tradeoff is write complexity you can afford, against a cache you must invalidate when the boundary moves.
Skip anti-cheat, animation, and a tour of sketch algorithms. Mention the sketch only if someone asks for an approximate board, and say the exact tree already fits.
The question that usually follows is “what if the cached top ten is 30 seconds old?” Walk Omar and Nia. The one after that is “how do I get my rank, and what if we outgrow one machine?” Subtree counts, then merge K for the board and sum counts for the rank.
Check yourself
Sorting 30 million players on every read takes about how long on one core under the lesson assumptions, and why does the peak make it worse?
About N log2 N comparisons, 30 million times 25, is 750 million comparisons. At an assumed 200 million comparisons a second, one sort is 3.75 seconds. Peak board reads are about 3,470 a second, so you would need on the order of 13,000 cores just to tread water, and every player would still be waiting on a multi-second sort.
Omar posts 4,350 while the cached tenth, Nia, is at 4,200 with a 30 second TTL. What does the board show, and what should happen instead?
Until the TTL ends, the board still shows Nia and does not show Omar. That is the bug. The new score is above the cached boundary, so you recompute the top ten from the ordered tree and replace the cache before you treat the match as visible. A score below 4,200 would leave the cache alone.
Why does a heap that stores only the current top ten fail when a score decreases?
If someone in the ten drops below the boundary, a player who was eleventh has to enter, and the heap never stored them. Monotone increases can be maintained by evicting the minimum when an outsider crosses it. Corrections and penalties are not monotone. The full ordered tree knows who the new tenth is.
You split players across four shards. How do you answer global top ten, and how do you answer a global rank?
Ask each shard for its own top ten and merge forty names down to ten. That is exact. Rank is the sum of four counts of players above the score, not the sum of four local ranks. Adding ranks double-counts the people ahead on other shards in a way that does not mean anything.
A match-end request times out and the client sends it again. How does the score stay correct?
The match id was stored with the score change in one transaction. The retry finds the id and returns the score already applied. An increment with no id adds the points a second time, and the ordered tree will dutifully move the player to a score they did not earn.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.