Leaderboards
The leaderboard pattern
Section titled “The leaderboard pattern”A game or app leaderboard needs three things: store a score, rank players, and add points over time. Redis Sorted Sets handle all three natively with O(log N) writes and O(log N + M) range reads.
Step 1 — Add initial scores with ZADD
Section titled “Step 1 — Add initial scores with ZADD”Start by inserting players and their scores. Scores are float64, so they can represent points, percentages, timestamps, or any numeric ranking value.
127.0.0.1:6379> ZADD game:lb 3200 "alice" 4100 "bob" 1750 "carol" 5800 "dave" 2900 "eve"(integer) 5ZADD game:lb 3200 "alice" 4100 "bob" 1750 "carol" 5800 "dave" 2900 "eve"Step 2 — Fetch the top 10 with ZREVRANGE
Section titled “Step 2 — Fetch the top 10 with ZREVRANGE”ZREVRANGE key 0 9 WITHSCORES returns the top 10 players in descending score order. The indices are rank offsets, so 0 9 always means positions 1 through 10.
127.0.0.1:6379> ZREVRANGE game:lb 0 9 WITHSCORES1) "dave"2) "5800"3) "bob"4) "4100"5) "alice"6) "3200"7) "eve"8) "2900"9) "carol"10) "1750"ZREVRANGE game:lb 0 9 WITHSCORESStep 3 — Look up a player’s rank with ZREVRANK
Section titled “Step 3 — Look up a player’s rank with ZREVRANK”ZREVRANK key member returns the 0-based rank in descending order — 0 is first place. Add 1 to get a human-friendly rank.
127.0.0.1:6379> ZREVRANK game:lb "alice"(integer) 2127.0.0.1:6379> ZREVRANK game:lb "carol"(integer) 4127.0.0.1:6379> ZSCORE game:lb "alice""3200"ZREVRANK game:lb "alice"
ZREVRANK game:lb "carol"
ZSCORE game:lb "alice"Step 4 — Award points with ZINCRBY
Section titled “Step 4 — Award points with ZINCRBY”When a player earns more points, use ZINCRBY to atomically add to their existing score. No read-modify-write cycle needed.
127.0.0.1:6379> ZINCRBY game:lb 1500 "carol""3250"127.0.0.1:6379> ZINCRBY game:lb 800 "alice""4000"127.0.0.1:6379> ZREVRANGE game:lb 0 4 WITHSCORES1) "dave"2) "5800"3) "bob"4) "4100"5) "alice"6) "4000"7) "carol"8) "3250"9) "eve"10) "2900"ZINCRBY game:lb 1500 "carol"
ZINCRBY game:lb 800 "alice"
ZREVRANGE game:lb 0 4 WITHSCORESFull leaderboard workflow in one paste
Section titled “Full leaderboard workflow in one paste”127.0.0.1:6379> ZADD lb 3200 "alice" 4100 "bob" 1750 "carol" 5800 "dave" 2900 "eve"(integer) 5127.0.0.1:6379> ZREVRANGE lb 0 9 WITHSCORES1) "dave"2) "5800"3) "bob"4) "4100"5) "alice"6) "3200"7) "eve"8) "2900"9) "carol"10) "1750"127.0.0.1:6379> ZREVRANK lb "carol"(integer) 4127.0.0.1:6379> ZINCRBY lb 2500 "carol""4250"127.0.0.1:6379> ZREVRANK lb "carol"(integer) 1ZADD lb 3200 "alice" 4100 "bob" 1750 "carol" 5800 "dave" 2900 "eve"
ZREVRANGE lb 0 9 WITHSCORES
ZREVRANK lb "carol"
ZINCRBY lb 2500 "carol"
ZREVRANK lb "carol"