Skip to content

Lesson 23 of 38Case studies

Design a Real-Time Leaderboard

Design a live game leaderboard with Redis sorted sets, fast rank queries, time-windowed boards, and server-side anti-cheat.

18 min read0/5 questions

Every competitive game, fitness app, and coding contest has a leaderboard, and players notice within seconds when theirs is slow or wrong. It is also a favourite interview question because the naive answer (ORDER BY score DESC) collapses at scale, and the good answer shows you know which data structure fits the job.

Requirements

Functional

  • When a match ends, the player's score goes up.
  • Show the global top 100.
  • Show a player's own rank ("you are #48,213").
  • Show the players near me (5 above, 5 below).
  • Separate daily, weekly, and all-time boards, per game mode and per region.

Non-functional

  • Real time: a new score shows up on the board within a second or two.
  • Rank lookups under 10 ms.
  • Scores must be trustworthy. A modified client must not be able to post a fake score.
  • Highly available. If the board is down, players get angry, but the game itself must keep working.

Out of scope: friends-only boards (we sketch them at the end), matchmaking, rewards payout.

Back-of-the-envelope numbers

Say the game has 50 million daily active players, and each plays 10 matches a day.

QuantityMathResult
Score writes50M × 10 / 86,400about 5,800/s (peak about 20,000/s)
Board readseach player checks the board about 20 times a dayabout 11,600/s (peak about 40,000/s)
Players on the all-time boardup to about 200 million
Memory per board entrymember name + score + index overheadabout 100 bytes
Memory for one 50M-player board50M × 100 Babout 5 GB

A single Redis node handles around 100,000 simple operations a second and comfortably holds tens of GB. So one board fits on one node, and the challenge is the number of boards (modes × regions × time windows) and the hot top 100.

Why a database is the wrong tool

The obvious SQL is:

SELECT COUNT(*) + 1 AS rank FROM scores WHERE score > (SELECT score FROM scores WHERE player_id = 42);

With an index on score, it still counts every row above you. If you are ranked 25 millionth, that is 25 million index entries scanned, for every rank lookup, 10,000 times a second. Ranking is the one query relational databases are bad at.

What you want is a structure that keeps players sorted at all times, lets you change one score in O(log n), and tells you a position in O(log n). That is a sorted set.

API

POST /v1/scores                       (called by the game server, not the client)
{ "match_id": "m_81f2", "player_id": "p_42", "points": 150 }
200 OK
 
GET /v1/boards/{board}/top?limit=100
200 OK  { "entries": [ { "rank": 1, "player": "ada", "score": 98210 }, ... ] }
 
GET /v1/boards/{board}/players/{player_id}?around=5
200 OK  { "rank": 48213, "score": 4410, "neighbours": [ ... ] }

{board} is a name such as ranked:eu:weekly.

Data model

Two stores, two jobs:

  • Redis sorted sets are the live leaderboard. Key per board, member is the player id, score is the points. For example lb:ranked:eu:daily:2026-10-20.
  • A database (Postgres or DynamoDB) is the source of truth: a match_results table with match_id (primary key, so a match cannot be counted twice), player_id, points, ended_at, plus a players table for names and avatars. If Redis is ever lost, you rebuild the boards from this.

Redis sorted sets, visually

A sorted set stores unique members, each with a score, always kept in score order. Under the hood it is a skip list plus a hash map, so updates and rank lookups are O(log n). Here are the commands you need, stepped through on a small board.

A sorted set, read highest first
ada 980
0
sam 870
1
leo 760
2
priya 650
3
cmd = ZADD lb 980 ada 870 sam ...

ZADD inserts members with scores. Redis keeps them sorted, so reading highest first is free. Index 0 is rank 1.

1/5

Since Redis 6.2 you can also write ZRANGE lb 0 2 REV WITHSCORES, and Redis 7.2 added ZREVRANK ... WITHSCORE to get rank and score in one call.

Quick check
A board holds 100 million players. Roughly how many steps does ZREVRANK take to find one player's rank?
Need a nudge? A hint rules out a wrong answer.

Here is the same idea in plain Python. A sorted list plus bisect (binary search) gives you O(log n) lookups; Redis uses a skip list so inserts are O(log n) too.

Pythonsorted_set.py
from bisect import bisect_left, insort class SortedSet: def __init__(self): self.score = {} # member -> score self.order = [] # (-score, member), so index 0 is the best def zadd(self, member, score): if member in self.score: self.order.remove((-self.score[member], member)) self.score[member] = score insort(self.order, (-score, member)) def zrevrank(self, member): return bisect_left(self.order, (-self.score[member], member)) def zrevrange(self, start, stop): return [(m, -s) for s, m in self.order[start:stop + 1]] def around(self, member, k): r = self.zrevrank(member) return self.zrevrange(max(0, r - k), r + k) lb = SortedSet()for name, pts in [("ada", 980), ("sam", 870), ("leo", 760), ("priya", 650), ("max", 540)]: lb.zadd(name, pts)lb.zadd("leo", 910) print("top 3:", lb.zrevrange(0, 2))print("leo rank:", lb.zrevrank("leo") + 1)print("near priya:", lb.around("priya", 1))
Output
Press Run (⌘ Enter) to see what happens.

High-level design

Step through a score being recorded, then a player opening the board.

Leaderboard architecture
Ingest (writes)Serving (reads)Game clientGame clientAPI gatewayAPI gatewayMatch server: authoritativeMatch serverauthoritativeScore svc: validatesScore svcvalidatesResults: KafkaResultsKafkaPersisterPersisterPostgres: match_resultsPostgresmatch_resultsBoard APIBoard APIRedis: sorted setsRedissorted setsTop-100: 1 s TTLTop-1001 s TTLHTTPSresultZINCRBYpublishINSERTZREVRANK

Write path. The match is played on our match server, which knows the real outcome. The client never sends 'my score is 9,000'.

1/7
Quick check
The leaderboard is read about 1,000x more often than any one player's entry changes. What do you cache in front of Redis?
Need a nudge? A hint rules out a wrong answer.

Deep dive 1: daily and weekly boards with TTL'd keys

You do not reset a daily board by deleting everyone at midnight. You start a new key each day and let the old one expire.

  • Key names include the window: lb:ranked:eu:daily:2026-10-20, lb:ranked:eu:weekly:2026-W43.
  • On the first write to a key, set EXPIRE a little past the window (for example, keep daily boards 2 days so "yesterday's winners" still works).
  • A score update writes to all relevant keys in one pipeline.
TypeScriptboard-keys.ts
function isoWeek(d: Date): string { const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate())); const day = t.getUTCDay() || 7; t.setUTCDate(t.getUTCDate() + 4 - day); const yearStart = new Date(Date.UTC(t.getUTCFullYear(), 0, 1)); const week = Math.ceil(((t.getTime() - yearStart.getTime()) / 86400000 + 1) / 7); return `${t.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;} function boardKeys(mode: string, region: string, at: Date): { key: string; ttlSeconds: number | null }[] { const day = at.toISOString().slice(0, 10); return [ { key: `lb:${mode}:${region}:daily:${day}`, ttlSeconds: 2 * 86400 }, { key: `lb:${mode}:${region}:weekly:${isoWeek(at)}`, ttlSeconds: 14 * 86400 }, { key: `lb:${mode}:${region}:alltime`, ttlSeconds: null }, ];} for (const k of boardKeys("ranked", "eu", new Date("2026-10-20T18:30:00Z"))) { console.log(`ZINCRBY ${k.key} 150 p_42` + (k.ttlSeconds ? ` (EXPIRE ${k.ttlSeconds})` : ""));}
Output
Press Run (⌘ Enter) to see what happens.

Deep dive 2: sharding and huge boards

Sharding means splitting data across several machines. Most boards are naturally separate: ranked:eu and casual:na are different keys, so Redis Cluster spreads them across nodes with no extra work. That covers sharding by game mode and region.

The hard case is one giant global board. Options, from simplest:

  1. One big sorted set on a large node with replicas for reads. 200 million entries is about 20 GB, which a single node can hold. Writes are still limited to one primary, around 100,000 a second, which is above our peak.
  2. Shard by score range (0–999 on shard A, 1,000–9,999 on shard B). Your global rank is your rank in your shard plus the sizes of all higher shards (ZCARD). Players move between shards as their score crosses a boundary.
  3. Approximate ranks for everyone outside the top tier. Keep exact sorted sets for the top 100,000 and a histogram of score buckets for the rest: "you are in the top 12%" is what a player ranked 30 millionth actually wants to see.
Quick check
You shard one global board by hashing player_id across 10 Redis nodes. What breaks?
Need a nudge? A hint rules out a wrong answer.

Deep dive 3: trust and durability

Anti-cheat. The rule is simple: the client never reports its own score. The authoritative match server computes results, signs them, and includes a unique match_id. The score service rejects anything that is impossible (more points than a match allows, a match shorter than physically possible) and anything already seen (the match_id primary key makes the write idempotent, meaning safe to repeat). Suspicious players are flagged for review rather than silently ranked.

Persistence. Redis can save snapshots (RDB) and an append-only log (AOF), but treat it as a fast index, not the record. Every result is written to Postgres through the queue. If a Redis node dies and its replica is behind, rebuild the affected boards by replaying match_results for the window.

Put it in order5 steps

Order what happens when a ranked match ends.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Bottlenecks, failures, and 10x scale

  • Hot key. The global top-100 key gets the most reads. The 1-second response cache and Redis read replicas fix it.
  • Redis node failure. Redis Cluster promotes a replica within seconds. A few writes may be lost; replaying recent match_results fixes them.
  • End-of-day spike. Everyone checks the daily board at reset. Prewarm the new daily key and the cached top 100.
  • Friends boards. Instead of one sorted set per friend group, read your friends' scores with ZMSCORE on the main board and sort the 200 results in the API.
  • 10x (500M players, 200,000 writes a second): many regional boards scale out for free on Redis Cluster; the global board moves to score-range shards plus approximate ranks below the top tier. Batch ZINCRBY calls per node to cut round trips.
Match the pairs0/5 matched

Match the need to the tool.

Choose an item, then its match on the other side.
ChallengeMedium

In-memory leaderboard

Build a tiny version of a Redis sorted set leaderboard.

  • add_score(player, points) adds points to the player's total (a new player starts at 0). Like ZINCRBY.
  • top(n) returns the best n players as (player, score) pairs, highest score first. Like ZREVRANGE 0 n-1 WITHSCORES.
  • rank(player) returns the player's 1-based rank (1 is the best), or None (null in TypeScript) if the player has no score.

Ties: when two players have the same score, the one whose name sorts first alphabetically ranks higher.

lb = Leaderboard()
lb.add_score("sam", 50)
lb.add_score("ada", 80)
lb.add_score("sam", 40)     # sam now has 90
lb.top(2)    →  [("sam", 90), ("ada", 80)]
lb.rank("ada")  →  2

In TypeScript the methods are addScore, top, and rank, and top returns [player, score] arrays.

Aim for add_score and rank faster than sorting every player on every call: keep the entries in sorted order and use binary search.

class Leaderboard: def __init__(self) -> None: # Keep a dict of totals and a list sorted by rank. pass def add_score(self, player: str, points: int) -> None: pass def top(self, n: int) -> list[tuple[str, int]]: pass def rank(self, player: str) -> int | None: pass
Key terms
sorted set
A collection of unique members, each with a score, kept in score order. Redis ZSET; updates and rank lookups are O(log n).
skip list
A linked list with extra express lanes of links, giving O(log n) search and insert. Redis uses it inside sorted sets.
ZREVRANK
Redis command returning a member's 0-based position counting from the highest score.
time-windowed key
A separate board key per day or week (with a TTL), so resets are just a new key name.
authoritative server
The server, not the client, decides what happened in a match, which is the basis of anti-cheat.
idempotent write
A write that is safe to repeat; a unique match_id stops one match being counted twice.