Redis Sets and Sorted Sets

Redis provides two related types for collections of unique values. A Set stores items with no order and no duplicates. A Sorted Set also stores unique items but attaches a numeric score to each one, which Redis uses to keep them ranked.

Part 1: Sets

The Voter List Analogy

A voter registration list contains each person's name exactly once. Adding the same person twice does nothing — they are already on the list. The list has no defined order. A Redis Set works the same way.

Key: "online:users"   (a Redis Set)

SADD online:users "Alice"
SADD online:users "Bob"
SADD online:users "Carol"
SADD online:users "Alice"   ← duplicate, ignored silently

Set contents:
┌──────────────────────────────────┐
│  { "Alice", "Bob", "Carol" }     │
│   no order, no duplicates        │
└──────────────────────────────────┘

Core Set Commands

SADD   online:users "Dave"      → adds "Dave"
SREM   online:users "Bob"       → removes "Bob"
SISMEMBER online:users "Alice"  → 1 (is a member)
SISMEMBER online:users "Bob"    → 0 (not a member, removed)
SMEMBERS online:users           → all members (Alice, Carol, Dave)
SCARD  online:users             → 3 (count of members)

Set Math – Union, Intersection, and Difference

Sets support mathematical operations that make them powerful for matching and filtering:

Set A: users who bought from Store 1
  { "Alice", "Bob", "Carol" }

Set B: users who bought from Store 2
  { "Bob", "Carol", "Dave" }

SUNION  A B → { Alice, Bob, Carol, Dave }    (all buyers, no duplicates)
SINTER  A B → { Bob, Carol }                 (bought from BOTH stores)
SDIFF   A B → { Alice }                      (bought from A but NOT B)

Visual:
       Store 1                Store 2
   ┌────────────┐          ┌────────────┐
   │   Alice    │          │            │
   │            │  Bob     │            │
   │            │  Carol   │    Dave    │
   └────────────┘          └────────────┘
   SDIFF(A,B)    SINTER     SDIFF(B,A)

Real Use: Tracking Unique Visitors

Each time a user visits today's page, add their ID to a Set:
  SADD visitors:2024-03-20 "user:1001"
  SADD visitors:2024-03-20 "user:1002"
  SADD visitors:2024-03-20 "user:1001"  ← duplicate, ignored

SCARD visitors:2024-03-20
→ 2   (correct unique count, not 3)

Part 2: Sorted Sets

The Exam Results Board Analogy

Imagine exam results pinned to a board. Each student has a name and a score. The board always shows students ordered from highest to lowest score. New students appear in the right position automatically when added. A Redis Sorted Set does exactly this.

Key: "leaderboard:game1"

ZADD leaderboard:game1 9800 "Alice"
ZADD leaderboard:game1 7500 "Bob"
ZADD leaderboard:game1 8200 "Carol"
ZADD leaderboard:game1 6100 "Dave"

Internal ranking (Redis sorts by score automatically):
┌────────┬────────────┬────────┐
│  Rank  │   Player   │ Score  │
├────────┼────────────┼────────┤
│   1    │   Alice    │  9800  │
│   2    │   Carol    │  8200  │
│   3    │   Bob      │  7500  │
│   4    │   Dave     │  6100  │
└────────┴────────────┴────────┘

Reading from a Sorted Set

ZRANGE leaderboard:game1 0 -1
→ lowest to highest: Dave, Bob, Carol, Alice

ZRANGE leaderboard:game1 0 -1 WITHSCORES
→ Dave 6100, Bob 7500, Carol 8200, Alice 9800

ZREVRANGE leaderboard:game1 0 2
→ top 3 highest: Alice, Carol, Bob

ZSCORE leaderboard:game1 "Carol"
→ "8200"

ZRANK leaderboard:game1 "Bob"
→ 1   (zero-indexed from lowest, so rank 1 from bottom)

ZREVRANK leaderboard:game1 "Bob"
→ 2   (rank 2 from top — Alice is 0, Carol is 1, Bob is 2)

Updating Scores

Bob earns 500 more points:
ZINCRBY leaderboard:game1 500 "Bob"
→ "8000"

New ranking:
  Alice  9800
  Bob    8000  ← moved up
  Carol  8200
  Dave   6100

Wait — Bob (8000) is now ranked above Carol (8200)? No.
  Alice  9800
  Carol  8200
  Bob    8000
  Dave   6100
Correct. Redis re-ranks automatically.

Range by Score

Find all players with scores between 7000 and 9000:
ZRANGEBYSCORE leaderboard:game1 7000 9000 WITHSCORES
→ Bob 8000, Carol 8200

Choosing Between Set and Sorted Set

┌────────────────────────────────┬─────────┬──────────────┐
│  Use Case                      │   Set   │  Sorted Set  │
├────────────────────────────────┼─────────┼──────────────┤
│  Track unique visitors         │   ✓     │              │
│  Find common buyers (SINTER)   │   ✓     │              │
│  Tags on an article            │   ✓     │              │
│  Live game leaderboard         │         │      ✓       │
│  Priority task queue           │         │      ✓       │
│  Time-based event log          │         │      ✓       │
└────────────────────────────────┴─────────┴──────────────┘

Key Points

  • A Set stores unique items with no defined order. Duplicates are silently ignored.
  • SUNION, SINTER, and SDIFF perform set math — useful for overlap and exclusion queries.
  • A Sorted Set attaches a numeric score to each member and keeps them ranked automatically.
  • Use ZRANGE for ascending order and ZREVRANGE for descending (top-N leaderboard).
  • ZINCRBY updates a member's score, and Redis re-ranks it instantly.

Leave a Comment