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.
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.
| Quantity | Math | Result |
|---|---|---|
| Score writes | 50M × 10 / 86,400 | about 5,800/s (peak about 20,000/s) |
| Board reads | each player checks the board about 20 times a day | about 11,600/s (peak about 40,000/s) |
| Players on the all-time board | up to about 200 million | |
| Memory per board entry | member name + score + index overhead | about 100 bytes |
| Memory for one 50M-player board | 50M × 100 B | about 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_resultstable withmatch_id(primary key, so a match cannot be counted twice),player_id,points,ended_at, plus aplayerstable 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.
ZADD inserts members with scores. Redis keeps them sorted, so reading highest first is free. Index 0 is rank 1.
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.
ZREVRANK take to find one player's rank?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.
Press Run (⌘ Enter) to see what happens.High-level design
Step through a score being recorded, then a player opening the board.
Write path. The match is played on our match server, which knows the real outcome. The client never sends 'my score is 9,000'.
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
EXPIREa 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.
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:
- 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.
- 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. - 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.
player_id across 10 Redis nodes. What breaks?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.
Order what happens when a ranked match ends.
- Tap the steps below in the right order.
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_resultsfixes 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
ZMSCOREon 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
ZINCRBYcalls per node to cut round trips.
Match the need to the tool.
In-memory leaderboard
Build a tiny version of a Redis sorted set leaderboard.
add_score(player, points)addspointsto the player's total (a new player starts at 0). LikeZINCRBY.top(n)returns the bestnplayers as(player, score)pairs, highest score first. LikeZREVRANGE 0 n-1 WITHSCORES.rank(player)returns the player's 1-based rank (1 is the best), orNone(nullin 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") → 2In 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.
- 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_idstops one match being counted twice.