Design a Real-Time Leaderboard
Rank hundreds of millions of players in real time — Redis sorted sets and their complexity, score updates and tie-breaking, top-N and "my rank ± neighbours" queries, time-windowed (daily/weekly) boards, sharding when one sorted set isn't enough (score-range partitioning, approximate ranks via histograms), friends leaderboards, durability and anti-cheat.
1. Requirements
Functional
- Update a player's score after each match (increment or set best score).
- Top N (e.g., top 100) globally; player's own rank and the players around them.
- Daily, weekly, all-time boards; friends leaderboard.
Non-functional
- 50M DAU, 500M total players; 20k score updates/s peak, 100k rank reads/s.
- Rank visible within ~1 s of a match ending.
- Leaderboard reads p99 < 50 ms.
2. API
POST /v1/scores {"player_id": "p_7", "match_id": "m_9", "delta": 120} (server-to-server, idempotent by match_id)
GET /v1/leaderboards/global?period=weekly&top=100
GET /v1/leaderboards/global/players/p_7?period=weekly&around=5
GET /v1/leaderboards/friends/p_7?period=weekly
3. High-level design
4. Core operations
import time
PERIODS = lambda ts: [f"lb:daily:{time.strftime('%Y-%m-%d', time.gmtime(ts))}",
f"lb:weekly:{time.strftime('%G-W%V', time.gmtime(ts))}",
"lb:alltime"]
def record(r, player_id, match_id, delta, ts):
if not r.set(f"seen:{match_id}", 1, nx=True, ex=7 * 86400): # idempotent per match
return
with r.pipeline() as p:
for key in PERIODS(ts):
p.zincrby(key, delta, player_id)
p.expire(PERIODS(ts)[0], 8 * 86400)
p.expire(PERIODS(ts)[1], 35 * 86400)
p.execute()
def top(r, key, n=100):
return r.zrevrange(key, 0, n - 1, withscores=True)
def around(r, key, player_id, k=5):
rank = r.zrevrank(key, player_id) # 0-based
if rank is None:
return None, []
start = max(0, rank - k)
return rank + 1, r.zrevrange(key, start, rank + k, withscores=True)
ZINCRBY lb:weekly:2026-W41 120 p_7 O(log N)
ZREVRANGE lb:weekly:2026-W41 0 99 WITHSCORES
ZREVRANK lb:weekly:2026-W41 p_7 → 48211
ZREVRANGE lb:weekly:2026-W41 48206 48216 WITHSCORES
5. Deep dives
Scaling beyond one sorted set
| Approach | Top-N | My rank | Notes |
|---|---|---|---|
| Single ZSET | O(log N + N) | O(log N) | up to ~tens of millions of players |
| Hash-sharded ZSETs | merge each shard's top-N | sum of ZCOUNT above my score on every shard | simple, O(shards) per rank query |
| Score-range shards | top shard only | counts of higher shards + local rank | rebalancing as distribution shifts |
| Top-K exact + histogram | exact for top | percentile estimate for the rest | cheapest at huge scale |
Friends leaderboard
Friends lists are small (≤ a few hundred): fetch friend IDs, ZMSCORE their scores from the period ZSET, sort in the app. Cache per user for a short time.
Rebuild and durability
Scores DB (or event log) is authoritative; on Redis loss, rebuild all-time from the DB (SELECT player_id, total) via pipelined ZADD in batches; rebuild period boards from events in the period.
6. Trade-offs
| Decision | Choice |
|---|---|
| Ranking store | Redis sorted sets (exact, in memory) |
| Source of truth | durable score events / DB |
| Scale-out | score-range shards or exact top-K + approximate percentiles |
| Freshness | updates via stream within ~1 s; top-N cached briefly |
| Integrity | server-authoritative scores, idempotent by match ID |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.