Design a Real-Time Leaderboard
Millions of players finish matches every minute, and each one wants to see the top ten and their own rank right now. This lesson designs that leaderboard: an in-memory sorted set that updates in logarithmic time, a durable score log behind it, rank and neighbour queries, sharding when one machine is not enough, approximate ranks for the long tail, daily and weekly boards, ties and protection against cheaters.
What you will learn
- Sorting the whole table on every request does not scale; keep the scores already sorted.
- A sorted set (a skip list plus a hash map) gives update, rank and top N in logarithmic time.
- Keep the durable truth in a database or log, and treat the in-memory board as rebuildable.
- Shard by score range for exact ranks, or by player with merging for the top N.
- Most players only need an approximate rank; a histogram of score buckets gives it cheaply.
- Validate scores on the server; a leaderboard is only worth what its scores are worth.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: The API
- Step 4: Why the obvious approach fails
- Step 5: Sorted sets
- Step 6: The high-level design
- Step 7: My rank and my neighbours
- Step 8: Scaling past one machine
- Step 9: Approximate ranks for the long tail
- Step 10: Time windows, resets and ties
- Step 11: Friends leaderboards
- Step 12: Cheating and validation
- Step 13: One match, end to end
- Step 14: Failures and recovery
- Step 15: The follow-up questions
- Recap
The question
Welcome to lesson twenty-one of the system design course. Today's question is: design a real-time leaderboard. The interviewer says: design a leaderboard for a game that updates instantly for millions of players, and shows each player their own rank.
Leaderboards are everywhere. Mobile games with weekly tournaments. Fitness apps ranking your steps against friends. Coding contests with a live scoreboard. Sales teams with a monthly target board. The shape is always the same: lots of score updates, and two questions asked constantly. Who is on top? And where am I?
The first question, the top ten, is easy. The second one is the interesting one. Telling a player that they are ranked one million, two hundred and thirty-four thousand and fifty-six, out of fifty million, exactly and instantly, is surprisingly hard to do with an ordinary database.
That makes this a lovely interview question, because it is small enough to finish in forty-five minutes, but it has a real data structure at its heart. If you explain that data structure well, you stand out.
As always, we go step by step: requirements, estimates, the API, why the obvious approach fails, the right data structure, scaling it, time windows, ties, cheating, failures and the follow-up questions. Let us start.
Step 1: Clarify the requirements
- 01Update scoreafter each match, add points
- 02Top Nshow the top 10 to 100 players
- 03My rankexact rank and score for any player
- 04Neighboursthe players just above and below me
- 05Time windowsmonthly board, maybe daily and all-time too
- 06Friends boardrank among my friends
Start with what it does. When a player finishes a match, their score changes. Ask: is the leaderboard score the best single match, or the total of all matches this week? Let us say the total points this month, which is common for tournaments. The board resets at the start of each month.
Three read queries matter: the top ten, my rank, and my neighbours, say the five players above and below me, which is what keeps people playing: I am only twelve points behind that person. A friends leaderboard is a nice extra; confirm whether it is in scope.
- 01Freshnew rank visible within about a second
- 02Fast readstop N and my rank under 50 ms
- 03Exact at the topapproximate is often fine in the long tail
- 04Durablenever lose a score
- 05Fairscores validated on the server
Non-functional requirements. Real time: after a match, my new rank should show within a second or two. Highly available: the game should not break if the leaderboard is slow, so score updates must not block the game. Accurate: ranks for the top players must be exact; for the long tail, ask whether approximate is acceptable.
That approximate question is a great one to ask. Does a player ranked forty million really need to know they are forty million and twelve, rather than around forty million? Often the product team says: exact for the top hundred thousand, approximate below. Keep that in your pocket; it will make scaling much easier later.
Step 2: Back-of-the-envelope estimates
Let us size it. Fifty million monthly players, ten million daily. Each daily player finishes about ten matches a day, so a hundred million score updates a day. That averages about twelve hundred per second, with peaks of maybe five thousand in the evening.
Reads are higher than writes. After every match, the player looks at their rank, and many players open the board without playing. Say ten times the update rate: fifty thousand reads per second at peak.
Memory: each entry is a player id and a score, plus the overhead of the sorted structure, say a hundred bytes in practice. Fifty million entries is about five gigabytes. That fits comfortably in one machine's memory. Remember this: the whole board fits on one server. That is a big hint about the design.
We also keep every score event in a durable log, for audits and for rebuilding. A hundred million events a day at about a hundred bytes is ten gigabytes a day. Cheap to store.
Step 3: The API
POST /v1/scores (game servers only)
{ player_id, match_id, points, board: "2026-11" }
GET /v1/boards/2026-11/top?n=10
→ [ { rank, player_id, name, score } ]
GET /v1/boards/2026-11/players/{id}
→ { rank, score, total_players }
GET /v1/boards/2026-11/players/{id}/around?k=5
→ 5 above, me, 5 belowThe API mirrors the requirements. The game server, not the player's phone, posts a score event with the match id. The match id doubles as an idempotency key, so a retried request does not add points twice.
Why must scores come from the game server? Because anything the phone sends can be faked. A player could post a score of a billion. The game server ran the match, so it knows the real result, and it signs or authenticates its request. We will come back to cheating at the end.
Reads come from players: top N, my rank, and around me. Each board has a name, like twenty twenty-six, November, so daily, monthly and all-time boards use the same API with a different board name.
Step 4: Why the obvious approach fails
SELECT player_id, score FROM board ORDER BY score DESC LIMIT 10; -- fast with an index SELECT COUNT(*) + 1 FROM board WHERE score > (SELECT score FROM board WHERE player_id = ?); -- counts every row above me: O(n)
The obvious design is a table of player and score, with an index on score. The top ten is: order by score descending, limit ten. With the index, that is fast. So far, so good.
Now my rank. My rank is one plus the number of players with a higher score. The database has to count every row above me. For a player in the middle, that is twenty-five million rows. Even walking an index, counting twenty-five million entries takes seconds, and we need fifty thousand of these per second.
Caching does not help much either. Ranks change constantly: every score update shifts the rank of everyone it passes. A rank cached a minute ago is wrong for millions of people. And recomputing all ranks every minute with a big sort is too slow and still not real time.
So we need a structure where finding a rank is cheap: not proportional to the number of players, but to the logarithm of it. Say that sentence in the interview: the problem is counting, and we need counting in logarithmic time.
Step 5: Sorted sets
| Operation | What it does | Cost |
|---|---|---|
| increment(player, points) | add points, re-position | O(log n) |
| rank(player) | how many are above me | O(log n) |
| range(0, 9) | top 10 | O(log n + 10) |
| range(r - 5, r + 5) | my neighbours | O(log n + 10) |
| score(player) | look up by id | O(1) |
The right structure is a sorted set. Many in-memory data stores provide one. It keeps members ordered by score and supports: add or increment a score, get the rank of a member, and get members by rank range. Each operation takes time proportional to the logarithm of the size.
How does it work inside? Usually two structures together. A hash map from player to score, so looking up a player is instant. And a skip list ordered by score. A skip list is a linked list with express lanes: each node is in the bottom lane, about half are also in the next lane up, a quarter in the next, and so on. To find a position you start in the top lane and drop down, like taking an express train then a local one.
The trick that gives ranks: each express link stores how many nodes it skips over. As you walk down to a player, you add up the skip counts along the way, and that sum is the player's rank. So rank, which took twenty-five million steps in the database, takes about twenty-five steps here.
A balanced tree that stores subtree sizes, called an order statistic tree, gives the same result. You can mention either. The point is the same: keep counts in the structure, so counting does not need scanning.
With fifty million players, each operation is roughly twenty-six steps, and one server can do a hundred thousand or more of these per second. Our peak is five thousand updates and fifty thousand reads per second. One sorted set on one machine handles our whole monthly board. Then we add replicas for reads and availability.
Step 6: The high-level design
Here is the architecture. Game servers send score events to a score service, which validates them and appends them to a durable event log.
From the log, two consumers. One writes the total per player and board into a database, the durable truth. The other, the board updater, increments the player's score in the in-memory sorted set.
Players read through a rank service, which calls the sorted set replicas for the top N, a rank and neighbours, and joins in player names and avatars from a profile cache.
Why the log in the middle? It decouples the game from the board. If the sorted set is slow or restarting, score events wait safely in the log, the game is unaffected, and the board catches up in seconds. And if the in-memory board is ever lost, we rebuild it from the database totals, or by replaying the log.
The update path takes a few milliseconds through the log and a sub-millisecond increment. So a player sees their new rank about a second after the match ends, which meets our freshness target.
Step 7: My rank and my neighbours
top 10: range(board, 0, 9, desc) # cache 1 s
my rank: r = rank(board, me, desc) + 1
s = score(board, me)
neighbours: range(board, r - 6, r + 4, desc)
total: size(board)
names: batch lookup in profile cacheLet us go through the reads. Top ten: a range query on ranks zero to nine, highest first. It is so popular that the rank service caches it for one second; at fifty thousand reads per second, that cache saves almost all of the load for the top ten.
My rank: ask the sorted set for the rank of my player id, in descending order, and add one because ranks start at zero. Also get my score and the total number of players, so the app can say: you are rank two thousand and ten out of fifty million, top one percent.
Neighbours: once you know my rank, fetch the range from five above to five below. That is the screen that shows: you are twelve points behind someone, play one more match. Product teams love it, and it costs just one range query.
Then join names and avatars. The sorted set only holds ids and scores, to keep it small. The rank service looks up the ten or eleven profiles in a cache, in one batch call. Never store names in the sorted set; a name change would mean rewriting the board.
Step 9: Approximate ranks for the long tail
bucket (score range) players
10,000+ 812
5,000 - 9,999 41,230
1,000 - 4,999 1,902,114
...
approx rank(score) = players in higher buckets
+ position estimated inside my bucketHere is the trick that makes huge boards cheap. Remember we asked whether the long tail needs exact ranks. Suppose it does not. Then keep exact ranks only for the top hundred thousand players in a sorted set, and for everyone else use a histogram.
The histogram counts how many players fall into each score bucket. When a score changes, decrement one bucket and increment another: constant time. To estimate my rank, add up the buckets above mine, and estimate my place within my bucket, assuming players are spread evenly inside it.
With a few thousand buckets, the error is tiny relative to the rank. Telling someone they are around rank twelve million, or in the top forty percent, is just as motivating as the exact number, and it costs a few kilobytes instead of gigabytes.
So the final design for a very large game is a hybrid: an exact sorted set for the top of the board, where every place matters and people compete for position, and a histogram for everyone else. This is the kind of product-aware trade-off that impresses interviewers.
Step 10: Time windows, resets and ties
- 01One set per windowdaily, weekly, monthly, all-time
- 02Resetnew window = new empty set; old one archived
- 03Final standingssnapshot to the database at window end
- 04Tiesearlier achiever ranks higher
- 05Encode tiesscore × 10^10 + (max_time - achieved_at)
Boards have time windows: daily, weekly, monthly, all-time. Keep a separate sorted set per window, named by the window, like November twenty twenty-six. A score event increments every active window's set. At the start of a new month, the new month's set simply starts empty.
At the end of a window, snapshot the final standings into the database for prizes and history, then expire the old set from memory after a few days. No big reset job, no downtime: a new month is just a new key.
Ties need a rule, and the interviewer will ask. A common rule: if two players have the same score, the one who reached it first ranks higher. Sorted sets sort by a single number, so encode both into one: the score, shifted left, plus a value that is bigger for earlier times. Then normal sorting gives the tie rule for free.
Show the encoding: score times ten to the power ten, plus the maximum timestamp minus the time the score was achieved. Earlier achievement gives a bigger remainder, so a higher rank. Divide to get the displayed score back. Small trick, but it shows care.
Step 11: Friends leaderboards
A friends leaderboard ranks me among my few hundred friends. It looks similar, but the right design is completely different. Building a sorted set per player, for every combination of friends, would be millions of small sets, all updating every time anyone plays.
Instead, compute it on read. Fetch my friend list, a few hundred ids, then fetch their scores in one batch from the hash map side of the sorted set, which is a constant-time lookup each. Sort a few hundred numbers in memory. That takes a millisecond.
Cache the result for a few seconds per player, because people open this screen repeatedly. And for players with thousands of friends, cap it at the most active few hundred. The general lesson is worth saying: big global rankings are precomputed, small personal ones are computed on read.
Step 12: Cheating and validation
- 01Server authorityonly game servers submit scores
- 02Sanity checksmax points per match, max matches per hour
- 03Match idseach counted once; replay detection
- 04Anomaly reviewsudden jumps flagged for review
- 05Hold before topnew top 100 entries verified before shown
A leaderboard is only worth something if the scores are real. If anyone can post any score, the top ten fills with impossible numbers within an hour of launch, and honest players leave.
First line: the client never submits scores. The game server, which ran the match, does, with its own credentials. Second: sanity limits. No match can give more than a certain number of points, and nobody plays two hundred matches an hour. Out-of-range events are rejected and logged.
Third: each match id counts once, enforced by the score service, so replaying a winning match's request gains nothing. Fourth: an anomaly job watches for players whose scores jump unusually fast and flags them for review. A flagged player can be hidden from the public board while the review happens.
Some games add one more rule: a new entry in the top hundred is verified, perhaps by checking the match replay, before it is shown publicly. The top of the board is the most visible and the most attacked, so it gets the most protection.
Step 13: One match, end to end
Let us follow one match through the system. At nine in the evening, a player finishes a match and earns three hundred and forty points. The game server, which hosted the match, sends a score event: player id, match id, three hundred and forty points, board November.
The score service checks the request is signed by a real game server, checks three hundred and forty is within the limit for this game mode, and checks this match id has not been counted before. It appends the event to the score log and returns in a few milliseconds. The game server moves on; it never waits for the board.
Two consumers read the event. One adds three hundred and forty to the player's total row in the database, recording the match id. The board updater increments the player's entry in the November sorted set, and in the daily and all-time sets too. The skip list unlinks the player's node and relinks it about twenty-six steps higher up the order, updating the skip counts on the way.
Meanwhile, the player's app shows the match result screen and asks the rank service: what is my rank, and who is around me? The rank service asks a replica, which received the increment a few milliseconds ago. The answer comes back: rank eighty-one thousand and four, up from ninety-two thousand, and you are now six points behind the next player. The app shows a little arrow going up.
Total time from match end to new rank: well under a second. And if anything had failed along the way, a slow updater or a replica restart, the event would have waited in the log, the game would not have noticed, and the board would have caught up a few seconds later. That is the design working as a whole.
Step 14: Failures and recovery
What if the sorted set primary dies? A replica takes over. It may have missed the last few increments, but the board updater tracks its position in the score log, so it replays from slightly before the failure. Because increments are not idempotent, the updater records the last applied match id per player, and skips duplicates.
What if we lose all copies of the board? Rebuild it from the database totals: read fifty million rows and load them into a new sorted set. At a few hundred thousand inserts per second, that takes a few minutes. During those minutes, show the board from the last snapshot with a note that it is updating. The game keeps working, because scores keep flowing into the log.
And monitor the lag between the score log and the board: how many seconds behind is the board? If it grows past a few seconds, players see stale ranks, which is what they will complain about first. Also compare totals between the board and the database every hour, to catch drift early.
Step 15: The follow-up questions
Now the follow-up questions interviewers like to ask.
Max asks
“Why not just use the database with a cache?”
Because rank needs counting, and ranks change for millions of players on every update. A cache of ranks goes stale immediately, and recounting in the database is linear. The sorted set keeps counts inside the structure, so a rank costs logarithmic time and is always current.
Max asks
“How would you show the top players by country?”
A sorted set per country and window, updated alongside the global one. A score event increments two sets instead of one. Country boards are smaller, so they are cheap. The same applies to any segment, like region or skill tier, as long as the number of segments is modest.
Max asks
“What if the score is the best single match, not a total?”
Then the update is a maximum, not an increment: set the score only if the new one is greater. Many sorted sets support an only-if-greater option. Everything else stays the same.
Max asks
“How do you handle a player who deletes their account?”
Remove them from every active sorted set and the database, and from archived final standings if the privacy rules require it. Ranks of everyone below shift up by one automatically, because ranks are computed, not stored.
Max asks
“How would you push rank changes to players in real time?”
Do not push every change to fifty million people. Push only meaningful events: you entered the top hundred, a friend passed you. The app polls its own rank when the board screen is open. Push is for moments, polling is for screens.
Max asks
“How much does all of this cost to run?”
Very little. The monthly board is about five gigabytes of memory, so one primary and two replicas of a modest memory-optimised machine. The log and database are small. The expensive part of a game is the game servers, not the leaderboard, which is a good thing to say when the interviewer asks you to justify your choices.
Recap
- 01Sorted setupdate, rank, top N in O(log n)
- 02Durable logboard is rebuildable
- 03Readstop N cached 1 s, rank, neighbours
- 04Shardingby score range for exact ranks
- 05Approximatehistogram for the long tail
- 06Honest scoresserver authority and checks
Let us recap. The obvious database approach fails because a rank means counting everyone above you. A sorted set, a skip list with skip counts plus a hash map, makes update, rank, top N and neighbours all logarithmic.
Put a durable score log and a totals table behind it, so the in-memory board can always be rebuilt. Fifty million players fit on one machine; beyond that, shard by score range, or use a histogram for approximate ranks in the long tail.
Use one set per time window, encode ties into the score, compute friends boards on read, and validate every score on the server.
The moment that wins this interview is explaining why rank is a counting problem, and how the skip list counts as it walks. Practice that explanation out loud with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson twenty-two.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.