patternbashredisModeratepending
Redis data structures for common use cases
Viewed 0 times
redisdata structuressorted sethashcachequeueleaderboard
Problem
Need to choose the right Redis data structure for different application needs: caching, queues, counters, leaderboards.
Solution
Redis data structure selection guide:
Selection guide:
| Need | Data Structure |
|------|---------------|
| Cache/session | STRING with EX |
| User profile | HASH |
| Job queue | LIST (LPUSH/RPOP) |
| Unique visitors | SET or HyperLogLog |
| Leaderboard | SORTED SET |
| Event stream | STREAM |
| Rate limiting | STRING with INCR + EXPIRE |
# STRING: Simple cache, counters, locks
SET user:123:session "abc" EX 3600 # Cache with TTL
INCR page:views:homepage # Atomic counter
SET lock:job:42 1 NX EX 30 # Distributed lock
# HASH: Object storage
HSET user:123 name "Alice" email "alice@example.com"
HGETALL user:123
HINCRBY user:123 login_count 1
# LIST: Queue, recent items
LPUSH queue:emails '{"to":"alice@example.com"}'
RPOP queue:emails # FIFO queue
LPUSH recent:viewed:user123 "product:456"
LTRIM recent:viewed:user123 0 49 # Keep last 50
# SET: Unique collections, tags
SADD online:users "user:123" "user:456"
SISMEMBER online:users "user:123" # Is online?
SINTER tags:python tags:beginner # Intersection
# SORTED SET: Leaderboard, priority queue
ZADD leaderboard 1500 "alice" 1200 "bob" 1800 "charlie"
ZREVRANGE leaderboard 0 9 WITHSCORES # Top 10
ZRANK leaderboard "alice" # Alice's rank
# STREAM: Event log, message queue
XADD events * type "order" id "123"
XREAD COUNT 10 STREAMS events 0 # Read eventsSelection guide:
| Need | Data Structure |
|------|---------------|
| Cache/session | STRING with EX |
| User profile | HASH |
| Job queue | LIST (LPUSH/RPOP) |
| Unique visitors | SET or HyperLogLog |
| Leaderboard | SORTED SET |
| Event stream | STREAM |
| Rate limiting | STRING with INCR + EXPIRE |
Why
Choosing the right data structure in Redis means O(1) or O(log n) operations instead of building complex logic on top of simple key-value storage.
Context
Applications using Redis for caching, queuing, or real-time features
Revisions (0)
No revisions yet.