Redis Leaderboard Sorted Set Design Prompt
Design scalable leaderboards with Redis sorted sets using ZADD/ZRANGE/ZRANK, handling ties, pagination, and huge member counts.
- Target user
- Game and product engineers building rankings
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior engineer who has built high-traffic leaderboards on Redis sorted sets. I will provide: - What I am ranking and by what score - Scale (members, updates/sec, read patterns) - Time windows (all-time, daily, weekly) Your job: 1. **Use a ZSET**: ZADD to set/update a member's score; scores are 64-bit doubles. ZINCRBY to add deltas atomically. 2. **Read ranks and pages**: ZREVRANGE for top-N descending (with WITHSCORES), ZREVRANK for a player's 0-based rank, ZRANGEBYSCORE / ZRANGE ... BYSCORE for score bands, ZCOUNT for population in a range. 3. **Handle ties**: equal scores sort lexicographically by member — encode a tiebreaker (e.g. earlier timestamp) into the score itself using a composite score, or accept lexical ordering. 4. **Paginate correctly**: offset pagination (ZREVRANGE start stop) is O(log(N)+M); deep offsets are fine but avoid recomputing full pages repeatedly — cache hot pages. 5. **Time-windowed boards**: use per-window keys like `lb:daily:2026-07-03` with a TTL; ZUNIONSTORE to roll up windows into weekly/monthly aggregates. 6. **Scale**: a single ZSET handles millions of members; for extreme scale shard by region and merge top-N client-side, or precompute. Memory ~ per-member overhead; estimate before committing. 7. **Get a player's neighborhood**: ZREVRANK to find position, then ZREVRANGE around it for "players near you". 8. **Cluster**: keep a leaderboard on one slot (single key already is); shard boards across slots with hash tags if you split them. Mark DESTRUCTIVE: DEL/UNLINK of a live leaderboard key, FLUSHDB, ZREMRANGEBYRANK trimming that discards real players, CONFIG changes to eviction on the board instance. --- Ranking: [DESCRIBE] Scale: [DESCRIBE] Time windows: [DESCRIBE]
Why this prompt works
Sorted sets make leaderboards easy to build and easy to get subtly wrong: float precision loss on big scores, lexical tie ordering, and accidental data loss from range-trim commands. This prompt makes the model design the score encoding, tie handling, and time-window rollups explicitly so the board stays correct as it scales.
How to use it
- State what you rank and the score semantics (higher = better?).
- Give scale and update rate so sharding is considered.
- List time windows (daily/weekly/all-time) for rollup design.
- Ask for the “players near me” query if you need it.
Useful commands
# Update scores atomically
redis-cli ZADD lb:alltime 15000 player:42
redis-cli ZINCRBY lb:alltime 250 player:42 # add a delta
# Top 10 with scores (descending)
redis-cli ZREVRANGE lb:alltime 0 9 WITHSCORES
# A player's rank (0-based) and score
redis-cli ZREVRANK lb:alltime player:42
redis-cli ZSCORE lb:alltime player:42
# Population in a score band and total size
redis-cli ZCOUNT lb:alltime 10000 20000
redis-cli ZCARD lb:alltime
Example config
# Daily board with TTL, then weekly rollup via union
redis-cli ZADD lb:daily:2026-07-03 8400 player:42
redis-cli EXPIRE lb:daily:2026-07-03 172800 # keep 2 days
# Roll 7 daily boards into a weekly aggregate (sum scores)
redis-cli ZUNIONSTORE lb:weekly:2026-w27 7 \
lb:daily:2026-06-29 lb:daily:2026-06-30 lb:daily:2026-07-01 \
lb:daily:2026-07-02 lb:daily:2026-07-03 lb:daily:2026-07-04 \
lb:daily:2026-07-05 AGGREGATE SUM
# "Players near me": find rank then read a window around it
# rank = ZREVRANK lb:alltime player:42 (say 57)
redis-cli ZREVRANGE lb:alltime 52 62 WITHSCORES
Common findings this catches
- Float precision loss → wrong order on huge scores.
- Unstable ties → lexical order surprises players.
- Accidental trim → ZREMRANGEBYRANK deletes real users.
- No time windows → cannot reset daily/weekly.
- Blocking union → big ZUNIONSTORE stalls the server.
- Hot page load → uncached repeated top-N reads.
- Whole-key eviction → board vanishes under memory pressure.
When to escalate
- Hundreds of millions of members — shard and precompute with the data team.
- Real-money or ranked-competitive scoring — add audit and anti-cheat review.
- Cross-region unified boards — dedicated architecture design.
Related prompts
-
Redis Data Structure Selection Prompt
Choose the right Redis type — string, hash, list, set, sorted set, stream, bitmap, or HyperLogLog — for a given use case and access pattern.
-
Redis Memory Optimization Prompt
Analyze Redis memory usage — encodings, big keys, fragmentation — and reduce footprint with listpack/intset thresholds and smarter modeling.
-
Redis TTL and Expiration Strategy Prompt
Design TTL hygiene with EXPIRE/PEXPIRE, understand active vs lazy expiry, and avoid immortal keys and expiry-driven latency spikes.