Catalog My learning Blog
Redis Tutorial: Caching, Persistence and Scaling · Phase 1 · Lesson 3 · 5 min read

Redis Sets, Sorted Sets and HyperLogLog

On this page
  1. Building a leaderboard: why sorted sets
  2. Redis sorted sets: ZADD, ZRANGE and ZREVRANK
  3. Redis sets: uniqueness and set operations
  4. HyperLogLog: approximate unique counts in 12 KB
  5. Bitmaps: one bit per user
  6. Set vs sorted set vs HyperLogLog
  7. Check yourself

Building a leaderboard: why sorted sets

A game needs a live top 10 and each player's current rank. You could store scores in a database and run ORDER BY score DESC LIMIT 10 on every page view. You could keep them in a Redis hash and sort in the app. Or you could use the type built for exactly this, the sorted set, and let Redis keep the order as scores change.

This lesson covers that type plus two relatives: the plain set and HyperLogLog.

Redis sorted sets: ZADD, ZRANGE and ZREVRANK

Every member of a sorted set has a numeric score, and Redis keeps members ordered by it at all times. Adding or updating a member costs O(log N). Reading a range costs O(log N) plus the number of items returned.

Redis
ZADD leaderboard 15420 player:sam 18730 player:kai 12100 player:rey
ZINCRBY leaderboard 500 player:rey               # "12600", score updated in place
ZRANGE leaderboard 0 9 REV WITHSCORES            # top 10, highest first
# 1) "player:kai"  2) "18730"  3) "player:sam"  4) "15420"  5) "player:rey"  6) "12600"
ZREVRANK leaderboard player:sam                  # (integer) 1, zero-based rank
ZSCORE leaderboard player:sam                    # "15420"

The app never sorts anything. With a million players, the top 10 and any single player's rank still come back in microseconds. ZRANGE ... REV replaced the older ZREVRANGE in Redis 6.2; both still work.

Ties need a decision. Members with the same score are ordered by member name, byte by byte, not by who got there first. If the player who reached a score first should rank higher, build a tiebreaker into the score, such as points plus a fraction that shrinks with the time the score was reached. Scores are 64-bit floating-point numbers, exact for whole numbers up to 2^53, so leave room for both parts.

The score doesn't have to be points. Use a timestamp and you have a time-ordered feed: ZRANGE feed (now-3600) +inf BYSCORE gets the last hour. Use a due time and you have a delay queue: workers fetch members whose score is in the past. Two workers can fetch the same job, so a worker owns it only if its ZREM returns 1; the other gets 0 and moves on.

Redis sets: uniqueness and set operations

A set holds unique members with no order. SADD ignores duplicates, SISMEMBER checks membership in O(1), and Redis can combine sets directly:

Redis
SADD tags:post:1 redis cache db
SADD tags:post:2 redis queue
SINTER tags:post:1 tags:post:2                   # "redis"

SINTER, SUNION and SDIFF answer questions like "mutual friends" or "products with all of these tags" without pulling both sets into your application. Watch the size, though: they cost time proportional to the sets involved, and on sets with millions of members they become the slow commands from Day 1.

HyperLogLog: approximate unique counts in 12 KB

How many distinct visitors did the site have today? An exact answer means storing every visitor id, which at tens of millions of ids costs hundreds of megabytes per day. HyperLogLog is a probabilistic structure that estimates the count of distinct items in a fixed amount of memory, about 12 KB, no matter how many items you add.

Redis
PFADD visitors:2026-10-10 user-1 user-2 user-1   # duplicates don't count
PFCOUNT visitors:2026-10-10

On a local test I added 200,000 distinct ids. PFCOUNT returned 200,361, about 0.2 percent off, and the key used about 14 KB. Redis documents a standard error of 0.81 percent. You can also merge days into a week with PFMERGE.

The trade-off is strict: you can't list the members or check whether a specific user is in there. HyperLogLog answers one question, "about how many distinct?", and nothing else.

A set gives uniqueness and fast membership tests, a sorted set keeps members ordered by score for leaderboards and time-ordered feeds, and HyperLogLog counts distinct items approximately in a fixed 12 KB.
A set gives uniqueness and fast membership tests, a sorted set keeps members ordered by score for leaderboards and time-ordered feeds, and HyperLogLog counts distinct items approximately in a fixed 12 KB.

Bitmaps: one bit per user

When ids are small integers, a bitmap answers a yes-or-no question per id in a single bit. SETBIT sets bit number N of a string, and BITCOUNT counts the bits that are set:

Redis
SETBIT active:2026-10-10 1042 1          # user 1042 was active today
GETBIT active:2026-10-10 1042            # (integer) 1
BITCOUNT active:2026-10-10               # exact number of active users today
BITOP AND active:both active:2026-10-09 active:2026-10-10
BITCOUNT active:both                     # users active on both days

Ten million users cost about 1.25 MB per day, the count is exact, and you can still check one user, which HyperLogLog can't do. The catch is that ids must be dense integers: setting one bit for user id 4,000,000,000 allocates a 500 MB string. For "have we seen this before?" checks on arbitrary strings, Redis 8 also includes a Bloom filter type (BF.ADD, BF.EXISTS) with a small, tunable false-positive rate.

Set vs sorted set vs HyperLogLog

NeedType
Unique members, membership checks, intersectionsSet
Members ordered by a number: rank, time, prioritySorted set
Approximate distinct count at very large scaleHyperLogLog
Exact distinct count you also need to list or checkSet (and pay for the memory)
Exact yes or no per user, with dense integer idsBitmap

Check yourself

ZREVRANK leaderboard player:id for the rank and ZSCORE for the score. Both are O(log N), so they stay fast at millions of members.

No. It's an estimate with an error around 1 percent, and you can't list who was counted. Use a set or the primary database for anything that must be exact.

A sorted set with the due timestamp as the score. Workers fetch members with a score at or below the current time, then ZREM each one. Only the worker whose ZREM returns 1 runs the job, so two workers never run it twice.

If an occasional false positive is acceptable, a Bloom filter (available in Redis Stack and Redis 8) answers "maybe seen" or "definitely not seen" in a tiny amount of memory. If answers must be exact, store ids in sets but shard by user and expire old entries, or keep the history in a database.

A sorted set keeps members ordered by score at all times, so updating a score with ZINCRBY and reading a rank or the top 10 are both O(log N). Sorting in the application would mean loading every player's score on each request, which grows linearly and quickly becomes slow.