Redis
Updated: September 10, 2025Categories: Query, Backend
Printed from:
Redis Cheatsheet: Mastering In-Memory Data Structures and Caching
1. Connection and Basic Commands
Connecting to Redis
Bash
123456# Connect to local Redis server
redis-cli
# Connect to remote Redis server
redis-cli -h hostname -p port -a password
Basic Server Commands
Bash
123456# Check server status
PING # Returns PONG if Redis is running
INFO # Detailed server information
FLUSHALL # Clear all keys from all databases
FLUSHDB # Clear keys from the current database
2. Data Types and Structures
Redis supports multiple data structures, each optimized for specific use cases:
- Strings: Simple key-value storage
- Lists: Ordered collection of strings
- Sets: Unordered collection of unique strings
- Hashes: Field-value mappings
- Sorted Sets: Sets with associated scores
- Bitmaps: Bit-level operations
- HyperLogLog: Probabilistic cardinality estimation
- Streams: Append-only log of messages
3. Key Operations
Bash
123456789# Basic Key Management
SET key value # Set a key with a value
GET key # Retrieve a key's value
DEL key # Delete a key
EXISTS key # Check if key exists
EXPIRE key seconds # Set expiration for a key
TTL key # Check time-to-live for a key
KEYS pattern # Find keys matching a pattern (use cautiously)
4. String Operations
Bash
1234567891011# String Commands
SET user:1000 "John Doe" # Set a string value
SETNX key value # Set if not exists
SETEX key seconds value # Set with expiration
MSET key1 value1 key2 value2 # Set multiple keys
MGET key1 key2 # Get multiple keys
INCR counter # Increment integer value
DECR counter # Decrement integer value
APPEND key value # Append to existing string
STRLEN key # Get string length
5. List Operations
Bash
123456789# List Commands
LPUSH mylist value # Push to left side of list
RPUSH mylist value # Push to right side of list
LPOP mylist # Remove and return left-most item
RPOP mylist # Remove and return right-most item
LRANGE mylist 0 -1 # List all elements
LLEN mylist # Get list length
LINDEX mylist 2 # Get element at specific index
6. Set Operations
Bash
123456789# Set Commands
SADD myset member1 member2 # Add members to set
SMEMBERS myset # List all set members
SINTER set1 set2 # Intersection of sets
SDIFF set1 set2 # Difference between sets
SUNION set1 set2 # Union of sets
SISMEMBER myset member # Check if member exists
SCARD myset # Count set members
7. Hash Operations
Bash
12345678# Hash Commands
HSET user:1000 name "John" age 30 # Set hash fields
HGET user:1000 name # Get specific hash field
HGETALL user:1000 # Get all hash fields and values
HMSET user:1000 name "John" age 30 # Set multiple hash fields
HINCRBY user:1000 age 1 # Increment hash field
HDEL user:1000 name # Delete hash field
8. Sorted Set Operations
Bash
1234567# Sorted Set Commands
ZADD leaderboard 100 user1 200 user2 # Add with score
ZRANGE leaderboard 0 -1 # List all members
ZRANK leaderboard user1 # Get member's rank
ZREVRANGE leaderboard 0 9 # Top 10 members
ZSCORE leaderboard user1 # Get member's score
9. Pub/Sub Messaging
Bash
12345# Publish/Subscribe
SUBSCRIBE channel # Subscribe to a channel
PUBLISH channel message # Publish a message
UNSUBSCRIBE channel # Unsubscribe from channel
10. Transactions and Pipelining
Bash
123456789101112# Transactions
MULTI # Start transaction
SET key1 value1
SET key2 value2
EXEC # Execute transaction
# Pipelining (in client library)
pipeline = redis.pipeline()
pipeline.set('key1', 'value1')
pipeline.get('key1')
results = pipeline.execute()
11. Scripting with Lua
lua
12345-- Lua Script Example
redis.call('SET', 'counter', 10)
local value = redis.call('GET', 'counter')
return value
12. Persistence and Backup
Bash
123456789# Persistence Modes
# RDB (point-in-time snapshots)
SAVE # Create immediate snapshot
BGSAVE # Background save
# AOF (append-only file)
CONFIG SET appendonly yes
CONFIG SET appendfsync everysec
13. Performance Optimization
Bash
12345678910# Memory Management
CONFIG SET maxmemory 2gb # Set memory limit
CONFIG SET maxmemory-policy allkeys-lru # Eviction policy
# Performance Tips
- Use appropriate data structures
- Minimize key sizes
- Use pipelining
- Avoid expensive operations on large datasets
14. Common Caching Patterns
Bash
12345678910111213141516# Cache Aside Pattern
def get_user(user_id):
user = redis.get(f'user:{user_id}')
if not user:
user = database.get_user(user_id)
redis.setex(f'user:{user_id}', 3600, user)
return user
# Rate Limiting
def is_allowed(user_id):
key = f'rate_limit:{user_id}'
current = redis.incr(key)
if current == 1:
redis.expire(key, 60) # Reset after 1 minute
return current <= 10 # 10 requests per minute
Best Practices
- Use appropriate data structures
- Set expiration on cache keys
- Be mindful of memory usage
- Use pipelining for bulk operations
- Consider data persistence needs
- Monitor performance and memory consumption
Recommended Tools
- Redis CLI
- Redis Desktop Manager
- Redmon (monitoring)
- redis-py (Python client)
- ioredis (Node.js client)
Learning Resources
- Official Redis Documentation
- Redis University
- Redis in Action (book)
- RedisLabs Blog
Continue Learning
Discover more cheatsheets to boost your productivity