ZSET Range Query

Difficulty: Intermediate

Question

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?

Answer

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.

The modern syntax

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.

Bound syntax

You wantWrite
10 <= score <= 5010 50
10 < score <= 50(10 50
10 <= score < 5010 (50
score >= 1010 +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.

Related commands

  • 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.

Where score ranges are used

  • Price filters. Store product IDs with price in paise as the score and query ZRANGE products:mobiles 1000000 2500000 BYSCORE for Rs 10,000 to Rs 25,000.
  • Time windows. Use a UNIX timestamp as the score to fetch events from the last hour, or delayed jobs due now (-inf to now).
  • Sliding-window rate limiting. Add each request with its timestamp, remove entries older than the window with ZREMRANGEBYSCORE, then ZCARD.

Performance gotchas

  • 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.
  • Scores are 64-bit doubles. Integers are exact up to 2^53, which is fine for millisecond timestamps and paise amounts.
  • Ties are ordered lexicographically by member, so results are deterministic.
How ZRANGE BYSCORE finds a range. The skip list jumps to the first match, then walks forward until the max bound.
  1. Parse min and max: Handles ( for exclusive and -inf or +inf.
  2. Skip list search: O(log N) to the first score >= min.
  3. Apply LIMIT offset: Skips offset elements one by one.
  4. Walk until max: Collects up to count members.
  5. Return members: Optionally WITHSCORES.

Code examples

Score ranges from redis-cli

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.

Sliding-window rate limiter (Python, redis-py)

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.

Key points

  • ZRANGE key min max BYSCORE is the 6.2+ form; ZRANGEBYSCORE is deprecated but works
  • Bounds are inclusive by default; prefix ( for exclusive; use -inf and +inf for open ends
  • With REV the max bound comes first
  • Complexity is O(log N + M); large LIMIT offsets add O(offset)
  • Timestamps or prices in paise as scores enable time-window and price-filter queries

Common follow-up questions

  • How would you paginate a feed stored in a sorted set without large offsets?
  • What data structure backs a sorted set and why?
  • How would you implement a delayed job queue with a sorted set?
  • What is the difference between BYSCORE and BYLEX?

Interview tips

  • Give the modern ZRANGE ... BYSCORE syntax and mention the legacy command; it shows you are current
  • Know the ( exclusive syntax and the reversed bounds with REV
  • Tie it to a use case like rate limiting or price filters

Concepts covered

Sorted Set, ZRANGE BYSCORE, ZRANGEBYSCORE, Exclusive bounds, LIMIT pagination

More Redis & Caching questions