Appearance
Redis Performance Tuning
Pipeline (Batch Commands)
Problem: Multiple commands = multiple round-trips (network latency)
javascript
// Node.js (ioredis): import Redis from "ioredis"; const redis = new Redis(); RTT 1 ms chỉ là giả định minh hoạ
// ❌ Bad: 3 round-trips (3 × 1ms = 3ms)
await redis.get('user:123:name')
await redis.get('user:123:email')
await redis.get('user:123:age')Solution: Pipeline (batch commands, 1 round-trip)
javascript
// Node.js (ioredis): chạy sau khi tạo client `redis` ở khối trên
// ✅ Good: 1 round-trip (1ms)
const pipeline = redis.pipeline()
pipeline.get('user:123:name')
pipeline.get('user:123:email')
pipeline.get('user:123:age')
const results = await pipeline.exec()
// results = [[null, 'John'], [null, 'john@...'], [null, '30']]Performance gain: đo bằng redis-benchmark -t get -n 100000 -q trong container redis:8 (đổi theo máy, RTT loopback rất nhỏ so với mạng thật):
- Không pipeline (
-P 1): ~147 nghìn request/giây - Pipeline 100 lệnh mỗi lô (
-P 100): ~3,3 triệu request/giây
Transactions (MULTI/EXEC)
Atomic operations:
javascript
// Node.js (ioredis): chạy sau khi tạo client `redis` (mục Pipeline); đã chạy: exec() trả [[null,400],[null,100]]
// Atomic/isolated execution, but NO rollback: if one command errors at runtime, the others still apply
const multi = redis.multi()
multi.decrby('balance:123', 100) // Deduct $100
multi.incrby('balance:456', 100) // Add $100
await multi.exec()
// Both commands execute atomicallyOptimistic locking with WATCH:
javascript
// Node.js (ioredis): chạy sau khi tạo client `redis` (mục Pipeline); đã chạy: thoát vòng lặp, balance 300
// Retry loop for concurrent updates (minh hoạ: WATCH gắn với kết nối nên mỗi giao dịch song song cần kết nối riêng; thực tế đặt trần số lần thử)
while (true) {
await redis.watch('balance:123')
const balance = parseInt(await redis.get('balance:123'))
if (balance >= 100) {
const multi = redis.multi()
multi.decrby('balance:123', 100)
const result = await multi.exec()
if (result) {
break // Success
} else {
// Transaction aborted (balance changed during WATCH)
// Retry
}
} else {
await redis.unwatch()
throw new Error('Insufficient balance')
}
}Lua Scripts (Better Transactions)
Why Lua > MULTI/EXEC:
- ✅ Conditional logic on server-side
- ✅ Atomic (no WATCH needed)
- ✅ Fewer round-trips
lua
-- Deduct balance if sufficient (atomic)
local balance = tonumber(redis.call('GET', KEYS[1]) or '0') -- khoá chưa có thì coi là 0
if balance >= tonumber(ARGV[1]) then
redis.call('DECRBY', KEYS[1], ARGV[1])
return 1 -- Success
else
return 0 -- Insufficient balance
endjavascript
// Node.js (ioredis): chạy sau khi tạo client `redis` (mục Pipeline)
const script = `
local balance = tonumber(redis.call('GET', KEYS[1]) or '0')
if balance >= tonumber(ARGV[1]) then
redis.call('DECRBY', KEYS[1], ARGV[1])
return 1
else
return 0
end
`
const result = await redis.eval(script, 1, 'balance:123', 100)
if (result === 1) {
console.log('Success')
} else {
console.log('Insufficient balance')
}Memory Optimization
1. Use Hashes for objects (not Strings)
bash
# ❌ Bad: 1000 users as Strings (high memory overhead)
redis-cli SET user:1:name "John"
redis-cli SET user:1:age 30
redis-cli SET user:1:email "john@example.com"
# 1000 users × 3 keys = 3000 keys (each key has overhead)
# ✅ Good: 1000 users as Hashes (lower memory)
redis-cli HSET user:1 name "John" age 30 email "john@example.com"
# 1000 users = 1000 keys (đo trên redis:8: ~189 KB dạng String, ~121 KB dạng Hash listpack, ít hơn ~1,6 lần)Memory saved: often significant for small objects (measure with MEMORY USAGE)
2. Use hash-max-listpack settings
conf
# Hash dùng listpack (mã hoá gọn) khi số field <= 512 và mỗi giá trị <= 64 byte (mặc định của redis:8)
hash-max-listpack-entries 512
hash-max-listpack-value 64
# Kiểm bằng: redis-cli OBJECT ENCODING user:1 (kết quả: listpack)3. Set TTL to avoid memory leaks
bash
# ❌ Bad: No expiration (memory leak)
redis-cli SET session:abc123 "token"
# ✅ Good: Auto-expire after 1 hour
redis-cli SET session:abc123 "token" EX 36004. Use SCAN instead of KEYS (non-blocking)
bash
# ❌ Bad: KEYS blocks Redis (production killer)
redis-cli KEYS 'user:*' # SLOWLOG đo 142 ms trên redis:8 với 1 000 000 key (đổi theo máy)
# ✅ Good: SCAN (non-blocking, cursor-based)
redis-cli SCAN 0 MATCH 'user:*' COUNT 100
# COUNT chỉ là gợi ý: số key mỗi lượt có thể khác 100; gọi lại với cursor trả về tới khi cursor = 0Eviction Policies
When maxmemory reached, what to evict?
conf
maxmemory 2gb
# Evict least recently used (any key)
maxmemory-policy allkeys-lruPolicies:
noeviction- Return errors (don't evict)allkeys-lru- ✅ Evict LRU (recommended for caching)volatile-lru- Evict LRU (only keys with TTL)allkeys-lfu- Evict LFU (least frequently used, Redis 4.0+)volatile-lfu- Evict LFU (only keys with TTL)allkeys-random- Evict random keyvolatile-random- Evict random (only keys with TTL)volatile-ttl- Evict key with nearest expire time
Recommendation:
- Cache:
allkeys-lru(evict least used) - Session store:
volatile-ttl(evict by expiration) - Truy cập lệch mạnh: thử
allkeys-lfu(evict least frequent); so vớiallkeys-lrubằngkeyspace_hits/keyspace_misses
Slow Log Monitoring
Track slow commands:
bash
# Log commands slower than 10ms (10000 µs là mặc định; slowlog-max-len mặc định 128)
redis-cli CONFIG SET slowlog-log-slower-than 10000
# View slow log
redis-cli SLOWLOG GET 10text
Kết quả (rút gọn, đo trên redis:8 với KEYS user:* trên 1 000 000 key):
1) 1) (integer) 1 # id mục log
2) (integer) 1795402914 # timestamp Unix
3) (integer) 141952 # thời gian chạy tính bằng µs (~142 ms)
4) 1) "KEYS" # lệnh và tham số
2) "user:*"
5) "127.0.0.1:48572" # địa chỉ client
6) "" # tên client
7) (integer) 2 # tổng số đối số của lệnh (từ Redis 8.10)Optimization based on slow log:
KEYS *→ UseSCAN- Large
LRANGE→ Use pagination SMEMBERSon large set → UseSSCAN- Unoptimized Lua script → Optimize script
Phải nhớ:
- Gộp lệnh bằng pipeline để giảm round-trip; đo bằng
redis-benchmark -P. - Thay
KEYSbằngSCAN; theo dõi lệnh chậm bằngSLOWLOG(mặc địnhslowlog-log-slower-than 10000µs,slowlog-max-len 128). latency-monitor-thresholdmặc định 0 (tắt): bật khi cần chẩn đoán độ trễ.