Redis Sorted Sets
A sorted set (zset) is like a set (every member is unique) but each member also carries a score, a floating-point number. Redis keeps the members ordered by score at all times, so you can ask for "the top 10", "everything between 100 and 200" or "what rank is this player" in logarithmic time. Leaderboards, priority queues, time-ordered indexes and rate limiters are all built on sorted sets.
ZADD and ZRANGE
ZADD key score member [score member ...] adds members (or updates their scores) and returns how many were new. ZRANGE key start stop returns members by rank, lowest score first; add WITHSCORES to see the scores.
ZADD game:scores 1200 ada 950 linus 1430 grace 950 alan
ZRANGE game:scores 0 -1 WITHSCORES
ZRANGE game:scores 0 1
ZCARD game:scores
ZSCORE game:scores graceredis> ZADD game:scores 1200 ada 950 linus 1430 grace 950 alan
(integer) 4
redis> ZRANGE game:scores 0 -1 WITHSCORES
1) "alan"
2) "950"
3) "linus"
4) "950"
5) "ada"
6) "1200"
7) "grace"
8) "1430"
redis> ZRANGE game:scores 0 1
1) "alan"
2) "linus"
redis> ZCARD game:scores
(integer) 4
redis> ZSCORE game:scores grace
"1430"
Members with the same score (alan and linus, both 950) are ordered alphabetically, byte by byte. That rule makes the order fully predictable.
Highest first: REV
For a leaderboard you usually want the highest scores first. Add REV to ZRANGE (the older ZREVRANGE does the same):
ZADD game:scores 1200 ada 950 linus 1430 grace 880 alan
ZRANGE game:scores 0 2 REV WITHSCORES
ZRANK game:scores grace
ZREVRANK game:scores grace
ZREVRANK game:scores alanredis> ZADD game:scores 1200 ada 950 linus 1430 grace 880 alan
(integer) 4
redis> ZRANGE game:scores 0 2 REV WITHSCORES
1) "grace"
2) "1430"
3) "ada"
4) "1200"
5) "linus"
6) "950"
redis> ZRANK game:scores grace
(integer) 3
redis> ZREVRANK game:scores grace
(integer) 0
redis> ZREVRANK game:scores alan
(integer) 3
Ranks are 0-based: ZREVRANK returns 0 for the leader. Add 1 when you show it to users.
Updating scores
ZINCRBY adds to a member's score (creating it if needed) and returns the new score. ZADD has flags for conditional updates:
| Flag | Meaning |
|---|---|
NX |
only add new members, never update |
XX |
only update existing members, never add |
GT / LT |
only update if the new score is greater / less than the current one |
CH |
return the number of changed members instead of new ones |
ZADD best:lap 92.4 mai 88.1 an
ZADD best:lap LT 90.0 mai
ZADD best:lap LT 95.0 an
ZRANGE best:lap 0 -1 WITHSCORES
ZINCRBY points 10 mai
ZINCRBY points 5 mai
ZADD points XX 100 binh
ZRANGE points 0 -1 WITHSCORESredis> ZADD best:lap 92.4 mai 88.1 an
(integer) 2
redis> ZADD best:lap LT 90.0 mai
(integer) 0
redis> ZADD best:lap LT 95.0 an
(integer) 0
redis> ZRANGE best:lap 0 -1 WITHSCORES
1) "an"
2) "88.1"
3) "mai"
4) "90"
redis> ZINCRBY points 10 mai
"10"
redis> ZINCRBY points 5 mai
"15"
redis> ZADD points XX 100 binh
(integer) 0
redis> ZRANGE points 0 -1 WITHSCORES
1) "mai"
2) "15"
LT keeps the best (lowest) lap time: Mai's new 90.0 replaced 92.4, while An's slower 95.0 was ignored. XX refused to add the unknown binh.
Ranges by score
ZRANGE ... BYSCORE selects by score instead of rank. Bounds are inclusive; prefix a bound with ( to make it exclusive, and use -inf / +inf for open ends. ZCOUNT only counts:
ZADD products:by-price 8.5 mug 24 teapot 3.2 spoon 15 bowl 60 kettle
ZRANGE products:by-price 5 20 BYSCORE WITHSCORES
ZRANGE products:by-price (8.5 +inf BYSCORE LIMIT 0 2
ZRANGE products:by-price +inf -inf BYSCORE REV LIMIT 0 1
ZCOUNT products:by-price -inf 10redis> ZADD products:by-price 8.5 mug 24 teapot 3.2 spoon 15 bowl 60 kettle
(integer) 5
redis> ZRANGE products:by-price 5 20 BYSCORE WITHSCORES
1) "mug"
2) "8.5"
3) "bowl"
4) "15"
redis> ZRANGE products:by-price (8.5 +inf BYSCORE LIMIT 0 2
1) "bowl"
2) "teapot"
redis> ZRANGE products:by-price +inf -inf BYSCORE REV LIMIT 0 1
1) "kettle"
redis> ZCOUNT products:by-price -inf 10
(integer) 2
LIMIT offset count gives you pagination. With REV the bounds are written from high to low.
Time-ordered indexes
Scores are often timestamps. A sorted set of post IDs scored by publication time is an index you can query by date and trim by age:
ZADD feed:user:7 1760600000 post:11 1760686400 post:12 1760772800 post:13
ZRANGE feed:user:7 1760650000 +inf BYSCORE
ZREMRANGEBYSCORE feed:user:7 -inf 1760650000
ZRANGE feed:user:7 0 -1 WITHSCORESredis> ZADD feed:user:7 1760600000 post:11 1760686400 post:12 1760772800 post:13
(integer) 3
redis> ZRANGE feed:user:7 1760650000 +inf BYSCORE
1) "post:12"
2) "post:13"
redis> ZREMRANGEBYSCORE feed:user:7 -inf 1760650000
(integer) 1
redis> ZRANGE feed:user:7 0 -1 WITHSCORES
1) "post:12"
2) "1760686400"
3) "post:13"
4) "1760772800"
ZREMRANGEBYSCORE (and ZREMRANGEBYRANK) delete whole ranges at once: handy for dropping old entries.
Popping and combining
ZPOPMIN and ZPOPMAX remove and return the lowest or highest members, so a sorted set works as a priority queue. ZUNIONSTORE and ZINTERSTORE combine sets, adding the scores by default (WEIGHTS and AGGREGATE MIN|MAX change that):
ZADD jobs 3 send-report 1 fix-login 2 resize-images
ZPOPMIN jobs
ZPOPMAX jobs
ZADD week:1 10 ada 7 linus
ZADD week:2 4 ada 9 grace
ZUNIONSTORE total 2 week:1 week:2
ZRANGE total 0 -1 REV WITHSCORESredis> ZADD jobs 3 send-report 1 fix-login 2 resize-images
(integer) 3
redis> ZPOPMIN jobs
1) "fix-login"
2) "1"
redis> ZPOPMAX jobs
1) "send-report"
2) "3"
redis> ZADD week:1 10 ada 7 linus
(integer) 2
redis> ZADD week:2 4 ada 9 grace
(integer) 2
redis> ZUNIONSTORE total 2 week:1 week:2
(integer) 3
redis> ZRANGE total 0 -1 REV WITHSCORES
1) "ada"
2) "14"
3) "grace"
4) "9"
5) "linus"
6) "7"
Lexicographic ranges
When all members have the same score, ZRANGE ... BYLEX returns members by alphabetical range. Brackets mark the bounds: [ inclusive, ( exclusive, - and + for the ends. This gives a simple prefix search for autocomplete:
ZADD names 0 anna 0 andrew 0 bao 0 andy 0 alice
ZRANGE names [and "[and\xff" BYLEX
ZRANGE names - (b BYLEXredis> ZADD names 0 anna 0 andrew 0 bao 0 andy 0 alice
(integer) 5
redis> ZRANGE names [and "[and\xff" BYLEX
1) "andrew"
2) "andy"
redis> ZRANGE names - (b BYLEX
1) "alice"
2) "andrew"
3) "andy"
4) "anna"
The upper bound "[and\xff" (the prefix followed by the highest byte, written in double quotes so that redis-cli turns \xff into one byte) catches every member starting with and.
Test yourself
Two members have the same score. How does Redis order them?
- By insertion time
- Randomly
- Lexicographically by member
- By member length
What does ZREVRANK board alice return when alice has the highest score?
- (integer) 1
- (integer) 0
- (integer) -1
- (nil)
In ZRANGE prices (10 20 BYSCORE, which scores are included?
- 10 ≤ score ≤ 20
- 10 < score ≤ 20
- 10 < score < 20
- only 10 and 20