intermediate
Sets
Use sets for uniqueness, membership, intersections, and id collections where ordering is irrelevant.
Sets store unordered unique strings — ideal for membership tests, tag collections, idempotency key tracking, and set algebra without caring about order.
SADD article:9:tags redis nosql cache
SISMEMBER article:9:tags redis # O(1) membership
SMEMBERS user:42:roles
SINTER tag:redis tag:cache # articles with both tags
SUNIONSTORE tmp:all user:1:likes user:2:likes
SREM processed:events evt-991
| Use sets for | Avoid sets when | |--------------|-----------------| | Unique ids or tags | You need ordering or ranking | | Fast membership checks | Values are huge documents | | Intersection / union counts | Cardinality is millions per key | | Dedup windows with TTL on parent key | Range-by-score queries |
`SCARD` and `SMEMBERS` on very large sets are expensive — prefer bucketing keys or HyperLogLog for approximate counts. Sets fit "have we seen this event id?" dedup with a bounded TTL namespace.
On interviews: give a uniqueness or overlap problem and show why a set beats a list or string.
Common pitfalls: storing large JSON in set members; unbounded `SMEMBERS` on hot paths; using sets as a primary database; forgetting expiration strategy for dedup sets.
The trade-off is O(1) uniqueness checks versus memory per member — sets are compact for ids and tags but wrong when order, score, or payload size matters.
Checklist:
- Confirm uniqueness is the core requirement.
- Pick set ops: add, test, intersect, union.
- Plan key TTL or pruning for dedup windows.
- Estimate cardinality before `SMEMBERS`.