Learn Labs
Data Structures

Sorted Sets

Members ranked by score: leaderboards, priority queues, and time indexes

A sorted set (zset) is a set where every member has a numeric score, and members are kept ordered by score. It's arguably Redis's most distinctive data structure: ranking, range queries, and top-N in O(log N) are hard to do this cheaply anywhere else.

Commands

ZADD lb:weekly 1500 player:1 900 player:2add/update members with scoresZINCRBY lb:weekly 50 player:2add to a score atomicallyZSCORE lb:weekly player:2950ZRANK lb:weekly player:20-based rank, lowest score firstZREVRANK lb:weekly player:2rank from the topZRANGE lb:weekly 0 9 REV WITHSCOREStop 10ZRANGE lb:weekly 1000 2000 BYSCOREmembers with score 1000..2000ZRANGE lb:weekly (1000 +inf BYSCORE LIMIT 0 20score > 1000, first 20 ( = exclusiveZCOUNT lb:weekly 1000 2000how many in a score rangeZCARD lb:weeklymember countZREM lb:weekly player:1ZREMRANGEBYSCORE lb:weekly -inf 100delete a score rangeZPOPMIN / ZPOPMAX / BZPOPMINtake lowest/highest (blocking variant too)ZADD lb:weekly GT 1700 player:1only update if the new score is greaterZUNIONSTORE lb:month 4 lb:w1 lb:w2 lb:w3 lb:w4combine (sums scores by default)

How it works

A large sorted set uses two structures together:

  • a hash table from member → score, so ZSCORE is O(1)
  • a skip list ordered by score, so ranks and ranges are O(log N)

A skip list is a sorted linked list with extra "express lane" pointers at random heights, giving balanced-tree performance with much simpler code. Each node also records how many elements its forward pointers skip, which is what makes ZRANK O(log N) rather than O(N).

head9001438150021004488higher levelsskip aheadZRANK walks the top level first and drops down a level when it would overshoot: O(log N).A hash table beside the skip list maps member → score, so ZSCORE is O(1).

Small sorted sets (up to 128 members, values up to 64 bytes) use a listpack instead, ordered by score, which is smaller and just as fast at that size.

Leaderboards

The demo in labs/leaderboard.py builds a 10,000-player board:

docker compose -f compose_prod.yaml run --rm labs python leaderboard.py

top 5:
#1  player:7431    4488
...
player:4242: rank #4908 of 10000, score 1438
around me:
#4906   player:1155    1439
#4907   player:9449    1438
#4908   player:4242    1438  <-- you
memory used by the leaderboard: 852 KiB

Top N, a player's rank, and the players around them are each one O(log N) command. The same queries in SQL need an index on score and a COUNT(*) of everyone above, which gets slow on large tables.

Time-based indexes

Use a timestamp as the score, and a sorted set becomes an index by time:

ZADD app:jobs:scheduled 1791800000 job:42run at this Unix timeZRANGE app:jobs:scheduled -inf 1791790000 BYSCOREeverything due by nowZREMRANGEBYSCORE rate:sliding:user-42 0 1791789990drop entries older than the window

This is how delayed job queues work (poll for due jobs, ZREM the ones you take) and how the sliding-window rate limiter keeps a log of recent request times.

Lexicographic ranges

When all scores are equal, members are ordered by name, and ZRANGE ... BYLEX does prefix queries. That's a cheap autocomplete:

ZADD app:autocomplete 0 apple 0 apricot 0 avocado 0 banana
ZRANGE app:autocomplete [ap (aq BYLEX     # members starting with "ap"
1) "apple"
2) "apricot"

Pitfalls

Lab

  1. Run leaderboard.py. Then in redis-cli, ZREVRANGE lb:weekly 0 2 WITHSCORES and ZREVRANK lb:weekly player:4242.
  2. Give player 4242 enough points to reach the top: ZINCRBY lb:weekly 5000 player:4242, then check its rank again.
  3. Check OBJECT ENCODING lb:weekly and OBJECT ENCODING app:products:by_price. Why are they different?
  4. Build the autocomplete example and query for prefix av.

On this page