Video in progress
How do you design a real-time leaderboard for millions of players in Redis?
A sorted set: the member is the player ID, the score is the points. ZINCRBY to update, ZREVRANGE for the top N, ZREVRANK for a player's own position, all O(log N). You have to handle tie-breaking, periodic (daily/weekly) leaderboards and splitting a very large set separately.
📖 Answer
The basics:
ZINCRBY lb:weekly:2026-45 50 "player:9812"
ZREVRANGE lb:weekly:2026-45 0 99 WITHSCORES -- top 100
ZREVRANK lb:weekly:2026-45 "player:9812" -- position, counting from 0
ZREVRANGE lb:weekly:2026-45 140 160 WITHSCORES -- "the players around me"
Design decisions:
Ties: Redis sorts equal scores lexicographically by member name, which is meaningless for the business. Usually you want "whoever got there first ranks higher". The score is a double, exact for integers up to 2^53. You put the points in the high part and the time in the low part:
// higher points should win, and an earlier time should win -> (MAX_TS - ts)
double score = points * 1e7 + (9_999_999 - secondsSinceSeasonStart);
You need to check that the range of points and time fits in 2^53.
Periods: a new key every week, with a TTL on old keys. When the week ends, you archive the result to the DB. The "all time" leaderboard is a separate set.
Size: a sorted set with 10 million members can be around 1 GB and lives on a single node. One key is one slot, so a cluster doesn't help. Options:
- split into "buckets" by score (each range is a separate set), where position = the sum of the buckets above + the rank within the bucket;
- an exact position only for the top 10,000, and for everyone else an approximate percentage like "top 15%".
The write path: the source of the points is the DB or an event stream, and Redis is derived. If Redis is lost, you must be able to rebuild the leaderboard.
Another practical matter is removing cheaters: ZREM is simple, but don't forget to refresh the cached top-100 page as well.
Sign up to mark studied questions and save your progress.