Difficulty: Intermediate
How do you fetch all members of a Sorted Set whose scores are between 10 and 50, and how do you make the bounds exclusive, sort descending or paginate?
Use ZRANGE myset 10 50 BYSCORE (Redis 6.2+) or the older ZRANGEBYSCORE myset 10 50. Both return members with scores from 10 to 50 inclusive, ordered by score ascending, in O(log N + M) time where M is the number of results. Add WITHSCORES to get scores back, prefix a bound with ( to make it exclusive, and use LIMIT offset count to paginate.
Redis 6.2 unified range queries into ZRANGE:
ZRANGE key min max BYSCORE [REV] [LIMIT offset count] [WITHSCORES]
ZRANGEBYSCORE and ZREVRANGEBYSCORE still work but are marked deprecated in the docs. New code should use ZRANGE ... BYSCORE.
| You want | Write |
|---|---|
| 10 <= score <= 50 | 10 50 |
| 10 < score <= 50 | (10 50 |
| 10 <= score < 50 | 10 (50 |
| score >= 10 | 10 +inf |
| score <= 50 | -inf 50 |
With REV, give the larger bound first: ZRANGE myset 50 10 BYSCORE REV returns 50 down to 10. Getting this order wrong returns an empty list, which is a frequent bug.
ZCOUNT key min max counts members in the range without returning them.ZREMRANGEBYSCORE key min max deletes a range, the core of a sliding-window rate limiter.ZRANGESTORE dst src min max BYSCORE (6.2+) writes the result into another sorted set.ZRANGE key min max BYLEX does lexicographic ranges when all scores are equal.ZRANGE products:mobiles 1000000 2500000 BYSCORE for Rs 10,000 to Rs 25,000.-inf to now).ZREMRANGEBYSCORE, then ZCARD.LIMIT with a large offset still walks past the skipped elements, so deep pagination is O(offset). For feeds, paginate by score ((lastScore) instead of offset.ZADD scores 5 asha 12 ravi 30 meera 50 kabir 72 neha
# Inclusive 10..50
ZRANGE scores 10 50 BYSCORE WITHSCORES
# Exclusive upper bound, descending (max first with REV)
ZRANGE scores (50 10 BYSCORE REV
# Count only
ZCOUNT scores 10 50
# Legacy form, still works
ZRANGEBYSCORE scores 10 50 LIMIT 0 2
Note that with REV the first bound is the maximum. The ( prefix excludes kabir at exactly 50.
import time, uuid
import redis
r = redis.Redis()
def allow(user_id: str, limit: int = 100, window_s: int = 60) -> bool:
key = f"rl:{user_id}"
now_ms = int(time.time() * 1000)
pipe = r.pipeline() # MULTI/EXEC by default
pipe.zremrangebyscore(key, 0, now_ms - window_s * 1000) # drop old entries
pipe.zadd(key, {f"{now_ms}-{uuid.uuid4().hex[:6]}": now_ms})
pipe.zcard(key)
pipe.expire(key, window_s)
_, _, count, _ = pipe.execute()
return count <= limit
Timestamps as scores turn 'requests in the last 60 seconds' into a score range. A unique member avoids collisions when two requests share a millisecond.
Sorted Set, ZRANGE BYSCORE, ZRANGEBYSCORE, Exclusive bounds, LIMIT pagination