Skip to content
Lesson 19 of 29

Step 1 of 3 · Reading · ~2 min

Sorted Sets

Sets & Sorted Sets

Sorted sets: the workhorse of leaderboards

A sorted set (zset) combines the uniqueness of a set with an explicit ordering: every member has a numeric score, and the set is always kept ordered by score. This single data type powers leaderboards, priority queues, and rate-limiting windows in real Redis deployments — it's worth understanding well.

Representation

The simplest correct representation is a dict mapping member → score. You get uniqueness (one score per member) and O(1) score lookups for free; ordering is computed on demand when a range command needs it:

python

Note ZADD takes score member in that order per pair — the opposite order from HSET's field value. It's an easy transposition bug when parsing arguments; write a small test with mismatched score/member values (e.g. ZADD z 5 alice 10 bob) to catch a swapped parser early.

Sorting for range queries

ZRANGE needs members ordered by score ascending, with ties broken lexicographically by member name (this matches real Redis's behavior, and gives deterministic output for testing):

python

From there, ZRANGE key start stop reuses the exact same negative-index normalization and clamping logic you wrote for LRANGE — compute the ordered list of members first, then slice it. This is a good moment to extract a shared clamp_range(start, stop, length) helper rather than re-deriving the off-by-one logic a third time.

ZSCORE, ZRANK, ZCARD

python

ZSCORE's reply is a bulk string, not an integer — scores can be floats (5.5), so they're formatted as text ($3\r\n5.5\r\n), unlike ZCARD's plain RESP integer.

WITHSCORES

When the caller appends WITHSCORES, flatten the reply the same way HGETALL does — member, score, member, score — rather than nesting pairs:

python

Format scores consistently (e.g. strip trailing .0 for whole numbers, or always emit as-is) — the format you pick has to match exactly what your tests expect for ZSCORE too, so define one format_score helper and use it everywhere a score gets serialized.

Up nextDEL, EXISTS, KEYS & TYPEAdvanced Features

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…