Lists and sets in depth
A list remembers order and allows duplicates. A set forgets order and refuses duplicates. Pick by the question you will ask.
Anatomy of a list
- LPUSH adds at the left, the head. The newest item is always index 0.
- RPUSH adds at the right, the tail.
- Indexes count from the head (0, 1, 2…) or from the tail (-1, -2…). LRANGE list 0 -1 reads everything.
- LPOP and RPOP remove from either end in constant time, even for a list of millions.
- Reaching into the middle (LINDEX 2, LINSERT, LSET) walks the list. Fine for short lists, slow for huge ones.
Stack, queue, capped feed
List lab
LPUSH / RPUSH key v [v …]
LPOP / RPOP key
LRANGE key 0 -1 LLEN key
LINDEX key -1 LTRIM key 0 99
BLPOP / BRPOP key 5 # wait up to 5 s
LMOVE src dst LEFT RIGHTActivity feeds and “recently viewed” (LPUSH + LTRIM), simple job queues (LPUSH + BRPOP), chat history for one room.
LRANGE key 0 -1 on a list of a million items blocks Redis. Page it: LRANGE key 0 49. An empty list is deleted automatically.
Sets and set algebra
- SINTER: members in both sets. “People who follow Ana and Ben.”
- SUNION: members in either set, each once. “Everyone tagged redis or cache.”
- SDIFF: members of the first set not in the others. “Posts this user has not seen yet.”
- And the rule underneath it all: a member is stored once. SADD returns 0 for a duplicate, which makes sets perfect for “have I processed this id?”.
…STORE variants (SINTERSTORE dest a b) to save the result as a new set.Set lab
SADD / SREM key m [m …]
SISMEMBER key m SCARD key
SMEMBERS key SSCAN key 0
SINTER / SUNION / SDIFF a b
SRANDMEMBER key SPOP keyTags, “who is online” (SADD online u42), idempotency (“already sent this webhook?”), random winner picks with SPOP.
No order. Need “newest first” or a score? Use a sorted set. SMEMBERS on a huge set blocks — iterate with SSCAN.
List, set, sorted set, or hash?
| “What came first / last?” | List — order of arrival, duplicates allowed. |
|---|---|
| “Is x in there?” | Set — unique members, O(1) membership, set algebra. |
| “Who ranks highest?” | Sorted set — unique members ordered by a score. Leaderboard. |
| “What is field f of object o?” | Hash — fields of one object. Cart. |
Quick check
Show answer
LPUSH recent:u42 /page then LTRIM recent:u42 0 19, ideally in one MULTI or pipeline.
Show answer
SADD seen:webhooks evt_91. If it returns 1, process; if 0, skip. Add a TTL or a daily key so the set does not grow forever.