Redis Best Practices
Contents
Quick Start
Installation & Version
Current version is Redis 8.6.2.
macOS
# Install via Homebrew
brew install redis
# Start service
brew services start redis
# Or start manually
redis-server
# Connect
redis-cliWindows
Redis doesn’t natively support Windows, but can be used via:
# Method 1: Use WSL2 (recommended)
# Install Redis in WSL2
sudo apt update && sudo apt install redis-server
sudo service redis-server start
# Method 2: Use Docker
docker run -d --name redis -p 6379:6379 redis:8.6.2-alpine
# Method 3: Download Microsoft-maintained Windows version (unofficial)Linux (Ubuntu)
# Update and install
sudo apt update
sudo apt install -y redis-server
# Start service
sudo systemctl start redis-server
sudo systemctl enable redis-server
# Or start manually
redis-server
# Connect
redis-cliDocker Compose Deployment
services:
redis:
image: redis:8-alpine
container_name: redis
restart: unless-stopped
ports:
- "6379:6379"
command: redis-server --requirepass password123
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "-a", "password123", "ping"]
interval: 10s
timeout: 5s
retries: 5
volumes:
redis_data:Start: docker compose up -d
Connect: redis-cli -h localhost -p 6379 -a password123
Basic Operations
# Test connection
PING
# View all keys
SCAN 0
# Basic data type operations
SET name "Alice"
GET name
DEL name
# View info
INFOData Types
String
# Basic operations
SET name "Alice"
GET name
MGET name age # Batch get
MSET name "Alice" age 30 # Batch set
# Counter operations
SET counter 100
INCR counter # 101
INCRBY counter 10 # 111
DECR counter # 110
# Set with expiration
SET token "abc123" EX 3600 # 1 hour
TTL token # Check remaining timeHash
# Create hash
HSET user:1 name "Alice" email "[email protected]" age 30
# Get fields
HGET user:1 name
HMGET user:1 name email
# Get all fields
HGETALL user:1
# Increment
HINCRBY user:1 age 1List
# Add elements
LPUSH tasks "task1"
RPUSH tasks "task2"
LPUSH tasks "task0"
# Get range
LRANGE tasks 0 -1 # Get all
# Pop elements
LPOP tasks
RPOP tasksSet
# Add members
SADD tags "redis" "database" "cache"
# Get members
SMEMBERS tags
SISMEMBER tags "redis"
# Intersection, Union, Difference
SINTER tag1 tag2
SUNION tag1 tag2
SDIFF tag1 tag2Sorted Set
# Add members with score
ZADD leaderboard 100 "Alice"
ZADD leaderboard 200 "Bob"
ZADD leaderboard 150 "Charlie"
# Get by score
ZRANGE leaderboard 0 -1 WITHSCORES
# Get rank
ZRANK leaderboard "Alice"
ZREVRANK leaderboard "Alice"Stream
New in Redis 8.x, for message queues:
# Create stream
XADD mystream * sensor-id temp 25.5
# Read stream
XRANGE mystream - +
# Consumer group
XGROUP CREATE mystream mygroup $
# Read new messages
XREADGROUP GROUP mygroup consumer1 COUNT 10 STREAMS mystream ">"Caching Strategies
Cache Patterns
# Cache-Aside
# 1. Read: Check cache first, fallback to DB, write to cache
# 2. Update: Update DB first, then delete cache
# Write-Through
# Write to both cache and DB simultaneously
# Write-Behind
# Write to cache only, batch write to DB periodicallyExpiration Policies
# Set expiration
EXPIRE user:1 3600 # 1 hour
EXPIREAT user:1 1735689600 # Unix timestamp
# Lazy expiration: Check when accessed
# Periodic expiration: Random check every 100ms
# Memory eviction policies
# noeviction: Return error
# allkeys-lru: Evict least recently used
# volatile-lru: Evict LRU from expired keys
# allkeys-random: Random eviction
# volatile-random: Random from expired keys
# volatile-ttl: Evict shortest TTLCache Problems
# Cache穿透: Bloom filter or cache null values
SET cache:bloom:users "exists"
# Cache击穿: Mutex or logical expiration
# Use RedLock for distributed lock
# Cache雪崩: Add random jitter to TTL, persistence + multi-level cachePersistence
RDB (Snapshot)
# Configuration
save 900 1 # Save if 1 key changed in 900 seconds
save 300 10 # Save if 10 keys changed in 300 seconds
save 60 10000 # Save if 10000 keys changed in 60 seconds
# Manual trigger
BGSAVE
SAVE
# Check last save time
LASTSAVEAOF (Append Only File)
# Enable AOF
appendonly yes
# Sync policies
appendfsync always # Sync every write
appendfsync everysec # Sync every second (default)
appendfsync no # Let OS decide
# Rewrite and compress
BGREWRITEAOFHybrid Persistence
# Enable hybrid persistence
aof-use-rdb-preamble yesClustering
Master-Replica
# Configure replica
replicaof master-ip master-port
# Stop replication
REPLICAOF NO ONE
# Check replication status
INFO replicationSentinel
# Monitor master
sentinel monitor mymaster 127.0.0.1 6379 2
# Automatic failover
# Sentinel elects new master automaticallyCluster
# Create cluster
redis-cli --cluster create 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 \
--cluster-replicas 1
# Check cluster status
redis-cli -p 7001 cluster info
# Reshard
redis-cli --cluster reshard 127.0.0.1:7001Cluster Slots
# View slot allocation
redis-cli cluster slots
# Manual slot assignment
redis-cli -p 7001 cluster addslots 0 1 2 3 4Security
Authentication
# Set password
CONFIG SET requirepass "your_password"
# Authenticate
AUTH your_password
# Or in command line
redis-cli -a your_passwordACL
# Create user
ACL SETUSER alice ON >password ~cached:* -@all +get +set +del
# List users
ACL LIST
# Permission syntax
# + grant permission
# - revoke permission
# @ grant permission category
# ~ add key patternSecure Configuration
# Disable dangerous commands
rename-command FLUSHALL ""
rename-command CONFIG "CONFIG_b45a0e32"
# Bind address
bind 127.0.0.1
# Disable protected mode
protected-mode yesPerformance Optimization
Slow Query
# View slow query log
SLOWLOG GET
# Set threshold (microseconds)
CONFIG SET slowlog-log-slower-than 1000
# Max slow log entries
CONFIG SET slowlog-max-len 100Memory Optimization
# Check memory usage
INFO memory
MEMORY STATS
# Defragment
MEMORY PURGE
# Find big keys
redis-cli --bigkeysConnection Optimization
# Max clients
CONFIG SET maxclients 10000
# TCP tuning
CONFIG SET tcp-backlog 511
CONFIG SET tcp-keepalive 300Common Commands Reference
| Command | Description |
|---|---|
SET key value |
Set string value |
GET key |
Get value |
DEL key |
Delete key |
EXISTS key |
Check if key exists |
EXPIRE key seconds |
Set expiration |
KEYS pattern |
Pattern matching |
SCAN cursor |
Progressive iteration |
INFO |
View Redis info |
DBSIZE |
Key count |
FLUSHDB |
Clear current DB |
FLUSHALL |
Clear all DBs |