9. Sets: Uniqueness & Intersection Operations
Unique Collections and Hash Set Representation
Redis Sets are unordered collections of unique strings. When you add a member to a Set using the SADD command, Redis guarantees that duplicates are ignored automatically. Under the hood, Sets are represented using two different internal structures: IntSets and Hash Tables. If a set consists entirely of integer strings, Redis stores them inside a sorted array of integers called an IntSet. This array is memory-efficient and uses binary search for lookups (O(log N)).
If a member containing non-numeric characters is added, or if the set size grows beyond set-max-intset-entries, Redis converts the set to a standard Hash Table (dict). In this representation, the set members are stored as the keys of the hash table, and the values are set to null pointers. This allows Redis to achieve O(1) constant-time complexity for adding, removing, and testing membership via SISMEMBER, regardless of set size.
Set uniqueness makes them ideal for tracking collections of unique entities. For example, tracking online users, unique IP visitors, or dynamic category tags. Checking membership in a Redis Set is significantly faster than scanning a relational database table or evaluating arrays in application code, making sets a key building block for real-time analytics.
Set Algebra in RAM: Intersections and Social Graphs
The power of Redis Sets lies in their ability to perform algebraic set calculations directly inside RAM. Rather than pulling large datasets into application memory to calculate intersections or unions, developers run set commands directly on the Redis server:
SINTER: Computes the intersection of multiple sets (returning members present in all sets).SUNION: Computes the union of multiple sets (returning all unique members across all sets).SDIFF: Computes the difference (returning members present in the first set but absent from subsequent sets).
These calculations are optimized to run in microseconds. A common use case is building social network graphs. If User A's followers are stored in a set, and User B's followers in another, calculating mutual friends requires a single SINTER command. This is fast and scales to millions of users.
Sets are also useful for faceted catalog searches. If you have sets for product properties (e.g., tag:electronics, tag:wireless, tag:brand_sony), you can find matching products by intersecting these sets. This allows applications to filter products dynamically without executing expensive database JOINs.
// Social Graph Analysis using Set Algebra const Redis = require('ioredis'); const redis = new Redis({ host: '127.0.0.1', port: 6379 }); async function getRecommendedFriends(userId) { const userFollowersKey = `user:${userId}:following`; const recommendedSetKey = `user:${userId}:recommendations`; // Find friends of my friends who I do not follow yet // Step 1: Get the list of people I follow const friends = await redis.smembers(userFollowersKey); if (friends.length === 0) return []; // Step 2: Union all the people they follow const friendsFollowingKeys = friends.map(id => `user:${id}:following`); await redis.sunionstore(recommendedSetKey, ...friendsFollowingKeys); // Step 3: Subtract the people I already follow to find new recommendations const recommendationList = await redis.sdiff(recommendedSetKey, userFollowersKey, `user:${userId}`); // Clean up temporary keys await redis.del(recommendedSetKey); return recommendationList; }
Knowledge Check
Ready to test your understanding of 9. Sets: Uniqueness & Intersection Operations?