← Lessons

quiz vs the machine

Gold1400

Databases

Redis Sets and Sorted Sets

Unique members, with or without a ranking score.

5 min read · core · beat Gold to climb

Sets of Unique Members

A Redis set holds unordered, unique strings. Adding a member that already exists is a no op. Useful commands:

  • SADD adds members.
  • SISMEMBER tests membership in constant time.
  • SINTER, SUNION, and SDIFF combine sets.

Sets answer questions like which users liked a post or which tags an item has. Set algebra makes things like mutual friends a single SINTER.

Sorted Sets

A sorted set adds a floating point score to each unique member and keeps members ordered by that score. This unlocks ranking:

  • ZADD inserts a member with a score.
  • ZRANGE and ZREVRANGE read members by rank.
  • ZRANGEBYSCORE reads by score window.
  • ZINCRBY adjusts a score atomically.

Where They Win

Sorted sets are the natural fit for leaderboards, priority queues, and time ordered indexes. Store a player and their points, and the top ten is a ZREVRANGE. Use a timestamp as the score and you get a sliding window you can trim by score.

Both types stay efficient at scale. Sorted sets keep operations logarithmic by maintaining members in score order internally.

Key idea

Sets store unique members for membership and algebra, while sorted sets attach a score to rank members for leaderboards and windows.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a sorted set add compared to a plain set?

2. Which command finds members two sets have in common?

3. How would you get the top ten scores from a leaderboard sorted set?