Sets & Sorted Sets in Redis

7 questions found

What is a Redis set, and what guarantee does it provide about the items you store in it?

Beginner
A Redis set stores an unordered collection of unique values, automatically preventing any duplicate from being added twice, which makes it a natural fit for tracking things like unique tags on a post or unique visitors to a page, where you only care whether an item is present, not how many times it might have been added.
SADD post_tags:1 'redis' 'database' 'caching'
SADD post_tags:1 'redis' -- has no effect, already present
Real-world example A blogging platform stores each post's tags in a set, automatically ensuring a tag can never accidentally be duplicated even if it is added multiple times through different parts of the application.

Common follow-ups: What happens if you try to add an item that already exists in a set?;How do you check how many unique items are currently in a set?

Data Types;Redis CLI & Basic Commands

How do you check if a specific item exists in a Redis set, and how do you remove an item from it?

Beginner
You use SISMEMBER to check whether a specific value is currently a member of a set, returning a simple true or false style result, and SREM to remove one or more specific values from the set, leaving the rest of its contents completely unaffected.
SISMEMBER post_tags:1 'redis'
SREM post_tags:1 'caching'
Real-world example A content management system checks whether a specific tag is already applied to a post using SISMEMBER before showing an add tag button, and removes a tag using SREM when an editor decides it no longer applies.

Common follow-ups: What is the time complexity of checking membership in a set?;What happens if you try to remove an item that is not actually in the set?

Data Types;Redis CLI & Basic Commands

How do you find the intersection, union, and difference between two or more Redis sets?

Intermediate
You use SINTER to find items that exist in every specified set, SUNION to find items that exist in at least one of the specified sets, and SDIFF to find items that exist in the first specified set but not in any of the others, giving you powerful built-in set algebra operations directly within Redis.
SADD set1 'a' 'b' 'c'
SADD set2 'b' 'c' 'd'
SINTER set1 set2 -- returns 'b', 'c'
SUNION set1 set2 -- returns 'a', 'b', 'c', 'd'
SDIFF set1 set2 -- returns 'a'
Real-world example A social networking feature finds mutual friends between two users using SINTER on their respective friend sets, quickly identifying shared connections without needing to write custom comparison logic.

Common follow-ups: Are there store variants of these commands that save the result directly into a new set?;How does the performance of these operations scale with the size of the sets involved?

Data Types;Distributed Locks with Redis

How do sorted sets differ from regular sets, and what additional capability does the associated score provide?

Intermediate
A sorted set also guarantees unique members like a regular set, but additionally associates a numeric score with each member, which Redis uses to automatically maintain the members in a consistently sorted order, enabling powerful range based queries and ranking operations that a regular unordered set simply cannot support.
ZADD scores 85 'alice'
ZADD scores 92 'bob'
ZRANGE scores 0 -1 WITHSCORES -- returns sorted by score
Real-world example A quiz application stores participant scores in a sorted set, automatically keeping everyone ranked by their score and letting the application instantly retrieve the current standings without any manual sorting logic.

Common follow-ups: Can two different members have the exact same score in a sorted set?;How does Redis handle sorting when two members do share the same score?

Leaderboards with Sorted Sets;Data Types

How would you use sorted sets to implement a simple tag based content recommendation system, finding content similar to a given item?

Advanced
You could store each piece of content's tags in a set, and to find similar content, calculate the intersection between a target item's tag set and the tag sets of other candidate items, using the size of that intersection as a similarity score, then use a sorted set to rank candidates by how many tags they share with the target item.
SINTERSTORE temp_similarity item1_tags item2_tags
ZADD similarity_scores <intersection_size> 'item2'
Real-world example A content platform recommends articles to readers by calculating tag overlap between the article they just read and other available articles, ranking recommendations using a sorted set based on how many tags each candidate shares with the original.

Common follow-ups: How does this simple tag based approach compare to more sophisticated recommendation algorithms?;How would you scale this approach for a catalog with millions of items?

Leaderboards with Sorted Sets;Data Types

What internal memory encoding does Redis use for small sets and sorted sets, and how does this affect performance and memory usage as they grow?

Advanced
Redis stores small sets containing only integers using a highly compact intset encoding, and small sets or sorted sets in general using a compact listpack encoding, automatically switching to a full hash table or skip list based structure once they exceed configurable size thresholds, trading memory efficiency for improved performance on larger collections.
OBJECT ENCODING myset
CONFIG GET set-max-intset-entries
CONFIG GET zset-max-listpack-entries
Real-world example A team storing many small sets of numeric identifiers benefits significantly from Redis's compact intset encoding, achieving meaningful memory savings across their large number of small collections compared to a less specialized encoding.

Common follow-ups: What are the specific size thresholds that trigger a switch to the larger encoding?;Does this encoding choice affect the actual commands available for interacting with the set?

Redis Memory Optimization;Data Types

How do you retrieve a random member, or several random members, from a Redis set without removing them?

Intermediate
You use the SRANDMEMBER command, optionally specifying a count of how many random members to retrieve, which returns one or more randomly selected members from the set without removing them, useful for features like randomly selecting a winner from a set of contest entries or showing a random sample of items.
SRANDMEMBER contest_entries 1
SRANDMEMBER contest_entries 5 -- returns 5 random unique members
Real-world example A contest application randomly selects a winner from a set of eligible entries using SRANDMEMBER, ensuring a fair, unbiased random selection process without needing to implement custom randomization logic.

Common follow-ups: What is the difference between SRANDMEMBER and SPOP for this kind of use case?;What happens if you request more random members than actually exist in the set?

Data Types;Redis CLI & Basic Commands