Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 42 ยท Core Data Types

Sorted Sets

Learn Redis sorted sets: ZADD, ZRANGE by index, score and lex, ZRANK, ZINCRBY, ZUNIONSTORE, leaderboards and the skip list behind them, with live demos.

A sorted set (often called a zset) is a set where every member carries a floating-point score, and Redis keeps the members ordered by that score. Members are unique, scores are not: two members may share a score, in which case they are ordered alphabetically (byte by byte). You can ask for the top ten, the rank of one member, everyone between two scores, or add the same number to a score atomically, and each of those operations is fast even with millions of members.

That combination makes sorted sets the most versatile structure in Redis. They power game leaderboards, "trending" lists, time-ordered feeds (score = timestamp), delayed job queues (score = run-at time), rate-limit windows and secondary indexes. If you have not met plain sets yet, read that first: sorted sets add one idea (the score) on top.

Real Redis cannot run on this page, so the redis-cli snippets are read-only. The runnable examples use a plain JavaScript emulator that implements the real command semantics (ordering, ranks, ranges, ZINCRBY, ZUNIONSTORE). It is a teaching stand-in: it sorts an array on every call, whereas real Redis keeps its data in a skip list, which the last TryIt of this lesson builds in miniature.

Member plus score

Member A unique string, such as a user id.
Score A float that decides the order.
Ties Equal scores sort by member.
1 / 2

Adding scores and reading ranks

ZADD key score member [score member ...] adds members or updates the score of existing ones. It returns the number of new members. Useful flags: NX (only add new), XX (only update existing), GT / LT (only update when the new score is greater / lower), CH (count changed members instead of only new ones) and INCR (behave like ZINCRBY).

Text
127.0.0.1:6379> ZADD board 120 ana 95 bo 120 cy
(integer) 3
127.0.0.1:6379> ZRANGE board 0 -1 WITHSCORES
1) "bo"
2) "95"
3) "ana"
4) "120"
5) "cy"
6) "120"
127.0.0.1:6379> ZRANK board cy
(integer) 2

ZRANGE works with indexes (0-based, negative numbers count from the end, so 0 -1 means everything). Order is ascending by default; add REV to read from the highest score down, which is how you get a top list. ZRANK gives the 0-based position counting from the lowest score, ZREVRANK counts from the highest, ZSCORE returns one member's score and ZINCRBY key amount member adds to a score (creating the member if needed) and returns the new score. Scores come back as strings in the reply because they are floating point.

The older commands ZREVRANGE, ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZRANGEBYLEX still work, but since Redis 6.2 the single ZRANGE command with REV, BYSCORE, BYLEX and LIMIT replaces all of them.

JS A leaderboard in the emulator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the three ZADD board lines with flags in the output. The first (GT with 100 against an existing 120) changes nothing, the second (GT CH with 130) updates the score and CH makes the reply count it, and the NX one refuses to touch an existing member. Without CH, the reply of a pure update is 0, which surprises many people.

Ranges: by index, by score and by lex

Besides indexes, ZRANGE can select by score (BYSCORE) or, when all scores are equal, by member name (BYLEX). Both take LIMIT offset count for pagination.

  • Score bounds are numbers, -inf and +inf. A leading ( makes a bound exclusive: ZRANGE board (100 +inf BYSCORE means "strictly above 100". With REV, give the max first, then the min.
  • Lex bounds are [value (inclusive), (value (exclusive), - (smallest possible) and + (largest). They compare bytes, so they only make sense when every member has the same score, usually 0. Setting all scores to 0 turns a sorted set into an alphabetically sorted index, which is how autocomplete prefixes are done: ZRANGE words [red (ree BYLEX returns every word starting with red.
  • ZCOUNT key min max counts members in a score range without returning them, and ZREMRANGEBYSCORE deletes them, which is how expired items are trimmed from time-ordered sets.

ZUNIONSTORE dest numkeys key [key ...] [WEIGHTS w ...] [AGGREGATE SUM|MIN|MAX] and ZINTERSTORE merge several sorted sets into a new one. Scores of members found in more than one input are combined with SUM (the default), MIN or MAX, after being multiplied by their set's weight. This is the engine behind "weekly total from seven daily boards".

ZADD, ZRANK and range queries cost O(log N) (plus the number of members returned), so a leaderboard with ten million players answers "what is my rank?" in microseconds. ZUNIONSTORE is different: it touches every member of every input, so run it from a scheduled job, not per request.

The next TryIt uses a fuller emulator. It stores daily scores, queries by score and lex, and rolls three days up into a weekly board with weights.

JS Score ranges, lex ranges and ZUNIONSTORE

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Leaderboards in practice

A leaderboard needs four operations, and a sorted set answers each with one command:

  1. Record a result: ZADD game:scores 4200 user:7 or ZINCRBY game:scores 150 user:7 to add points. ZINCRBY is atomic, so two servers adding points at once never lose an update.
  2. Top N: ZRANGE game:scores 0 9 REV WITHSCORES.
  3. My rank: ZREVRANK game:scores user:7 returns the 0-based position from the top; add 1 to show "#1" to the player.
  4. Around me: take the rank, then ZRANGE game:scores (rank-5) (rank+5) REV, so players see their neighbours.

Two details bite people in production. First, ties: equal scores are ordered by member name, so a player who reached 500 points first is not ranked above one who reached it later. To make "earliest wins", encode the time into the score, for example points * 10^10 + (10^10 - timestamp), keeping the whole number inside the 53 bits a double stores exactly. Second, scores are doubles: integers above 2^53 lose precision, so never store a 64-bit id as a score.

How it works inside: the skip list

Redis keeps a sorted set in two structures at once: a hash table from member to score, which makes ZSCORE O(1), and a skip list ordered by score, which makes ranges and ranks O(log N). A skip list is a sorted linked list with express lanes. Each node is randomly given a height (with probability 1/4 of each extra level, as Redis does); the higher lanes skip over many nodes, so a search starts on the top lane, moves right while the next score is smaller, then drops a level and repeats. Redis also stores the span of each link, which is how ZRANK counts positions without walking the list. Small sorted sets use a compact packed encoding instead, because for a handful of members a skip list would waste memory.

The last TryIt builds a bare skip list with Redis's 1/4 promotion rule and compares a search against walking a plain list.

JS A skip list in miniature

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The bottom lane holds every node and each lane above holds about a quarter of the one below, so the number of comparisons grows like log N instead of N.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two members in a sorted set have the same score. How does Redis order them?

    Scores may repeat but members are unique, and ties are broken by comparing the member strings byte by byte, so the order is stable.
  2. 2. How do you read the top 10 players, highest score first, in one command?

    ZRANGE is ascending by default. REV reverses the order so index 0 is the highest score, and WITHSCORES adds the scores to the reply.
  3. 3. What does ZADD board 90 ana return when ana already exists with a different score?

    ZADD counts only newly added members. Updating an existing member's score returns 0 unless you pass CH to count changed members too.
  4. 4. Which range style is only meaningful when all members share the same score?

    BYLEX compares member names, ignoring scores, so the result is only well defined when all scores are equal, typically 0.
  5. 5. Why is ZRANK fast even on a huge sorted set?

    The skip list's express lanes and stored link spans let Redis find a position and count how many nodes precede it in logarithmic time.

Summary

  • A sorted set holds unique members with float scores, ordered by score and then by member name.
  • ZADD adds or updates (flags NX, XX, GT, LT, CH), ZINCRBY adds atomically, ZSCORE, ZRANK and ZREVRANK read one member.
  • ZRANGE handles indexes, BYSCORE, BYLEX, REV and LIMIT; the legacy ZREVRANGE and ZRANGEBYSCORE are replaced by it.
  • ZUNIONSTORE and ZINTERSTORE merge sets with WEIGHTS and AGGREGATE SUM|MIN|MAX; they are O(N) work, so run them off the request path.
  • Leaderboards use ZINCRBY, ZRANGE ... REV and ZREVRANK; encode time into the score if ties need a winner, and remember scores are doubles.
  • Internally a hash table plus a skip list give O(1) score lookups and O(log N) ranks and ranges.

Next, an append-only log with consumer groups: Streams.