Design a Real-Time Leaderboard With Redis Sorted Sets
Why sorting the scores table on every request does not scale, how a sorted set gives rank and top-N in logarithmic time, and how to handle ties, durability and very large boards.
A leaderboard ranks players by score and shows the top players along with each player's own rank. In a real-time leaderboard the ranking reflects new scores immediately, even with millions of players whose scores change constantly.
A relational query with ORDER BY score returns the correct answer, but repeating a sort over millions of rows on every request is too slow. The standard solution is a data structure that stays sorted as scores change.
1. Requirements
- Functional: update a player's score when they earn points.
- Functional: show the top N players, for example the top 10 or top 100.
- Functional: show a given player's rank and score, and the players immediately above and below them.
- Functional (ask): daily, weekly and all-time boards; boards per region or among friends.
- Non-functional: real-time. A score change is reflected in the ranking within about a second.
- Non-functional: low latency for reads and writes, and no loss of scores.
2. Scale estimation
Assume 10 million daily active players, each finishing 10 games per day. That is 100 million score updates per day, about 1,000 per second on average and several thousand at peak. Leaderboard views are of a similar or higher order. One entry needs a player ID and a score; with data structure overhead, allow about 100 bytes per player. Ten million players therefore need roughly 1 GB of memory, which fits on a single node.
3. Why sorting in the database fails
With an index on the score column, the top 10 query is fast. The problems are elsewhere. Finding a player's rank means counting how many players have a higher score, which scans a large part of the index and is slow for a player in the middle of the table. Thousands of such queries per second cannot be sustained.
At the same time, every score update modifies that index, so a table with a high write rate is also being scanned heavily, and reads and writes compete. Caching the top 10 helps that one query, but it does not help rank lookups, which are different for every player.
-- Top 10: acceptable with an index on score SELECT player_id, score FROM scores ORDER BY score DESC LIMIT 10; -- Rank of one player: counts every player above them SELECT COUNT(*) + 1 AS player_rank FROM scores WHERE score > (SELECT score FROM scores WHERE player_id = 42);
4. The Redis sorted set
A Redis sorted set stores unique members, each with a numeric score, and keeps them ordered by score at all times. Internally it combines a hash table, which finds a member's score in constant time, with a skip list, which maintains the order and records the span of each link so that a member's position can be computed without counting one by one.
As a result, adding or updating a score, and finding a member's rank, each take O(log N) time. Reading the top K takes O(log N + K). For ten million members, log N is about 23 steps. The ordering is maintained incrementally on each write, so nothing is ever sorted at read time.
# Player 42 earns 50 points ZINCRBY lb:global 50 player:42 -> O(log N) # Top 10, highest first, with scores ZREVRANGE lb:global 0 9 WITHSCORES -> O(log N + 10) # Rank of player 42 (0-based, highest score = rank 0) ZREVRANK lb:global player:42 -> O(log N) # Score of player 42 ZSCORE lb:global player:42 -> O(1) # Five players above and five below player 42 (suppose their rank is 1500) ZREVRANGE lb:global 1495 1505 WITHSCORES
5. High-level design
Scores must not be accepted directly from the client, because a modified client could submit any value. The game server, which knows the result of the match, reports the score to a score service. The score service writes the event to a durable database and updates the sorted set. The leaderboard service reads rankings from Redis and fetches display details such as names and avatars from a profile cache.
Game server (authoritative result)
|
v
Score service ------------> Scores DB (durable source of truth: score events + totals)
|
+--> Redis sorted sets
lb:global
lb:daily:2026-11-08 (EXPIRE after a few days)
lb:weekly:2026-W45
lb:region:in
Client --> Leaderboard service --> Redis: ZREVRANGE / ZREVRANK
|
+--> Profile cache (names, avatars for the returned player IDs)
Optional: push top-10 changes to connected clients over WebSocketPOST /internal/v1/scores (called by game servers only)
Body: { "playerId": 42, "points": 50, "matchId": "m_9912" }
GET /v1/leaderboards/global?top=10
Response: { "entries": [ { "rank": 1, "playerId": 7, "name": "...", "score": 98200 }, ... ] }
GET /v1/leaderboards/global/players/42?around=5
Response: { "rank": 1501, "score": 43150, "neighbours": [ ... ] }6. Ties
When two players have the same score, Redis orders them by member name, which is arbitrary from the players' point of view. The usual rule is that the player who reached the score first ranks higher. Since a sorted set has one numeric score per member, the tie-breaker is encoded into that number.
One method is a composite score: multiply the real score by a large constant and add a term that decreases as time passes, so that an earlier achievement produces a slightly larger number. The composite must stay within the 53 bits of integer precision of a double, which limits the ranges of both parts. An alternative is to keep the plain score in Redis and resolve ties when reading, using a timestamp stored elsewhere.
const MAX_TS = 9999999999; // seconds, far in the future
// Higher score wins; for equal scores, the earlier timestamp wins.
function compositeScore(score, achievedAtSeconds) {
return score * 1e10 + (MAX_TS - achievedAtSeconds);
}
// score 500 at t = 1767225600 -> 5000000000000 + 8232774399
// score 500 at t = 1767225700 -> 5000000000000 + 8232774299 (ranks lower)
// Keep score * 1e10 below 2^53 (about 9.0e15), i.e. scores under ~900,000.7. Source of truth and recovery
Redis holds data in memory. Persistence options and replicas reduce the risk of loss, but the leaderboard should be treated as a derived view, not as the system of record. Every score event is written to a durable database first. If the Redis data is lost, the sorted sets are rebuilt by replaying totals from the database.
To avoid counting a match twice when a request is retried, score updates carry the match ID and are applied idempotently. A replica with automatic failover keeps the leaderboard available during a node failure.
8. Time-based boards
Daily and weekly leaderboards are separate sorted sets whose key contains the period, such as lb:daily:2026-11-08. Each score update is applied to the global set and to the sets for the current day and week. Old sets are given an expiry so that they are removed automatically. A new period starts with an empty set simply because its key does not exist yet, so no reset job is needed.
9. Scaling beyond one node
A single sorted set must live on one node, and one node handles tens of millions of members. Beyond that, or for higher throughput, the board is partitioned.
- Natural partitions: separate boards per region, per game mode or per league. Most products need exactly these boards anyway.
- Sharding by score range: each shard holds one band of scores. A player's global rank is their rank within the shard plus the total number of players in all higher shards. Players move between shards as their scores change.
- Sharding by player ID: writes are spread evenly, and the global top N is obtained by taking the top N from each shard and merging. Exact rank requires querying every shard.
- Approximate rank: for players far from the top, an exact position rarely matters. A percentile computed from a histogram of score buckets ('top 12 percent') is cheap and sufficient.
Interview summary
- Requirements: real-time updates, top N, a player's own rank, low latency.
- Do not sort in the database per request: rank queries are too slow.
- Use a Redis sorted set: increment, range and rank in O(log N).
- Break ties with a timestamp encoded in the score; keep a durable database as the source of truth.
- For very large boards, partition by region or score range, and use approximate ranks.
Summary
A leaderboard needs a structure that remains ordered as scores change. A Redis sorted set provides updates, top-N reads and rank lookups in logarithmic time. The durable record of scores lives in a database from which the board can be rebuilt, ties are broken with a time component, periodic boards are separate keys with expiry, and very large boards are partitioned.
Puneet Tiwari
Full Stack Developer
