Design: real-time leaderboard
Keep scores in a Redis sorted set: score updates and rank lookups are O(log N), the top 10 is one range read, and the set is a view rebuilt from the durable score store.
Fundamentals you'll use
How it works
- A Redis sorted set is a skip list plus a hash: update and rank in O(log N).
- Top 10 is one range read; my rank is
ZREVRANK, then a range around it. - Equal scores sort by member bytes; pack a timestamp into the score to rank the earlier player first.
- Redis is a rebuildable view: scores live in a database and replay from the match log.
- Past one node, shard by player and scatter-gather, or bucket by score range.
Check yourself
Answer to mark it learned; your answers aren't scored.
A game with 30M players keeps scores in Postgres with an index on score. "My rank" runs SELECT COUNT(*) FROM scores WHERE score > $1. The top 10 is fast, but "my rank" takes seconds for mid-table players, and ranks must be current within a second. What do you do?
Go deeper
Full explanation
Requirements
Functional: update a player's score when a match ends; show the top 10; show my rank with the players just above and below; daily, weekly and all-time boards. Non-functional: a new score is visible within about a second; reads take a few ms; no score is lost if the cache dies.
Scale (assumed): 50M players; 5M DAU × 10 matches ≈ 50M updates/day ≈ 580/s average, ~3k/s at peak.
Questions I'd ask:
- Does every player need an exact rank, or is "top 12%" enough beyond the first pages?
- One global board, or also per region, per season, per friend group?
- How are ties ordered?
API and data model
POST /scores {match_id, player_id, points} comes from the game server, never from the client. GET /leaderboard?top=10, GET /leaderboard/me?around=5. Source of truth: a scores(player_id, season, score) table and the log of match results. Serving copy: one Redis sorted set per board, member = player id, score = points.
Architecture
- The game service validates the match, writes the result to the database and publishes an event.
- A worker applies each event to Redis with
ZINCRBY, deduplicated bymatch_id(Idempotency). - Reads:
ZRANGE board 0 9 REV WITHSCORESfor the top 10;ZREVRANKfor my rank, then a range around it. Names and avatars come from a profile cache.
The hard parts
- Rank at scale: counting the players above me in SQL scans all of them; a sorted set answers in O(log N).
- Ties, and what the score encodes.
- A board too big for one node, and rebuilding it when Redis loses it.
Code Leaderboard on a Redis sorted set (redis-py)
import redis
r = redis.Redis(decode_responses=True)
BOARD = "lb:2026-W48" # one sorted set per board and period
# Atomic: mark the match as applied and add its points; a redelivery does nothing
APPLY = r.register_script("""
if redis.call('SET', KEYS[2], 1, 'NX', 'EX', 604800) then
return redis.call('ZINCRBY', KEYS[1], ARGV[1], ARGV[2])
end""")
def record_match(match_id: str, player: str, points: int) -> None:
APPLY(keys=[BOARD, f"applied:{match_id}:{player}"], args=[points, player]) # O(log N)
def top(n: int = 10):
return r.zrange(BOARD, 0, n - 1, desc=True, withscores=True) # O(log N + n)
def around_me(player: str, span: int = 5):
rank = r.zrevrank(BOARD, player) # 0-based, O(log N); None if unranked
if rank is None:
return None, []
rows = r.zrange(BOARD, max(0, rank - span), rank + span, desc=True, withscores=True)
return rank + 1, rows # 1-based rank plus neighbours
def rebuild(scores_db) -> None:
"""Redis lost the board: reload it from the source of truth, then swap."""
tmp = BOARD + ":rebuild"
r.delete(tmp)
for batch in scores_db.iter_scores(batch_size=10_000): # [(player, score), ...]
r.zadd(tmp, dict(batch))
r.rename(tmp, BOARD) # atomic switch; then replay newer matchesReal example
Weekly board lb:2026-W48 with 50M players (assumed). Ana finishes a match worth 120 points: ZINCRBY lb:2026-W48 120 ana is one O(log N) update, and log₂(50M) ≈ 26. Her client asks for her position: ZREVRANK returns 1,204,551 (0-based), then ZRANGE lb:2026-W48 1204546 1204556 REV WITHSCORES returns the five players above and below her. The home screen's top 10 is ZRANGE … 0 9 REV, cached for a second because everyone requests it. At ~100 B per member (assumed) the set takes ~5 GB: one node plus a replica.
Trade-offs +3 · −3
+ You gain
- Update, rank and top-N are O(log N) commands on one structure: no custom ranking code.
- A board per season, region or game mode is just another key.
- The serving copy is disposable: rebuild it from the score table and the match log.
− You pay
- One sorted set lives on one node: that node's memory and CPU bound the board.
- In-memory with asynchronous replication: a failover can drop the last writes.
- Tie-breaks and shared ranks need composite scores or extra commands.
Use it when
Ranked lists with frequent score updates and rank-by-member reads: game leaderboards, contest standings, top sellers or contributors.
Avoid it when
A few thousand rows read occasionally: ORDER BY with a window function in SQL. If only the top N matters and nobody asks "what is my rank", a cached query or a heap is enough.
Numbers to know 5
ZADD,ZINCRBY,ZREVRANK,ZCOUNT: O(log N).ZSCORE: O(1). A range of M: O(log N + M).- Assumed load: 5M DAU × 10 matches = 50M updates/day ≈ 580/s average, ~3k/s at peak.
- Memory: 50M members × ~100 B (assumed) ≈ 5 GB, which fits one node.
- Scores are doubles: integers are exact only up to 2⁵³ ≈ 9 × 10¹⁵.
ZREVRANGEis deprecated since Redis 6.2; useZRANGE … REV(checked Nov 2026).
Common pitfalls 4
- Ranking in SQL with
COUNT(*) WHERE score > mine: every request scans all the better players. - Accepting scores from the client: validate matches on the server, or the top 10 belongs to cheaters.
- Treating Redis as the source of truth: a failover drops recent updates and there is nothing to rebuild from.
- Composite scores above 2⁵³: the double loses precision and ranks silently collide.
Interview questions 3
Answer out loud first, then reveal.
How do you get one player's rank among 50M?Show answer
With a sorted set, ZREVRANK is O(log N): Redis keeps a skip list ordered by score where each link records how many nodes it skips, and sums those on the way down. A hash beside it maps member to score in O(1). The naive SQL, counting players with a higher score, reads millions of index entries per request. Beyond the first pages I'd also ask whether a percentile from a score histogram is enough.
The board outgrows one Redis node. What do you do?Show answer
First I check that it really does: assuming ~100 B per member, 50M players is ~5 GB. If so, I hash players into S sorted sets. The top 10 is a scatter-gather of each shard's top 10, merged; that is exact because a player lives on one shard. My rank is the sum of ZCOUNT above my score across shards. Score-range buckets make the top 10 a single read, but skew and cross-bucket moves make them harder to run.
Redis crashes and the leaderboard is gone. How do you recover?Show answer
It's a derived view, so I rebuild it. A replica takes over first. If the data is gone, a job bulk-loads scores from the database into a new key and renames it into place, then the worker replays match events since that snapshot. Applying an event is deduplicated by match id, so the replay can't double count. Meanwhile the API serves the last cached top 10 and hides ranks.
Deep dive 4
Why a sorted set, not SQL
ORDER BY score DESC LIMIT 10 on an indexed column is cheap. The rank is the problem: SELECT COUNT(*) FROM scores WHERE score > :mine walks the index entry of every better player, O(rank) per request, so a mid-table player among 50M reads ~25M entries. A sorted set keeps two structures: a hash from member to score, and a skip list ordered by score in which every link records how many nodes it skips. Summing those spans on the way down gives the rank in O(log N). So ZADD, ZINCRBY, ZREVRANK and ZCOUNT are O(log N), ZSCORE is O(1), and a range of M items is O(log N + M). For a few thousand players, SQL with a window function is fine.
Ties and composite scores
Redis orders members with equal scores lexicographically by member bytes, which looks arbitrary to players. The usual rule is "whoever reached the score first ranks higher". Encode it in the score: points × 10¹⁰ + (10¹⁰ − 1 − unix_seconds), so more points win and, at equal points, the earlier timestamp is larger. Scores are 64-bit doubles, exact only for integers up to 2⁵³ ≈ 9 × 10¹⁵, so this leaves room for ~900k points; beyond that, ranks silently collide. A composite score can't be incremented with ZINCRBY: read the new total from the source of truth and ZADD it. For best-score boards, ZADD GT only updates when the new score is higher. If equal scores must share a rank, compute it as ZCOUNT board (score +inf plus one.
Sharding a huge board
A sorted set is one key, and a key lives on one node: Redis Cluster's 16,384 hash slots spread keys, not the members of a key. First check you need more: 50M members × ~100 B (assumed) ≈ 5 GB. If you do, there are three patterns. Hash by player into S sets: the top K is a scatter-gather of each shard's top K, merged, and exact because a player lives on one shard (Design: top-K and heavy hitters); my rank is the sum over shards of ZCOUNT above my score. Score-range buckets: each shard owns a range, so rank = players in higher buckets + local rank and the top 10 is one read; but scores cluster, and a player crossing buckets is two non-atomic writes. Approximate tail: exact ranks for the top ~100k, a score histogram for everyone else ("top 12%").
Persistence and rebuild
Treat the board as a materialized view. A replica covers node failure, but replication is asynchronous, and AOF with appendfsync everysec can lose about a second of writes, so Redis alone cannot be the record. Keep scores in a durable database and match results in a log (Design: distributed message queue). To rebuild: bulk-load ZADD from the database into a new key, RENAME it into place, then replay match events newer than the snapshot; the match_id dedupe makes the replay safe. Period boards are just keys (lb:2026-W48): write the final standings to the database, then expire the key. A friends board needs no set of its own: ZMSCORE for the friend ids and sort in the app.