Appearance
Redis Production Setup
Production Checklist
redis.conf (production):
conf
# Memory
maxmemory 16gb
# Evict least recently used keys
maxmemory-policy allkeys-lru
# Persistence (choose one or both)
# 1. RDB (snapshot)
# Save if 1 key changed in 900s
save 900 1
# Save if 10 keys changed in 300s
save 300 10
# Save if 10,000 keys changed in 60s
save 60 10000
rdbcompression yes
rdbchecksum yes
# 2. AOF (append-only file) - recommended for durability
appendonly yes
# Balance: durability + performance
appendfsync everysec
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
# Replication
replica-read-only yes
# Disable if disk I/O is fast
repl-diskless-sync no
# Security
requirepass your-strong-password-here
# Only listen on private IPs
# IP ví dụ: thay bằng IP có thật trên máy; IP không tồn tại thì Redis không mở được socket (đo trên redis:8)
bind 10.0.1.5 127.0.0.1
protected-mode yes
# Clients
maxclients 10000
# Close idle clients after 5 minutes
timeout 300
# Slow log
# Log queries >10ms
slowlog-log-slower-than 10000
slowlog-max-len 128
# Performance
tcp-backlog 511
tcp-keepalive 300Connection pooling:
javascript
// Node.js (ioredis), cần cụm 3 nút: minh hoạ, không chạy độc lập
const Redis = require('ioredis')
const redis = new Redis.Cluster([
{ host: '10.0.1.5', port: 6379 },
{ host: '10.0.1.6', port: 6379 },
{ host: '10.0.1.7', port: 6379 }
], {
redisOptions: {
password: process.env.REDIS_PASSWORD,
// ioredis kết nối tới từng nút cụm (doc không nêu pool kết nối)
maxRetriesPerRequest: 3,
enableReadyCheck: true,
enableOfflineQueue: true,
// Timeouts
connectTimeout: 10000,
commandTimeout: 5000,
// Reconnect strategy (doc ioredis không nêu chắc retryStrategy trong redisOptions có áp cho nút cụm;
// cụm có clusterRetryStrategy (khi không nút khởi động nào truy cập được) và clusterNodeRetryStrategy (từng nút))
retryStrategy: (times) => {
const delay = Math.min(times * 50, 2000)
return delay
}
},
// Cluster options
scaleReads: 'slave', // Read from replicas
clusterRetryStrategy: (times) => Math.min(100 * times, 2000)
})
// Test connection:
redis.on('connect', () => console.log('Redis connected'))
redis.on('error', (err) => console.error('Redis error:', err))Monitoring Queries
1. Check memory usage:
bash
redis-cli INFO memory
# Key metrics:
# - used_memory_human: 14.2G (current memory usage)
# - used_memory_peak_human: 15.8G (peak usage)
# - maxmemory_human: 16G (configured limit)
# - mem_fragmentation_ratio: 1.23 (>1.5 = problem, consider restart)
# - evicted_keys: 12847 (keys evicted due to maxmemory)
# Alert if used_memory > 90% of maxmemory⚠️ GOTCHA: Memory Fragmentation Ratio > 1.5 Wastes RAM (RSS vượt dữ liệu 50%+)
Redis memory fragmentation occurs when the operating system's allocator (jemalloc/glibc malloc) allocates more memory than Redis actually uses. A fragmentation ratio > 1.5 means Redis RSS is 50%+ larger than its data (overhead = 1/3 of RSS or more), causing OOM kills even when logical memory usage is low.
Why it happens:
- Redis stores variable-size objects (strings, lists, hashes)
- Frequent key updates/deletes create memory "holes"
- OS allocator doesn't release freed memory back to OS (keeps it reserved)
- Memory layout becomes like Swiss cheese (allocated but unused gaps)
mem_fragmentation_ratio = RSS / used_memory(>1.5 = RSS vượt dữ liệu 50%; 2.0 = một nửa RSS là overhead)
Kịch bản minh hoạ (số ví dụ, không đo thật):
bash
# Redis configured with maxmemory 16GB
# Server has 20GB RAM
# Check memory stats
redis-cli INFO memory
# used_memory: 10GB (logical Redis data)
# used_memory_rss: 18GB (actual RAM consumed by Redis process!)
# mem_fragmentation_ratio: 1.80 (80% overhead!)
# BUG: Redis using 18GB RAM but only storing 10GB of data
# - 8GB wasted on fragmentation
# - System has only 2GB RAM left
# - Kernel triggers OOM killer
# - Redis killed despite being "under" maxmemory limit!
# Cause: Workload with frequent SET/DEL operations
# - Create 1M keys (100 bytes each) → 100MB used
# - Delete 500K keys → 50MB freed BUT memory not released
# - Create 1M new keys (100 bytes each) → allocate NEW 100MB
# - Total RSS: 200MB (used: 150MB, fragmented: 50MB)
# - Repeat 100 times → fragmentation ratio: 2.0+Bài học: dùng mem_fragmentation_ratio cùng used_memory_rss để báo động, và chừa RAM ngoài maxmemory (đo trên redis:8: dữ liệu 1,54M mà ratio 18,71 vì RSS nền, nên chỉ đọc ratio khi dataset đủ lớn).
How to detect:
bash
# Monitor fragmentation ratio
redis-cli INFO memory | grep mem_fragmentation_ratio
# mem_fragmentation_ratio:1.87
# Thresholds:
# < 1.0 = swapping (very bad, Redis using swap)
# 1.0 - 1.3 = healthy
# 1.3 - 1.5 = monitor
# > 1.5 = take action (restart or defragment)
# > 2.0 = critical (RSS gấp đôi dữ liệu: một nửa RAM của tiến trình là overhead)
# Check RSS (resident set size) vs used_memory
redis-cli INFO memory | grep -E 'used_memory_human|used_memory_rss_human'
# used_memory_human:10.2G (logical data)
# used_memory_rss_human:18.4G (actual RAM used)
# Gap = 8.2GB wasted!Prevention:
Enable active defragmentation (Redis 4.0+):
conf# redis.conf activedefrag yes # Defrag when fragmentation > 100% overhead # 10% fragmentation minimum active-defrag-threshold-lower 10 # 100% = ratio 2.0 active-defrag-threshold-upper 100 # CPU limits for defragmentation # Minimum 1% CPU active-defrag-cycle-min 1 # Maximum 25% CPU active-defrag-cycle-max 25 # Ignore small memory waste # Don't defrag if waste < 100MB active-defrag-ignore-bytes 100mbRestart Redis periodically (manual defragmentation):
bash
# Chạy trên primary hiện tại (Redis 6.2+): chuyển vai có phối hợp, chờ replica bắt kịp.
redis-cli FAILOVER
# Đo trên redis:8: sau FAILOVER nút cũ tự thành replica (role:slave, master_link_status:up).
redis-cli INFO replication
# Lưu cấu hình replicaof, nếu không nút sẽ khởi động lại như primary rỗng.
# Cần server khởi động bằng redis.conf (đo redis:8: chạy không file cấu hình thì CONFIG REWRITE báo lỗi).
redis-cli CONFIG REWRITE
# Lưu snapshot rồi tắt; systemd hoặc container khởi động lại nút này để dọn phân mảnh.
redis-cli SHUTDOWN SAVE
# Sau khi lên lại, nếu INFO replication báo role:master thì gắn lại:
# redis-cli REPLICAOF <ip-primary-mới> 6379
# Tỷ lệ phân mảnh về ~1.0 sau khi khởi động lại- Đừng kỳ vọng TTL giảm phân mảnh (key hết hạn giải phóng bộ nhớ giống DEL):
javascript
// Node.js (ioredis); minh hoạ, không chạy độc lập
await redis.set('session:123', data)
// Sau này...
await redis.del('session:123') // giải phóng bộ nhớ, có thể để lại lỗ trống
// TTL tiện cho dọn tự động nhưng phân mảnh y hệt DEL; dùng activedefrag
await redis.set('session:123', data, 'EX', 3600) // hết hạn sau 1 giờUse smaller key sizes and batching:
javascript// Node.js (ioredis); minh hoạ, không chạy độc lập // Nhiều key nhỏ: tốn overhead mỗi key (đo bằng MEMORY USAGE, không khẳng định phân mảnh) for (let i = 0; i < 1000000; i++) { await redis.set(`key:${i}`, `value${i}`) } // Hash cho dữ liệu liên quan: ít key hơn, ít overhead mỗi key (đo bằng MEMORY USAGE) await redis.hset('keys:batch1', { 'key:1': 'value1', 'key:2': 'value2', // ... 1000 keys in one hash })Monitor workload patterns:
javascript// Node.js (ioredis); minh hoạ, không chạy độc lập // Detect fragmentation-causing workload const info = await redis.info('stats') // If evicted_keys high + fragmentation high: // → maxmemory too low, frequent evictions cause fragmentation // If expired_keys high + fragmentation high: // → TTL-based expiration causing fragmentation // → Increase maxmemory or adjust TTLsAllocate sufficient RAM (account for fragmentation):
bash
# Không có hệ số cố định "RAM = maxmemory x 1.5". Theo Redis admin doc:
# - đặt maxmemory thấp hơn RAM trống (ví dụ doc: RAM trống 10 GB thì đặt 8-9 GB)
# - BGSAVE / AOF rewrite trong ca ghi nặng có thể dùng tới 2 lần bộ nhớ (copy-on-write)
# Đo thật: RSS đỉnh lúc BGSAVE và mem_fragmentation_ratio
redis-cli INFO memory | grep -E 'used_memory_rss_human|mem_fragmentation_ratio'Hệ điều hành (Linux, cần root; chưa chạy: cần Linux root, đối chiếu Redis admin doc):
bash
sysctl vm.overcommit_memory=1
echo never > /sys/kernel/mm/transparent_hugepage/enabled- Use jemalloc (better than glibc malloc):bash
# Check allocator redis-cli INFO server | grep mem_allocator # mem_allocator:jemalloc-5.2.1 # If using glibc malloc (worse fragmentation): # Compile Redis with jemalloc: make MALLOC=jemalloc
→ See also: Redis High Availability, Redis Anti-Patterns
2. Check slow queries:
bash
redis-cli SLOWLOG GET 10
# Example output:
# 1) 1) (integer) 142 # ID
# 2) (integer) 1704801234 # Timestamp
# 3) (integer) 15234 # Execution time (microseconds) = 15.2ms
# 4) 1) "KEYS" # ← Problem command!
# 2) "user:*"
# Alert on:
# - KEYS command (use SCAN instead)
# - Queries >100ms3. Check hit rate:
bash
redis-cli INFO stats
# Calculate hit rate:
# keyspace_hits: 10,284,719
# keyspace_misses: 847,234
# hit_rate = hits / (hits + misses) = 92.4%
# Target: >90% hit rate
# If <80% → review caching strategy or TTLs4. Check replication lag:
bash
# On master:
redis-cli INFO replication
# Check:
# - connected_slaves: 2
# - slave0: ip=10.0.1.6, state=online, offset=12847234, lag=0
# - slave1: ip=10.0.1.7, state=online, offset=12847234, lag=1
# Alert if lag >5 seconds5. Check key distribution (cluster):
bash
redis-cli CLUSTER INFO
# Check:
# - cluster_state: ok
# - cluster_slots_assigned: 16384
# - cluster_known_nodes: 6
# Check key distribution per node:
for node in $(redis-cli CLUSTER NODES | awk '{print $2}'); do
echo "$node"
addr=${node%@*}; redis-cli -h ${addr%:*} -p ${addr#*:} DBSIZE
done
# Alert if imbalance >20% (some nodes have 20% more keys)Backup Strategies
1. RDB snapshot:
bash
# Manual snapshot:
redis-cli BGSAVE
# Check status:
redis-cli LASTSAVE # Unix timestamp of last save
# Backup RDB file:
cp /var/lib/redis/dump.rdb /backup/redis-$(date +%Y%m%d).rdb
# Restore:
# 1. Stop Redis
# 2. Replace dump.rdb
# 3. Nếu appendonly yes thì Redis nạp AOF và bỏ qua dump.rdb (doc): dời appendonlydir đi chỗ khác,
# hoặc thêm vào redis.conf: preload-file rdb:/backup/redis-YYYYMMDD.rdb (Redis 8.10+)
# 4. Start Redis2. AOF backup:
bash
# Backup AOF file:
# Trước khi sao chép: redis-cli CONFIG SET auto-aof-rewrite-percentage 0, rồi chờ INFO persistence có aof_rewrite_in_progress:0 (doc).
cp -r /var/lib/redis/appendonlydir /backup/redis-aof-$(date +%Y%m%d)/
# Sau khi xong: đặt lại auto-aof-rewrite-percentage về giá trị cũ (ví dụ 100).
# Restore:
# 1. Stop Redis
# 2. Thay thư mục appendonlydir (Redis 7+ không còn một file appendonly.aof)
# 3. Start Redis (replays AOF)3. Redis Cluster backup:
bash
# Backup each node:
for node in node1 node2 node3; do
ssh $node "redis-cli BGSAVE && while [ \$(redis-cli INFO persistence | grep -c 'rdb_bgsave_in_progress:1') -eq 1 ]; do sleep 1; done && \
cp /var/lib/redis/dump.rdb /backup/redis-$node-$(date +%Y%m%d).rdb"
doneSecurity Hardening
1. Authentication:
conf
# redis.conf:
requirepass your-very-strong-password-here
# ACLs (Redis 6+). Giữ MỘT user quản trị trước khi tắt default, nếu không không còn user nào chạy CONFIG, INFO hay SHUTDOWN.
user admin on >admin-password ~* &* +@all
# Tắt user default ở production
user default off
user app_user on >app-password ~app:* +@read +@write -@dangerous
user readonly_user on >readonly-password ~* +@read2. Network security:
conf
# redis.conf:
# IP ví dụ: thay bằng IP có thật trên máy (IP không tồn tại thì Redis không mở được socket, đo)
# Chỉ lắng nghe IP riêng
bind 10.0.1.5 127.0.0.1
protected-mode yes
port 6379Firewall (cần root, chưa chạy):
bash
iptables -A INPUT -p tcp --dport 6379 -s 10.0.1.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 6379 -j DROP3. TLS/SSL (Redis 6+):
conf
# redis.conf:
tls-port 6380
# Tắt cổng không TLS
port 0
tls-cert-file /etc/redis/redis.crt
tls-key-file /etc/redis/redis.key
tls-ca-cert-file /etc/redis/ca.crt
# Yêu cầu chứng chỉ client
tls-auth-clients yesKết nối từ client:
bash
redis-cli --tls \
--cert /path/to/client.crt \
--key /path/to/client.key \
--cacert /path/to/ca.crt \
-h redis-host -p 6380Phải nhớ (Redis Production Setup):
- Chú thích redis.conf chỉ trên dòng riêng: chú thích cùng dòng làm Redis báo FATAL khi khởi động (đo trên redis:8).
- Bật AOF thì restart nạp AOF, không nạp dump.rdb: khôi phục từ RDB phải xử lý AOF trước.
- Chừa RAM cho copy-on-write khi BGSAVE (doc: tới 2 lần bộ nhớ) và dùng
activedefragthay vì tin hệ số cố định.