Redis Data Structures Deep Dive: Beyond Basic Key-Value
Explore Redis's powerful data structures: lists, sets, sorted sets, and hashes. Learn when and how to use each structure effectively.
Redis is usually described as a key-value store, but the values are typed: lists, sets, sorted sets, hashes and more, each with its own commands. Picking the right type is the difference between one O(log n) call and fetching a blob, editing it in your app and writing it back.
Redis Data Types Overview
Redis supports five main data types:
- Strings - Simple key-value pairs
- Lists - Ordered collections of strings
- Sets - Unordered collections of unique strings
- Sorted Sets - Sets with scores for ordering
- Hashes - Field-value pairs within a key
Lists: Ordered Collections
Redis stores a list as a quicklist: a doubly linked list of small packed arrays (listpacks). Pushing or popping at either end is O(1); reaching into the middle with LINDEX or LSET is O(n). Lesson 3 of the Redis course, Redis lists, hashes and sets, runs these commands with real output.
Common List Operations
# Add elements to the left (head)
LPUSH mylist "item1" "item2"
# Add elements to the right (tail)
RPUSH mylist "item3" "item4"
# Get list length
LLEN mylist
# Get elements by index
LINDEX mylist 0
# Get range of elements
LRANGE mylist 0 -1
Use Cases for Lists
- Message Queues: Use LPUSH/RPOP for FIFO queues
- Recent Activity: Store recent user actions
- Leaderboards: Maintain ordered lists of items
Sets: Unique Collections
Sets store unique strings and provide fast membership testing.
Set Operations
# Add members
SADD myset "member1" "member2" "member3"
# Check membership
SISMEMBER myset "member1"
# Get all members
SMEMBERS myset
# Set operations
SUNION set1 set2 # Union
SINTER set1 set2 # Intersection
SDIFF set1 set2 # Difference
Use Cases for Sets
- Tagging: Store tags for articles or products
- Friend Lists: Social network connections
- Unique Visitors: Track unique IP addresses
Sorted Sets: Ranked Collections
Sorted sets combine sets with scores, enabling efficient range queries and ranking. For two complete builds, a leaderboard and a sliding-window rate limiter, see Redis sorted set: leaderboard and rate limiter.
Sorted Set Operations
# Add members with scores
ZADD leaderboard 100 "player1" 200 "player2"
# Get rank of member
ZRANK leaderboard "player1"
# Get range by score
ZRANGEBYSCORE leaderboard 100 200
# Get top N members
ZREVRANGE leaderboard 0 9
Use Cases for Sorted Sets
- Leaderboards: Game scores, user rankings
- Time Series: Timestamped data points
- Priority Queues: Tasks with different priorities
Hashes: Field-Value Maps
Hashes store field-value pairs within a single key, perfect for object storage.
Hash Operations
# Set field values
HSET user:1001 name "John" email "john@example.com"
# Get field value
HGET user:1001 name
# Get all fields and values
HGETALL user:1001
# Increment numeric field
HINCRBY user:1001 score 10
Use Cases for Hashes
- User Profiles: Store user information
- Session Data: Session attributes
- Configuration: Application settings
Performance Considerations
Memory Usage
- Strings: Most memory-efficient for simple values
- Lists: Good for small to medium collections
- Sets: Memory overhead for uniqueness
- Sorted Sets: Highest memory usage due to score storage
- Hashes: Efficient for structured data
Operation Complexity
Understanding Big O complexity helps choose the right structure:
- O(1): HGET, SET, SADD
- O(log N): ZADD, ZRANK
- O(N): LRANGE, SMEMBERS
- O(N+M): Set operations (SUNION, SINTER)
Practical rules
Choose the Right Structure
- Simple values: Use Strings
- Ordered data: Use Lists or Sorted Sets
- Unique items: Use Sets
- Ranked data: Use Sorted Sets
- Object data: Use Hashes
Memory Optimization
# Use appropriate data types
# Instead of storing JSON strings
SET user:1001 '{"name":"John","email":"john@example.com"}'
# Use hashes for structured data
HSET user:1001 name "John" email "john@example.com"
Expiration Strategies
# Set expiration on keys
EXPIRE mykey 3600
# Set expiration on creation
SETEX mykey 3600 "value"
Example: a social media feed
Let’s build a simple social media feed using Redis data structures:
# User posts (List)
LPUSH user:1001:posts "Post about Redis"
LPUSH user:1001:posts "Another post"
# User followers (Set)
SADD user:1001:followers "user:1002" "user:1003"
# Timeline generation
# Get followers
SMEMBERS user:1001:followers
# For each follower, get recent posts
LRANGE user:1001:posts 0 9
Where to go next
The free Redis course covers each type with code you run yourself, plus persistence, replication and Cluster. If you are using these structures as a cache, caching with Redis covers cache-aside, TTLs and what happens when maxmemory fills up.