Design a Real-Time Gaming Leaderboard: Redis Sorted Sets, Skip Lists & Sharding
Why ORDER BY score DESC Fails Live Leaderboards
SELECT user_id, score FROM players ORDER BY score DESC LIMIT 10 on MySQL forces full table scans or expensive index maintenance as thousands of rows mutate concurrently. Fetching an individual player's exact rank (WHERE score > my_score) scans millions of rows!ZSET) solve both Top-10 and arbitrary user-rank queries in $O(\log N)$ time (< 1ms) in RAM.Real-Time Gaming Leaderboard Architecture
1. How Redis Sorted Sets Work Under the Hood
ZSET pairs two complementary structures simultaneously in C:- Hash Table: Maps
player_id -> scorein $O(1)$. - Skip List: A multi-layered probabilistic linked list maintaining elements sorted by score (and lexicographically on ties), enabling $O(\log N)$ rank lookup, range slices, and insertions without heavy balanced-tree rotations!
Essential Leaderboard Commands:
redis# 1. Atomically increment player score upon match win (O(log N)) ZINCRBY leaderboard:season_12 25 "user:rudresh" # 2. Fetch Global Top 10 Players with scores (O(log N + M)) ZREVRANGE leaderboard:season_12 0 9 WITHSCORES # 3. Fetch exact 0-based rank of a single player (O(log N)) ZREVRANK leaderboard:season_12 "user:rudresh" # 4. Fetch 4 players immediately above and below the current player ZREVRANGE leaderboard:season_12 1046 1054 WITHSCORES
2. Production Persistence, Tie-Breaking & Memory Math
- Tiny RAM Footprint: 25 million monthly players × ~64 bytes/entry (
24B id + 8B score + skip list pointers) $\approx 1.6\text{ GB}$—fits easily inside a single Redis instance! - Persistence & Hydrating Profiles: Keep Redis lean (
user_id -> scoreonly). Hydrate display names/avatars in batch from a MySQL/Redis user-profile cache, and persist match results in MySQL so Redis can rebuild after a crash. - Deterministic Tie-Breaking: When two players tie at
1,500points, who ranks higher? Encode timestamp fractionally into the float score or secondary lookup:score + (MAX_TS - achieved_at) * 1e-10so whoever reached the score first ranks ahead cleanly!
3. Scaling Beyond One Redis Node (500M+ Players)
- Fixed Score Range Bucketing (Best when score distribution is bounded): Partition keys across Redis shards by score range (
0..1000,1001..2000,2001+). Top-10 reads only touch the highest bucket! Track per-bucket user counts (ZCARD) to calculate global rank across buckets in $O(1)$ network hops. - Hash Partitioning + Scatter-Gather: Shard players uniformly across $K$ Redis nodes (
hash(user_id) % K); compute Top-10 via Scatter-Gather + Min-Heap merge on read (cached for 5 seconds).