CodingNodes Space play · ←→ step · R restart

The problem

A leaderboard is a set of (player, score) pairs ordered by score, and it has two operations that are both hot. One is an update: a player finishes a game and their score changes, so the ranking moves. The other is a query, and the query that matters most is not 'show me the top 100' — it is 'where am I, and who is immediately around me?' A player on a 5,000th place out of two million wants their rank and the names above and below them, not a list of strangers at the top.

A plain map of player to score answers both badly: an update is a write, but a rank query means sorting everyone, which is too slow to run millions of times a second. The fix is to keep the set sorted in an order-statistic tree, which answers both 'update' and 'rank of a given score' in logarithmic time. And the fix for scale is to split the score space into segments, each owned by a shard, so that a global rank is a small prefix-sum over the segment counts plus a local rank within the player's own segment. We will build the data model, the two hot operations, the order-statistic tree that makes both fast, the score-space sharding that makes a global rank cheap, the tie rule, and the windowing and update flow that make it real-time — and close the loop with one score that is updated, moves across a segment boundary, and is reflected in a player's rank and neighborhood.

Requirements

Functional — what it must do

  • Update: a player's score changes and the leaderboard reflects it, with the ordering and every rank that depends on it moving accordingly.
  • Rank: a player asks for their rank and the players around them, and the system returns their position plus a bounded set above and below, fast.
  • List: the system can return the top K players on a board, and the players within a score range.
  • Window: the system keeps separate boards for a daily window, a weekly window, and an all-time window, each with its own ordering.

Non-functional — how well it must do it

  • Latency: a rank query for a player in the middle of the board returns in single-digit milliseconds, not a sort of the whole board.
  • Throughput: the system absorbs a burst of score updates as many games finish at once — a peak hour is a spike of writes — without a query ever blocking on them.
  • Consistency: a player's rank is never negative or greater than the number of players, and a player's own rank is always consistent with the scores the system reports.
  • Scale: the board holds millions of players and the rank query stays logarithmic in the board size, not linear in it.

Scale — how much it must take

  • On the order of millions of players per board, with a peak of a high share of those players updating their score in a short window, and rank queries at a fraction of a percent of the players per second, sustained.

Assumptions — the numbers this design is sized for

A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.

Players/board
millions
The ranking set. The rank query must stay logarithmic in this, not linear.
Update burst
a peak-hour spike
Many games finish at once, so writes arrive in bursts. Reads must not block on them.
Hot query
my rank + neighborhood
Not the top 100 — a mid-board player wants their position and a bounded set around them.
Query latency
single-digit ms
A rank query in the middle of the board. A sort of the whole board cannot meet this.
Windows
daily · weekly · all-time
Three boards, each a separate ranking over the same players with their own scores.
Ties
many, at the same score
Gaming scores cluster; the tie rule must be deterministic and total so the ordering is a well-defined one.

Takeaways

Part 1

Two hot operations

A leaderboard is a ranked set. It has two operations, both hot: an update (a score changes) and a rank query (where am I, and who is around me). The map answers both badly; the sorted structure answers both well.

  1. 1
    The query that matters is not the top 100

    The tempting read is 'give me the top 100', and it is easy. But the query a player actually fires is 'where am I, and who is immediately above and below me?' A player at 5,000th place out of two million does not care about the names at 1st and 2nd; they care about their rank and the handful of players around it. That query — a rank of a specific player plus a bounded neighborhood — is the one that has to be fast, and it is the one a naive design gets wrong, because it forces a sort of the whole board to answer a question about one point in it.

  2. 2
    Update and query, both hot

    The two operations are both on the critical path. The update is a write: a player's score changes, and the ranking moves, which changes the rank of every player who was above or below the crossing point. The query is a read: a player asks for their rank and a neighborhood. A leaderboard is judged on doing both at high rates at once — a peak hour is a burst of updates interleaved with a steady stream of rank queries — so the data structure has to make both cheap, not just one of them. A structure that is fast to write but slow to query, or the reverse, fails one of the two hot paths.

Part 2

The data model: a board of ranked pairs

A board is an id and a window. Its contents are (player, score) pairs, and the board is their set ordered by score. The order is the product; the pair is the unit; the window is what separates the daily board from the weekly one.

  1. 1
    A pair, an order, a window

    The unit of a leaderboard is a pair: a player and their score on this board. The product is the order: the set of pairs sorted by score, highest first, with a deterministic tie-break so that two players at the same score have a well-defined, stable order. The window is the scope: the same player appears on the daily board with their daily score, on the weekly board with their weekly score, and on the all-time board with their lifetime score. The three boards are three separate rankings over the same players, and a change to a player's score on one board does not touch the others.

  2. 2
    Why a total order, not a partial one

    Scores cluster — many players finish at exactly the same score — so 'sorted by score' alone is not a total order. If it is not total, then 'the player just below me' is ambiguous, and the neighborhood query is ill-defined. The fix is to make the order total: sort by score, and break ties by a stable secondary key, such as the time the score was first achieved, or the player id. Once the order is total, every player has a unique rank and a well-defined neighborhood, and the query has one correct answer.

Part 3

The map is wrong, the tree is right

A player-to-score map is fast to update but a rank query means sorting everyone. An order-statistic tree keeps the set sorted, so both an update and a 'rank of this score' are logarithmic. It is the one structure that makes both hot operations cheap.

  1. 1
    The map answers the query badly

    The naive design is a map from player to score. An update is an O(1) write, which is fine. But a rank query — 'how many players are above me?' — requires counting every player with a higher score, which means touching the whole map, and a neighborhood query means sorting the whole board to find the players around a given score. At millions of players, that is a linear or worse operation on every query, and a steady stream of those will drown the system. The map is fast on the write and slow on the read, and the read is the one that must be fast.

  2. 2
    The order-statistic tree

    The fix is to keep the set sorted in an order-statistic tree: a balanced binary search tree over the total order, where each node also stores the size of its subtree. That one extra number is what changes everything. 'Rank of a given score' becomes a walk down the tree, accumulating the sizes of the subtrees that are strictly higher, in O(log N). 'The K players above me' is a bounded range query over the sorted order, in O(log N + K). And an update — remove the old pair, insert the new one — is two tree operations, in O(log N). One structure, and both hot operations are logarithmic.

  3. 3
    The ranked set, made concrete

    Concretely, the board's state is a sorted set of (score, tie-key, player) triples. The top of the set is the 1st place, and each step down is one rank. A player's rank is their index in this set, and their neighborhood is a window of that index. The tree is just the data structure that makes 'index of this triple' and 'the window around it' both cheap, without ever sorting the whole set. The set is the product; the tree is the mechanism.

Part 4

The rank query, decomposed

A rank query asks for a player's rank and a bounded neighborhood. In a single tree that is one logarithmic walk. Across a sharded board it is a small prefix-sum over the segment counts plus a local rank within the player's own segment — and both halves are cheap.

  1. 1
    Rank is a count, neighborhood is a range

    Two things decompose the query. The rank of a player is a count: the number of players strictly above them, plus one. In a single order-statistic tree that is one walk down the tree, accumulating the sizes of the subtrees that are strictly higher. The neighborhood is a range: the bounded set of players immediately above and below them, which is a range query over the sorted order, bounded by K. Both are logarithmic-plus-K in the tree, which is why the query is fast even for a player in the dead middle of the board.

  2. 2
    The neighborhood is bounded, by design

    The neighborhood query must be bounded — 'the 10 above and 10 below me' — not 'everyone above me'. An unbounded 'everyone above' is a prefix of the order and is as large as the board itself, which defeats the purpose. A bounded neighborhood is a small, fixed-size answer, and it is what a player actually wants to see: their rank, and the handful of names that surround it. Bounding the query is not a limitation; it is the contract that makes the operation cheap and the answer useful.

  3. 3
    A rank that is never wrong

    Because the order is total and the rank is a count over that order, the answer is deterministic and always consistent: a player's rank is at least 1, at most the number of players, and equal to one plus the number of players strictly above them. There is no off-by-one, no 'rank greater than the population', and a player who queries twice in a row without any update in between gets the same answer. That consistency is not a special guarantee; it falls out of the rank being a count over a well-defined total order.

Part 5

Sharding by score space

A single tree over millions of players does not fit one node, and a global rank across nodes is expensive. The fix is to split the score space into segments, each owned by a shard: a global rank is a prefix-sum over the segment counts plus a local rank within the player's own segment.

  1. 1
    The score space, not the players, is sharded

    The tempting shard key is the player id, but that does not help a global rank: a player's rank depends on everyone with a higher score, and those are scattered across shards, so the rank becomes a distributed aggregation. The better key is the score. The score space is split into contiguous segments — a low range, a mid range, a high range — and each segment is owned by a shard. A player belongs to the segment of their current score, so the 'everyone above me' set is exactly the segments above mine, plus the players above me within my own segment. The shard boundary follows the score, which is exactly what the rank query needs.

  2. 2
    A global rank is a prefix-sum plus a local rank

    With the score space sharded, a global rank is two cheap pieces. The first is the prefix-sum: the total number of players in all segments strictly above the player's own segment, read from a small per-segment count array. The second is the local rank: the number of players above the player within their own segment, answered by that segment's order-statistic tree in O(log N). The global rank is the sum of the two, plus one. The prefix-sum is over a small number of segments, not over millions of players, so it is cheap, and the local rank is logarithmic. Together, a global rank is a small addition plus a logarithmic query.

  3. 3
    The update that crosses a boundary

    The one non-local operation is an update that moves a player from one segment to another — their new score falls in a different range than their old one. That update removes the player from their old segment, inserts them into the new one, and adjusts the two affected entries of the count array. Everything else — a score change that stays within a segment — is a purely local tree operation. So the sharding is cheap for the common case and only occasionally touches the count array, and the count array is the single shared state that makes a global rank a small sum.

Part 6

Windows and the real-time flow

A player's score on the daily board is not their lifetime score. Each window is a separate board with its own scores and its own ordering, and the update flow must write to the right board and keep the order current as scores change.

  1. 1
    Three boards, three orderings

    The daily, weekly, and all-time boards are three separate rankings over the same players, each with its own score and its own order. A player's daily score is their best or their sum on the current day; their weekly score is over the current week; their all-time score is their lifetime total. A change to the daily board does not touch the weekly or the all-time, and a player can be 50th daily but 5,000th all-time. The window is what makes the three boards different, and it is the reason a 'update' is really an update to one specific board, not to the player's score in general.

  2. 2
    The update flow, board by board

    When a game finishes, the system decides which boards the new score affects — the daily board always, the weekly board if the week is still open, the all-time board always — and applies the update to each of those boards. Each update is a local remove-and-insert on that board's tree, or a cross-segment move with a count-array adjust if the score crossed a boundary. The client then sees the new rank either by polling for a change or by a push of the rank delta. The flow is: game ends, validate the score, update the affected boards, and let the client see the new rank.

  3. 3
    Ties and the push of a rank change

    Because scores cluster, a batch of players at the same score move together when a new score is inserted among them, and their ranks all shift by the same amount. The system does not recompute every one of those ranks eagerly; it notes that a range of ranks has shifted by a delta, and a client that asks for its rank is told the delta. A player who was 50th and is now 52nd after two players inserted above them does not need a full re-sort — they need the delta. That is the real-time part: the order is maintained continuously, and a client's rank is the maintained order plus any pending deltas.

★ Finale

End to end

One score's life on the board: a game ends, the score is validated, the player is removed from their old position and inserted at their new one — crossing a segment boundary along the way — and the count array and the local tree are both updated, so the player's rank and neighborhood reflect the change, and the clients that care are told the delta.

  1. 1
    The whole system

    Every piece in one frame. A finished game produces a score; the leaderboard API validates it and decides which boards it affects; the score-space is split into segments, each owned by a shard with its own order-statistic tree; and a small count array holds the per-segment totals. A rank query is a prefix-sum over the count array plus a local rank in the player's segment. An update is a local remove-and-insert, or a cross-segment move with a count-array adjust. One score, one rank, always consistent.

  2. 2
    A score, validated and placed

    A game ends and produces a new score for a player. The API validates it — it is in range, it is from a trusted game server, and it is for an open window — and decides it belongs on the daily and all-time boards. The player's old position is removed from the tree, and the new position is inserted. If the new score stays in the same segment, that is a purely local operation. The order is updated, and the player's rank and neighborhood are now the correct ones for the new score.

  3. 3
    Crossing a boundary, and the count array

    Now the new score is high enough that it falls in a different segment than the old one. The player is removed from their old segment, inserted into the new one, and the two affected entries of the count array are adjusted. The prefix-sum is now correct: the number of players in segments above the player's new segment is the right value, and the local rank within the new segment is the right value. A global rank computed from the two is the player's true rank on the board, after the crossing.

  4. 4
    The rank and the neighborhood, correct

    A client asks for the player's rank and neighborhood. The system reads the prefix-sum from the count array, reads the local rank from the player's segment tree, adds them, and returns the rank plus the bounded set above and below. Every number is consistent: the rank is at least 1, at most the population, and equal to one plus the count of strictly-higher players. And the clients that had the player at the old rank are told the delta, so their view updates without a full re-sort. The board is correct, current, and cheap to read.

🌐 In the wild

In the wild

Leaderboards are a core feature of every competitive game. The boxes below are anchored to the classes of well-known systems that run each piece — an illustrative mapping, not a claim about any one product's internals.

  1. 1
    The pattern, piece by piece

    Each box is a standard building block of a leaderboard. Anchoring them to the classes of production systems that run that piece turns the abstract design into the shape behind the 'you moved up two places' notification a player sees the moment a game ends.

  2. 2
    Why the same pieces keep winning

    Independent leaderboards converge on the same pieces because each one removes a real failure: the sorted tree removes the sort-the-whole-board failure, the total-order tie rule removes the ambiguous-rank failure, the score-space sharding removes the expensive-distributed-rank failure, the count array removes the full-aggregation failure, and the delta push removes the re-sort-the-clients failure. That convergence across independent systems is the evidence the design is load-bearing.