Redis Tutorial 0/42 lessons ~6 min read Lesson 10

    Sets

    Sets store unique unordered strings — O(1) SADD and SISMEMBER make them perfect for tags, unique visitors, permission roles, and graph adjacency lists.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Sets store unique unordered strings — O(1) SADD and SISMEMBER make them perfect for tags, unique visitors, permission roles, and graph adjacency lists.

    Redis uses intset encoding for small integer-only sets and hash table for larger or string members. Set operations (SUNION, SINTER) power recommendation and filtering features.

    When order or ranking matters, use sorted sets instead — plain sets cannot sort by score.

    Understanding the topic

    Key concepts

    • SADD key member — add; returns count of new elements.
    • SISMEMBER — O(1) existence check.
    • SMEMBERS — returns all members; O(N) danger on large sets.
    • SUNION/SINTER/SDIFF — combine sets server-side.
    • SCARD — cardinality count.
    • SRANDMEMBER — random sampling.

    Step-by-step explanation

    1. Small integer sets stored as sorted intset array.
    2. Grows to hash table when size or type thresholds exceeded.
    3. Set commands run atomically on single key.
    4. Multi-key ops (SINTER) block until complete.
    5. No duplicate members — SADD idempotent.

    Syntax reference

    Common commands

    • SISMEMBER — feature flag / role check.
    • Avoid SMEMBERS on huge sets — use SSCAN.
    • SINTER — mutual followers, shared tags.
    bash
    SADD article:42:tags redis cache nosql
    SISMEMBER article:42:tags redis
    SCARD article:42:tags
    SINTER tag:redis tag:cache

    Informative example

    Track unique article viewers per day with set cardinality:

    java
    @Service
    public class UniqueViews {
    private final StringRedisTemplate redis;
    public UniqueViews(StringRedisTemplate redis) {
    this.redis = redis;
    }
    public long recordView(String articleId, String userId) {
    String key = "views:" + articleId + ":" + LocalDate.now();
    redis.opsForSet().add(key, userId);
    redis.expire(key, Duration.ofDays(2));
    return redis.opsForSet().size(key);
    }
    }

    For approximate counts at scale use HyperLogLog. Sets are exact but memory-heavy for millions of users.

    Real-world use

    Real-world use cases

    • Article tags and filtered browse (SINTER).
    • Unique daily active users per page (exact, small scale).
    • Mutual connections — SINTER friends:a friends:b.
    • Blacklist IP set — SISMEMBER on each request.
    • Lottery draw — SRANDMEMBER without replacement pattern.

    Best practices

    • Use SSCAN not SMEMBERS for large sets.
    • Set TTL on daily analytics keys.
    • Prefer HLL when ~1% error acceptable for UV counts.
    • Namespace: article:{id}:tags.
    • Limit set size — split by shard if millions of members.
    • SINTER on large sets is expensive — precompute or cache.

    Common mistakes

    • SMEMBERS on million-member set in production.
    • Using set when you need sorted ranking.
    • No expiry on daily UV sets — memory accumulates.
    • Storing large JSON blobs as set members.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionWhat is a Redis set?+

    Answer

    Unordered collection of unique strings.
    2BeginnerQuestionSISMEMBER complexity?+

    Answer

    O(1) average.
    3IntermediateQuestionSINTER use case?+

    Answer

    Find common elements — mutual tags, shared friends.
    4IntermediateQuestionSet vs HyperLogLog for UV?+

    Answer

    Set exact O(N) memory; HLL ~12KB fixed ~0.81% error.
    5AdvancedQuestionDesign tag system for 10M articles?+

    Answer

    Set per article capped tags; inverted index via set per tag; SINTER cached; shard hot tags.

    Summary

    Sets = unique membership, O(1) lookup.

    Ready to mark this lesson complete?Track your journey across the entire course.