Skip to content

Leaderboards

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.

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) 5
ZADD 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 WITHSCORES
1) "dave"
2) "5800"
3) "bob"
4) "4100"
5) "alice"
6) "3200"
7) "eve"
8) "2900"
9) "carol"
10) "1750"
ZREVRANGE game:lb 0 9 WITHSCORES

Step 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) 2
127.0.0.1:6379> ZREVRANK game:lb "carol"
(integer) 4
127.0.0.1:6379> ZSCORE game:lb "alice"
"3200"
ZREVRANK game:lb "alice"
ZREVRANK game:lb "carol"
ZSCORE game:lb "alice"

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 WITHSCORES
1) "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 WITHSCORES
127.0.0.1:6379> ZADD lb 3200 "alice" 4100 "bob" 1750 "carol" 5800 "dave" 2900 "eve"
(integer) 5
127.0.0.1:6379> ZREVRANGE lb 0 9 WITHSCORES
1) "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) 4
127.0.0.1:6379> ZINCRBY lb 2500 "carol"
"4250"
127.0.0.1:6379> ZREVRANK lb "carol"
(integer) 1
ZADD 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"
Which command fetches the top 10 players in descending score order?
ZREVRANK returns 0 for which player?
Why is ZINCRBY preferred over ZADD when awarding points?
If carol's current score is 1750 and you run ZINCRBY lb 2500 carol, what is her new score?