Appearance
Redis Data Structures
Redis là gì?
Tình huống: DB chính quá tải vì cùng một truy vấn đọc lặp lại liên tục; hoặc cần đếm, xếp hạng, giới hạn tốc độ mà không khoá bảng.
Quy tắc: Dùng Redis cho dữ liệu nóng, nhỏ, mất được hoặc dựng lại được / Đừng dùng làm kho chính khi chưa chọn persistence và đo RAM.
Ẩn dụ: Redis là bàn làm việc: nhanh, chật, mất khi mất điện nếu không lưu. (Ẩn dụ sai ở chỗ: Redis lưu được xuống đĩa bằng RDB/AOF và nhân bản sang replica.)
Vì sao nhanh: dữ liệu nằm trong RAM; lệnh chạy trên một luồng chính nên mỗi lệnh là atomic (INCR, LPUSH, ZADD). Cũng vì một luồng chính, một lệnh chậm (KEYS, SAVE, Lua chạy lâu) chặn mọi client.
| Có sẵn | Dùng cho |
|---|---|
| String, Hash, List, Set, Sorted Set, Stream | Cache, session, counter, queue, leaderboard, event log |
| JSON, Time Series, probabilistic (Bloom, Cuckoo, Count-min sketch, Top-K, t-digest), Vector Set, Query Engine | Có sẵn trong core từ Redis 8; trước đó phải cài module Redis Stack |
| Pub/Sub | Thông báo tức thời, at-most-once: client mất kết nối là mất tin |
| Lua script, Functions | Logic phía server chạy atomic |
| RDB, AOF | Persistence, xem Redis Persistence |
Use case phổ biến: cache (nhiều nhất), session, rate limiting, leaderboard, real-time analytics, queue.
Core Data Structures
1. Strings (most basic)
bash
# Set/Get
redis-cli SET user:123:name "John Doe"
redis-cli GET user:123:name
# → "John Doe"
# Expiration (TTL)
redis-cli SET session:abc123 "token" EX 3600 # Expire in 1 hour
redis-cli TTL session:abc123
# → (integer) 3600 (giảm dần theo giây)
# Atomic increment (counters)
redis-cli SET page:views 0
redis-cli INCR page:views
redis-cli INCR page:views
redis-cli GET page:views
# → "2"
# Use cases: Caching, counters, rate limiting2. Hashes (objects/maps)
bash
# Store user object
redis-cli HSET user:123 name "John" age 30 email "john@example.com"
redis-cli HGET user:123 name
# → "John"
redis-cli HGETALL user:123
# → 1) "name" 2) "John" 3) "age" 4) "30" 5) "email" 6) "john@example.com"
# Increment field
redis-cli HINCRBY user:123 age 1
# → (integer) 31
# Redis 8.0+: TTL riêng cho từng field (HSETEX, HTTL)
redis-cli HSETEX user:123 EX 100 FIELDS 1 otp 482913
redis-cli HTTL user:123 FIELDS 1 otp
# → 1) (integer) 100
# Use cases: User profiles, session data, object caching3. Lists (ordered collections)
bash
# Push to list (queue)
redis-cli LPUSH queue:jobs job1
redis-cli LPUSH queue:jobs job2
redis-cli LPUSH queue:jobs job3
# → list là [job3, job2, job1]
# Pop from list
redis-cli RPOP queue:jobs
# → "job1"
# Blocking pop: returns at once when the list has items; waits up to 5 s only when it is empty
redis-cli BRPOP queue:jobs 5
# → 1) "queue:jobs" 2) "job2"
# Range query (all items)
redis-cli LRANGE queue:jobs 0 -1
# → 1) "job3"
# Use cases: activity feeds, recent items, simple queues
# Risk: RPOP/BRPOP removes the job before it is processed; worker crash = job lost.
# Need at-least-once: BLMOVE into a processing list, or Streams + XACK
redis-cli BLMOVE queue:jobs queue:processing RIGHT LEFT 54. Sets (unordered unique collections)
bash
# Add members
redis-cli SADD tags:article:123 "redis" "database" "nosql"
redis-cli SADD tags:article:456 "redis" "cache"
# Check membership
redis-cli SISMEMBER tags:article:123 "redis"
# → (integer) 1 (true)
# Set operations (thứ tự phần tử trả về không đảm bảo)
redis-cli SINTER tags:article:123 tags:article:456 # Intersection
# → "redis"
redis-cli SUNION tags:article:123 tags:article:456 # Union
# → "redis", "database", "nosql", "cache" (thứ tự bất kỳ)
redis-cli SDIFF tags:article:123 tags:article:456 # Difference
# → "database", "nosql" (thứ tự bất kỳ)
# Random member (useful for randomization)
redis-cli SRANDMEMBER tags:article:123
# Use cases: Tags, unique visitors, social graphs (followers)5. Sorted Sets (tập hợp duy nhất có thứ tự, theo score)
bash
# Add members with scores
redis-cli ZADD leaderboard 100 "player1"
redis-cli ZADD leaderboard 200 "player2"
redis-cli ZADD leaderboard 150 "player3"
# Top 10 players (descending)
redis-cli ZRANGE leaderboard 0 9 REV WITHSCORES
# → 1) "player2" 2) "200" 3) "player3" 4) "150" 5) "player1" 6) "100"
# Rank (position)
redis-cli ZREVRANK leaderboard "player2"
# → (integer) 0 (first place)
# Score range query
redis-cli ZRANGE leaderboard 100 200 BYSCORE
# → "player1", "player3", "player2"
# Increment score
redis-cli ZINCRBY leaderboard 50 "player1"
# → "150"
# Use cases: Leaderboards, priority queues, time-series (score=timestamp)6. Streams (append-only log)
bash
# Add entry (Redis 5.0+); * = server generates ID <unix time in ms>-<sequence> (đặt trong nháy để shell không mở rộng dấu *)
redis-cli XADD events:user:123 '*' action "login" timestamp 1640000000
# → "1794969316668-0" (server clock in ms, not the timestamp field)
# Read all entries
redis-cli XRANGE events:user:123 - +
# → 1) 1) "1794969316668-0" 2) 1) "action" 2) "login" 3) "timestamp" 4) "1640000000"
# Consumer groups (Kafka-like); dấu > cũng cần nháy
redis-cli XGROUP CREATE events:user:123 mygroup 0
redis-cli XREADGROUP GROUP mygroup consumer1 COUNT 10 STREAMS events:user:123 '>'
# Acknowledge after processing; un-acked entries stay in the pending list (XPENDING) for retry
# (thay ID dưới đây bằng ID mà XADD đã in ra)
redis-cli XACK events:user:123 mygroup 1794969316668-0
# → (integer) 1
# Use cases: Event sourcing, audit logs, message queuesRedis Persistence
Tình huống: restart Redis xong, toàn bộ session biến mất; hoặc khôi phục từ backup thì thiếu vài giờ dữ liệu.
Quy tắc: Chọn persistence theo lượng dữ liệu chấp nhận mất khi crash, rồi chừa RAM cho fork.
Vì sao: RDB chụp toàn bộ dataset theo chu kỳ, nên crash mất mọi ghi sau lần chụp cuối; AOF ghi nối từng lệnh, appendfsync everysec mất tối đa khoảng 1 giây ghi. Cả hai đều fork một child process để ghi file (BGSAVE, AOF rewrite).
| Chế độ | Mất khi crash | Chi phí | Dùng khi |
|---|---|---|---|
| Không persistence | Toàn bộ | Không | Cache thuần, dựng lại được từ DB chính |
| RDB | Từ lần snapshot cuối | Fork định kỳ; file gọn, khởi động nhanh | Backup, chấp nhận mất vài phút |
AOF everysec | Khoảng 1 giây ghi | Fork khi rewrite; file lớn hơn RDB | Session, queue, dữ liệu phải giữ |
| AOF + RDB | Như AOF | Như AOF, thêm file RDB để backup | Redis giữ dữ liệu quan trọng |
Ví dụ giải sẵn (redis-cli):
bash
# Triệu chứng: restart là mất dữ liệu. Đo cấu hình hiện tại:
redis-cli CONFIG GET appendonly
# → 1) "appendonly" 2) "no"
redis-cli CONFIG GET save
# → 1) "save" 2) "3600 1 300 100 60 10000" (chỉ RDB: mất mọi ghi sau snapshot cuối)
# Sửa: bật AOF lúc đang chạy
redis-cli CONFIG SET appendonly yes
redis-cli CONFIG SET appendfsync everysec
# Đo lại
redis-cli INFO persistence | grep -E 'aof_enabled|aof_last_write_status|rdb_last_bgsave_status'
# → aof_enabled:1, aof_last_write_status:ok, rdb_last_bgsave_status:okBẫy production: CONFIG SET không ghi vào redis.conf; restart là quay lại cấu hình cũ. Sửa cả redis.conf (hoặc CONFIG REWRITE nếu server chạy với file config). Theo dõi aof_last_write_status, rdb_last_bgsave_status, latest_fork_usec. Lui: CONFIG SET appendonly no.
Option 1: RDB (Redis Database) - Snapshots
conf
# Save snapshot every 60 seconds if 1000+ keys changed
save 60 1000bash
# Manual save
redis-cli SAVE # Blocking (production: don't use)
redis-cli BGSAVE # Background (use this)- ✅ Gọn, nạp nhanh (doc: 'RDB allows faster restarts with big datasets compared to AOF')
- ✅ Hợp để backup
- ❌ Mất dữ liệu từ lần snapshot cuối tới lúc crash
⚠️ BẪY: lệnh SAVE chặn mọi client (cả Redis đứng im)
SAVE tạo snapshot ngay trên luồng chính và chặn cả instance tới khi xong: mọi request đọc lẫn ghi đều chờ, nên gây gián đoạn hoàn toàn, dài hay ngắn tuỳ kích thước dataset và tốc độ đĩa.
Vì sao xảy ra:
SAVEchạy đồng bộ trên luồng chính của Redis- Redis xử lý lệnh trên một luồng
- Lúc ghi file .rdb xuống đĩa, không lệnh nào khác được chạy
- Dataset lớn có thể mất hàng chục giây hoặc hơn (đổi theo đĩa và dataset)
Kịch bản minh hoạ, không phải sự cố có nguồn (số liệu là ví dụ):
bash
# Production Redis with 20GB data, 50K requests/sec
# Operator runs SAVE for backup (thinking it's quick)
redis-cli SAVE
# [Redis FREEZES for 45 seconds]
# During freeze:
# - All 50K req/sec timeout
# - Clients retry → connection pool exhaustion
# - Application shows error pages
# - Monitoring alerts fire: "Redis down!"
# - Total requests failed: 2.25M (50K × 45s)
# After SAVE completes:
# - Redis accepts commands again
# - Damage: every request in those 45 s failed (SAVE loses no data, but the outage is user-visible)Bài học: chỉ dùng BGSAVE, chặn SAVE bằng ACL cho user ứng dụng, và đo latest_fork_usec thay vì tin rằng BGSAVE không chặn gì.
Cách phát hiện:
bash
# Monitor Redis latency
redis-cli --latency
# Output is "min: X, max: Y, avg: Z (N samples)" in ms; a 5 s SAVE shows up as max: 5000 or more
# Count SAVE calls (the log only says "DB saved on disk", never "SAVE")
redis-cli INFO commandstats | grep cmdstat_save
# Monitor INFO stats
redis-cli INFO persistence | grep rdb_
# blocked_clients (INFO clients) only counts clients waiting on BLPOP/BRPOP/XREAD...; use SLOWLOG GET, or LATENCY DOCTOR after CONFIG SET latency-monitor-threshold 100 (latency monitor is off by default)Phòng tránh:
Không dùng SAVE trên production, dùng BGSAVE:
bash# BAD: Blocks entire Redis redis-cli SAVE # GOOD: child process writes the RDB; main thread only pauses for the fork itself redis-cli BGSAVEDùng BGSAVE (fork + child process); bản thân lời gọi fork vẫn làm luồng chính dừng trong
latest_fork_usec:bash# BGSAVE forks child process to save snapshot redis-cli BGSAVE # Redis continues serving requests while child saves # Check save status redis-cli LASTSAVE # Returns timestamp of last successful save
Chặn SAVE ở tầng quyền (ACL, Redis 6+): user ứng dụng không chạy được SAVE, FLUSHALL, FLUSHDB, KEYS.
bash
redis-cli ACL SETUSER app on '>s3cret' '~*' '&*' +@all -save -flushall -flushdb -keys
redis-cli --user app --pass s3cret --no-auth-warning SAVE
# → (error) NOPERM User app has no permissions to run the 'save' command
# Rollback: redis-cli ACL SETUSER app +save
# Persist the ACL: aclfile + ACL SAVE, otherwise restart drops itConfigure automatic snapshots (uses BGSAVE automatically):
conf# redis.conf # After 3600 s if >= 1 change, 300 s if >= 100, 60 s if >= 10000 (default since Redis 7.0) save 3600 1 300 100 60 10000 # Automatically uses BGSAVE (non-blocking)Theo dõi hiệu năng fork() (BGSAVE vẫn có thể gây vấn đề):
bash# fork() copies memory pages (copy-on-write) # Large datasets + high write rate = memory spike # Monitor: latest_fork_usec metric redis-cli INFO stats | grep latest_fork_usec # No universal threshold: fork time grows with dataset size; record a baseline per instance and alert on deviations (1 s is only an example)Đừng chuyển sang AOF chỉ để tránh fork: AOF rewrite cũng fork y hệt. Choose RDB/AOF for durability, and cut fork cost with smaller instances and THP disabled:
conf# AOF appends incrementally, but AOF rewrite (BGREWRITEAOF) still forks appendonly yes appendfsync everysec
→ See also: Redis Production Setup, Redis Anti-Patterns
Option 2: AOF (Append-Only File) - Write log
conf
# Append every write command
appendonly yes
# appendfsync: always | everysec (default) | no
appendfsync everysecNội dung AOF minh hoạ (rút gọn; file thật lưu lệnh dạng RESP, ví dụ *3\r\n$3\r\nSET...):
text
SET key1 value1
INCR counter
HSET user:123 name "John"- ✅ Bền hơn:
everysecchỉ mất tối đa khoảng 1 giây ghi (doc: 'you can only lose one second worth of writes') - ⚠️ Incr files are readable; base file is RDB format by default (aof-use-rdb-preamble yes, multi-part AOF since 7.0)
- ❌ File lớn hơn RDB cùng dataset (doc: 'AOF files are usually bigger than the equivalent RDB files')
- ❌ Khởi động chậm hơn RDB với dataset lớn (doc: 'RDB allows faster restarts with big datasets compared to AOF')
Option 3: Both (RDB + AOF)
conf
# AOF for durability, RDB files for backups
# On restart with both enabled, Redis loads the AOF (most complete), not the RDB
# The AOF base file is RDB-format (aof-use-rdb-preamble yes), so restart stays fast
appendonly yes
save 3600 1 300 100 60 10000⚠️ BẪY: fork() của BGSAVE có thể mất dữ liệu khi thiếu RAM (OOM kill)
Khi chạy BGSAVE hoặc BGREWRITEAOF, Redis dùng fork() tạo process con. Nếu máy đã dùng nhiều RAM, Linux có thể kích hoạt OOM killer giết Redis, mất mọi ghi chưa persist.
Vì sao xảy ra:
fork()tạo bản sao copy-on-write của bộ nhớ Redis- Khi ghi nặng trong lúc lưu RDB hoặc viết lại AOF, Redis có thể dùng tới 2 lần bộ nhớ thường dùng; phần thêm tỉ lệ với số trang nhớ bị sửa trong lúc lưu
- RAM hệ thống hạn chế thì kernel có thể từ chối
fork()hoặc OOM killer giết Redis - Doc khuyên đặt
vm.overcommit_memory = 1đểfork()không bị từ chối vì thiếu RAM ảo; ghi nặng trong lúc fork vẫn làm bộ nhớ thật tăng (tới 2 lần bộ nhớ thường dùng) - Nếu Redis bị giết, mọi ghi sau lần snapshot cuối bị mất
Kịch bản minh hoạ, không phải sự cố có nguồn (số liệu là ví dụ):
bash
# Production Redis: 16GB dataset, server has 20GB RAM
# Redis memory usage: 16GB
# Available RAM: 4GB
# Automatic BGSAVE triggers
redis-cli BGSAVE
# Fork needs 16GB virtual memory
# System only has 4GB available
# Scenario 1: Fork fails
# Log: "Can't save in background: fork: Cannot allocate memory"
# rdb_last_bgsave_status:err. With the default stop-writes-on-bgsave-error yes, every write now fails:
# "MISCONF Redis is configured to save RDB snapshots, but it's currently unable to persist to disk..."
# Reads still work; writes stay refused until a BGSAVE succeeds
# (stop-writes-on-bgsave-error no: writes continue with NO snapshot, a crash loses everything since the last good save)
# Kịch bản 2: OOM killer
# fork ban đầu thành công, nhưng tốc độ ghi cao làm copy-on-write chép thêm trang
# Bộ nhớ tăng vọt (ví dụ minh hoạ): 16GB → 24GB (Redis + process con)
# OOM killer của kernel giết Redis: "Out of memory: Kill process Redis"
# Redis chết ngay, mọi ghi sau snapshot cuối bị mất
# Result: 12 hours of data GONE (last snapshot was 12 hours ago)Bài học: chọn tần suất persistence theo lượng dữ liệu chấp nhận mất, chừa RAM cho copy-on-write, và cảnh báo ngay khi rdb_last_bgsave_status khác ok.
How to detect:
bash
# Monitor fork failures
redis-cli INFO persistence | grep -E 'rdb_last_bgsave_status|aof_last_bgrewrite_status'
redis-cli INFO stats | grep latest_fork_usec
# Slow fork = large page tables (big dataset, THP on), not a direct memory-pressure signal; failed forks show as rdb_last_bgsave_status:err
# Check system logs for OOM kills (chưa chạy: cần Linux root)
dmesg | grep -i "killed process"
dmesg | grep -i "redis"
# Output: "Out of memory: Kill process 1234 (redis-server)"
# Monitor memory overcommit
cat /proc/sys/vm/overcommit_memory
# 0 = heuristic (risky)
# 1 = always overcommit (recommended for Redis)
# 2 = never overcommit (Redis will fail)
# Check for fork errors in Redis logs
grep "Can't save in background" /var/log/redis/redis.logPrevention:
Set Linux overcommit_memory = 1:
bash# (chưa chạy: cần Linux root) Allow kernel to overcommit memory (required for Redis fork) sudo sysctl vm.overcommit_memory=1 echo "vm.overcommit_memory = 1" | sudo tee /etc/sysctl.d/99-redis.conf # Disable THP (Transparent Huge Pages) - causes fork latency and CoW memory spikes # Runtime only; persist with a systemd unit or the boot parameter transparent_hugepage=never echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabledDành sẵn RAM dự phòng cho copy-on-write; hãy đo, đừng giả định:
bash# After a BGSAVE or AOF rewrite under real write load: redis-cli INFO persistence | grep -E 'rdb_last_cow_size|aof_last_cow_size' # Headroom = peak CoW size + OS + client/replication buffers # Worst case (every page rewritten during the fork) = 2x datasetĐặt maxmemory và chọn eviction policy theo vai trò:
conf# redis.conf: leave headroom for CoW, OS and buffers (size it from step 2, not a fixed %) maxmemory 12gb # Pure cache: evicting is fine maxmemory-policy allkeys-lru # Data you must keep (sessions, queues, primary store): never evict, writes fail with OOM error instead # maxmemory-policy noevictionAOF không tránh được fork (AOF rewrite cũng fork y hệt). Choose AOF for durability, at most about 1 s of writes lost with everysec, not as a fork fix:
conf# redis.conf appendonly yes appendfsync everysec # Empty save directive disables RDB snapshots (you also lose compact RDB backups) save ""Diskless replication does not remove the fork:
repl-diskless-synconly streams the RDB to replicas over the socket instead of writing it to disk first; the primary still forks a child for every full sync:conf# redis.conf (default yes since Redis 7.0) repl-diskless-sync yesSchedule BGSAVE during low-traffic periods:
conf# redis.conf: tắt snapshot tự động save ""text# crontab: chạy BGSAVE lúc 3 giờ sáng (ít tải; chưa chạy: cần cron trên Linux) 0 3 * * * redis-cli BGSAVE # Risk: without AOF, a crash loses up to 24 h of writes; alert when rdb_last_bgsave_status is not ok
→ See also: Redis High Availability, Redis Production Setup
Option 4: None (cache-only)
bash
# No persistence
# Fastest performance
# Acceptable for pure cachingRedis Clustering
1. Standalone (single node)
text
App → Redis (single instance)- Simple, fast
- Không có high availability
2. Sentinel (automatic failover)
text
App → Sentinel → Primary Redis
↓
Replica Redis- Monitors primary health
- Tự động failover sang replica
- Sentinel quorum (3+ sentinel nodes)
3. Redis Cluster (horizontal sharding)
text
App → Redis Cluster
├── Node 1 (slots 0-5460) + Replica
├── Node 2 (slots 5461-10922) + Replica
└── Node 3 (slots 10923-16383) + Replica- 16384 hash slots
- Dữ liệu được shard theo key
- Auto-failover per shard
- Scale gần tuyến tính theo số node (cluster-spec: 'linear scalability up to 1000 nodes'); đổi lại multi-key khác slot bị CROSSSLOT
Cluster key distribution:
bash
# Slot = CRC16(key) mod 16384. Đã chạy trên cluster 3 master (slot 0-5460, 5461-10922, 10923-16383)
redis-cli -c CLUSTER KEYSLOT user:123:name
# → (integer) 6198 → thuộc Node 2 (slot 5461-10922)
redis-cli -c SET user:123:name "John"
# Hash tags: chỉ phần trong {...} được băm, nên hai key cùng slot
redis-cli -c CLUSTER KEYSLOT '{user:123}:name'
# → (integer) 12893
redis-cli -c CLUSTER KEYSLOT '{user:123}:age'
# → (integer) 12893 (cùng slot)
redis-cli -c SET '{user:123}:name' "John"
redis-cli -c SET '{user:123}:age' 30
# Cùng slot nên làm được multi-key (MGET, transactions)
redis-cli -c MGET '{user:123}:name' '{user:123}:age'
# Khác slot thì lỗi: MGET user:123:name user:456:name
# → (error) CROSSSLOT Keys in request don't hash to the same slotRedis Transactions
MULTI/EXEC (queued, isolated execution)
bash
# redis-cli đọc lệnh từ stdin trong MỘT kết nối, nên MULTI và EXEC dùng chung phiên
redis-cli <<'EOF'
MULTI
SET k1 "v1"
INCR k1
SET k2 "v2"
EXEC
GET k2
EOF
# → EXEC trả OK, "ERR value is not an integer or out of range", OK; GET k2 = "v2"
# Chạy cô lập nhưng KHÔNG rollback: INCR lỗi lúc chạy mà SET k2 vẫn được ghi
# Lệnh sai tên lúc xếp hàng (ví dụ FOOBAR): EXEC trả EXECABORT, không lệnh nào chạyWATCH (optimistic concurrency control)
python
# redis-py (pip install redis), Redis chạy ở localhost:6379
import redis
r = redis.Redis(decode_responses=True)
r.set("balance:123", 150)
with r.pipeline() as pipe:
pipe.watch("balance:123")
balance = int(pipe.get("balance:123"))
if balance >= 100:
pipe.multi()
pipe.decrby("balance:123", 100)
pipe.execute() # ném redis.WatchError nếu balance:123 đổi sau WATCH, giao dịch bị huỷ
else:
pipe.unwatch()Lua Scripts (better transactions)
lua
-- decrby_if_enough.lua: giảm số dư nguyên tử nếu đủ (khoá thiếu cũng trả 0)
local balance = tonumber(redis.call('GET', KEYS[1]))
if balance and balance >= tonumber(ARGV[1]) then
redis.call('DECRBY', KEYS[1], ARGV[1])
return 1
else
return 0
endbash
# Lưu script thành decrby_if_enough.lua; trước đó: redis-cli SET balance:123 150
redis-cli --eval decrby_if_enough.lua balance:123 , 100
# → (integer) 1 (đủ tiền) hoặc (integer) 0 (không đủ)
# All commands in script are atomicCaching Patterns
1. Cache-Aside (Lazy Loading)
python
# minh hoạ, không chạy độc lập: giả định redis (redis-py), db và json đã có
def get_user(user_id):
# Check cache first
user = redis.get(f"user:{user_id}")
if user:
return json.loads(user)
# Cache miss - fetch from DB
user = db.query("SELECT * FROM users WHERE id = ?", user_id)
# Store in cache (with TTL)
redis.set(f"user:{user_id}", json.dumps(user), ex=3600)
return user- ✅ Only cache what's requested (efficient)
- ❌ First request always slow (cache miss)
2. Write-Through
python
# minh hoạ, không chạy độc lập: giả định redis, db và json đã có
def update_user(user_id, data):
# Update DB
db.execute("UPDATE users SET name = ? WHERE id = ?", data['name'], user_id)
# Update cache
redis.set(f"user:{user_id}", json.dumps(data), ex=3600)- ✅ Cache luôn mới nhất
- ❌ Write latency (2 writes)
3. Write-Behind (Write-Back)
python
# minh hoạ, không chạy độc lập: giả định redis, queue, write_to_db và json đã có
def update_user(user_id, data):
# Update cache immediately
redis.set(f"user:{user_id}", json.dumps(data), ex=3600)
# Queue DB write (async)
queue.enqueue(write_to_db, user_id, data)- ✅ Fast writes (async DB write)
- ❌ Data loss risk (cache eviction before DB write)
4. Refresh-Ahead
python
# minh hoạ, không chạy độc lập: giả định redis, db, queue, refresh_cache và json đã có (đã chạy với stub)
def get_user(user_id):
key = f"user:{user_id}"
user = redis.get(key)
if user is None: # cache miss: nạp từ DB như cache-aside
user = json.dumps(db.query("SELECT * FROM users WHERE id = ?", user_id))
redis.set(key, user, ex=3600)
return json.loads(user)
# Refresh if TTL < 10% remaining (ttl là -1 khi key không hết hạn)
ttl = redis.ttl(key)
if 0 <= ttl < 360: # 10% of 3600
queue.enqueue(refresh_cache, user_id)
return json.loads(user)- ✅ Tránh cache miss trên dữ liệu nóng
- ❌ Complexity (background refresh)
Eviction Policies
conf
# When memory limit reached, what to evict?
maxmemory 2gb
maxmemory-policy allkeys-lru
# Policies:
# noeviction - Return errors (don't evict)
# allkeys-lru - Evict least recently used (any key)
# volatile-lru - Evict LRU (only keys with TTL)
# allkeys-lfu - Evict least frequently used (Redis 4.0+)
# volatile-lfu - Evict LFU (only keys with TTL)
# allkeys-random - Evict random key
# volatile-random - Evict random (only keys with TTL)
# volatile-ttl - Evict key with nearest expire timeRecommendation:
- Dùng làm cache:
allkeys-lru(loại key ít dùng nhất) - Session store:
noeviction(hết RAM thì ghi báo lỗi OOM, không mất session; đo rồi nângmaxmemory);volatile-ttlchỉ khi chấp nhận mất các session sắp hết hạn - Mixed use (cache lẫn dữ liệu phải giữ): tách hai instance; nếu buộc dùng một instance thì
volatile-lruvà chỉ đặt TTL cho key cache
Redis Production War Stories
Sự cố thực tế về memory, failover và hiệu năng
War Story 1: KEYS làm Redis chạm giới hạn 64 GB và bị OOM kill
Kịch bản minh hoạ, không phải sự cố có nguồn; số liệu là ví dụ.
Company: Social media platform (50M MAU) Vấn đề: Developer chạy KEYS * trên production để debug, gây OOM Tác động: Redis crash, ngưng 15 phút, mất 3M session
bash
# ❌ WRONG: KEYS * blocks Redis and scans ALL keys
redis-cli KEYS 'user:*'
# What happened:
# - 47 million keys in Redis
# - KEYS command is O(N) - blocks ALL operations
# - Scanned all 47M keys in 23 seconds
# - During scan: 0 ops/sec (total blockage!)
# - Memory used for iteration: 2.1GB additional
# - Memory limit: 64GB, current: 62.8GB
# - Additional 2.1GB → 64.9GB → OOM error
# - Redis killed by OOM killer
# - Result: 15-minute outage until Redis restartedDetailed impact:
text
Timeline:
00:00:00 - Developer chạy KEYS user:* để debug
00:00:02 - CPU Redis lên 100% (single-threaded)
00:00:23 - KEYS xong, nhưng bộ nhớ ở 64,9 GB (giới hạn 64 GB)
00:00:24 - OOM killer dừng tiến trình Redis
00:00:25 - Ứng dụng báo lỗi "Connection refused"; Redis khởi động lại và nạp snapshot RDB (15 phút)
00:15:25 - Dịch vụ phục hồi
Impact:
- 3M active sessions: mất phần ghi sau snapshot RDB cuối
- 50K concurrent users disconnected
- $180K revenue loss (15 min × $12K/min)
- 14K support ticketsCách sửa: Dùng SCAN thay cho KEYS
python
# minh hoạ, không chạy độc lập: giả định redis = redis.Redis() (redis-py)
# ✓ CORRECT: SCAN iterates in chunks (non-blocking)
cursor = 0
pattern = "user:*"
matches = []
while True:
cursor, keys = redis.scan(cursor, match=pattern, count=100)
matches.extend(keys)
if cursor == 0:
break
# SCAN characteristics:
# - Returns about COUNT keys per call (default COUNT 10)
# - Cursor-based iteration (can pause/resume)
# - Non-blocking (other operations can run)
# - Time: Same total time, but split across many calls
# - Memory: O(1) per call (not O(N))
# Example: Scanning 47M keys
# - KEYS *: 23 seconds, blocks all ops
# - SCAN (count=1000): 47,000 calls × 0.5ms = 23.5 seconds, non-blocking
# - Other ops continue during SCAN ✅Các lệnh bị cấm thêm trên production:
text
# ❌ NEVER use in production:
KEYS * # O(N) - blocks Redis
FLUSHALL # Deletes ALL data
FLUSHDB # Deletes current DB
SAVE # Blocks Redis during snapshot
SHUTDOWN # Stops Redis
DEBUG SLEEP # Intentional blocking (debug only)
CONFIG RESETSTAT # Resets stats (lose monitoring data)
# ✅ Safe alternatives:
SCAN # Use instead of KEYS
BGSAVE # Background save (use instead of SAVE)
UNLINK # Async delete (use instead of DEL for large keys)Giám sát để phòng ngừa:
conf
# Detect slow commands (redis.conf)
# 10 ms threshold (đơn vị micro giây)
slowlog-log-slower-than 10000
slowlog-max-len 128bash
# View slow log
redis-cli SLOWLOG GET 10
# Kết quả minh hoạ:
# 1) 1) (integer) 123 # Slow log ID
# 2) (integer) 1640000000 # Timestamp
# 3) (integer) 23412000 # Execution time (microseconds) = 23.4 seconds!
# 4) 1) "KEYS" # Command
# 2) "user:*"
# Alert if:
# - Command execution time > 100ms
# - Độ trễ lệnh (SLOWLOG, redis-cli --latency) vượt baseline đã đo
# - Memory usage > 90%Bài học: không chạy KEYS trên production; dùng SCAN, chặn lệnh nguy hiểm bằng ACL và theo dõi SLOWLOG để thấy lệnh chậm trước khi nó chặn Redis.
War Story 2: Lần failover âm thầm mất 47 giây
Kịch bản minh hoạ, không phải sự cố có nguồn; số liệu là ví dụ. Cơ chế và số đo bên dưới lấy từ Redis 8 (1 primary + 2 replica + 3 Sentinel trong Docker).
Company: E-commerce platform (Black Friday) Vấn đề: Redis Sentinel failover mất 47s thay vì 10s như kỳ vọng Tác động: cache không khả dụng 47s, 30K đơn hàng thất bại, mất $850K
text
Setup: 1 primary + 2 replica (32GB RAM mỗi nút), 3 Sentinel (quorum = 2)
sentinel.conf để down-after-milliseconds mặc định (30000)
11:42:00 - Primary (redis-1) crash (kernel panic)
11:42:30 - Sentinel đánh dấu primary down sau 30 s (down-after-milliseconds)
11:42:33 - Sentinel bầu leader, promote redis-2: redis-2 nhận ghi
11:42:47 - Ứng dụng kết nối lại: client giữ địa chỉ primary cũ và timeout dài
Total failover time: 47 seconds (expected: 10-15s)Root cause: thời gian phát hiện cộng độ trễ client, không phải fork().
- Sentinel chỉ bắt đầu failover sau
down-after-milliseconds(mặc định 30000 ms, đo trên Redis 8);failover-timeoutmặc định 180000 ms. - Promote không đợi fork: replica được chọn nhận ghi ngay. Các replica còn lại thường chỉ cần partial resync: 'Since Redis 4.0, when an instance is promoted to master after a failover, it will still be able to perform a partial resynchronization'.
- Fork vẫn có giá trên dataset lớn: 'may result in Redis stopping serving clients for some milliseconds or even for one second' (doc persistence, khi dataset rất lớn và CPU kém). Đo
latest_fork_usectrên máy thật, không dùng bảng GB-giây chung.
Fix 1: Sentinel phát hiện sớm hơn
conf
# sentinel.conf
sentinel resolve-hostnames yes
sentinel monitor mymaster redis-1 6379 2
# Phát hiện primary hỏng sau 5 s (mặc định 30000 ms)
sentinel down-after-milliseconds mymaster 5000
# Đồng bộ 1 replica mỗi lần (mặc định 1)
sentinel parallel-syncs mymaster 1
# Mặc định 180000 ms; 10 s chỉ hợp khi dữ liệu nhỏ
sentinel failover-timeout mymaster 10000Đo trên Docker (dataset nhỏ, đổi theo máy): dừng primary, Sentinel công bố primary mới sau khoảng 7,4 s với down-after-milliseconds 5000.
Fix 2: Client theo Sentinel, timeout ngắn
python
# redis-py (pip install redis); Sentinel chạy ở sentinel-1..3:26379, đã chạy trên Redis 8
from redis.sentinel import Sentinel
sentinel = Sentinel([
('sentinel-1', 26379),
('sentinel-2', 26379),
('sentinel-3', 26379)
], socket_timeout=0.5) # Fast timeout
# Hỏi Sentinel địa chỉ primary hiện tại, tự nối lại primary mới khi failover
primary = sentinel.master_for('mymaster', socket_timeout=0.1)
primary.set('key', 'value')Monitoring failover health:
bash
# Check sentinel status
redis-cli -p 26379 SENTINEL MASTER mymaster
# Kết quả mẫu (đã chạy, rút gọn): name mymaster, ip 172.24.0.8, port 6379, flags master,
# last-ok-ping-reply 446 (ms), down-after-milliseconds 5000, num-slaves 2, num-other-sentinels 2, quorum 2
# Alert if:
# - last-ok-ping-reply > down-after-milliseconds (Sentinel sắp coi primary là down)
# - num-other-sentinels < 2 (không đủ Sentinel cho quorum)
# - flags chứa s_down hoặc o_down (primary bị đánh dấu down chủ quan hoặc khách quan)
# Simulate failover (TEST ONLY)
redis-cli -p 26379 SENTINEL FAILOVER mymaster
# Measure actual failover time in stagingBài học: Redis có thể rất ổn mà failover vẫn chậm vì ngưỡng phát hiện và client; tính thời gian từ ngưỡng đã cấu hình, đo bằng cách dừng primary ở staging.
War Story 3: Hit rate 93% che giấu database bị quá tải
Kịch bản minh hoạ, không phải sự cố có nguồn; số liệu là ví dụ.
Company: News aggregator (120M lượt đọc/ngày) Problem: Dashboard báo hit rate 93,3% nhưng database vẫn quá tải Impact: Database 8M query/ngày (mục tiêu 1M), P95 latency 2,500ms (mục tiêu 50ms)
text
Số liệu ví dụ:
- GET: 120M/ngày, hit 112M, miss 8M → hit rate = 112 / 120 = 93,3%
- Mỗi bài mới bị miss đúng một lần (lần đọc đầu): 8M bài mới/ngày = 8M miss = 8M query
- Hit rate chung đo trên TỔNG lượt đọc nên che việc 8M miss đều rơi vào bài mới
- Bài 12 KB: 16 GB / 12 KB = khoảng 1,33M bài chứa vừa
- Bài mới vào khoảng 5 560/phút (8M / 1 440), bộ nhớ đầy nên evicted_keys tăng liên tụcRoot cause: cache nhồi nội dung đầy đủ (12 KB/bài) nên tập nóng không vừa 16 GB và evicted_keys tăng liên tục. Cache lớn hơn cũng không cứu được lần đọc đầu của 8M bài mới.
Fix: Right-size theo dữ liệu nóng và tách hai tầng
bash
# Tầng 1: Redis chỉ giữ metadata nhỏ (khoảng 200 byte/bài: 16 GB / 200 B = 80M bài)
redis-cli SET article:123:meta '{"title":"Tin mới","author":"An","views":1000}' EX 3600
# Tầng 2: CDN giữ nội dung đầy đủ (Cache-Control: max-age=300)
# Sau khi sửa: đo lại số query DB/ngày và P95 thay vì tin con số mục tiêuMonitoring that matters:
bash
# BAD metric: hit rate chung, hits / (hits + misses)
# GOOD: xem hit, miss và eviction cùng lúc, so hai lần đo cách nhau một khoảng
redis-cli INFO stats | grep -E 'keyspace_hits|keyspace_misses|evicted_keys'
# Bộ nhớ so với giới hạn và phân mảnh
redis-cli INFO memory | grep -E 'used_memory_human|maxmemory_human|mem_fragmentation_ratio'
# INFO chỉ cho hit/miss toàn instance: hit rate theo nhóm key phải đếm ở tầng ứng dụng
# Alert when:
# - evicted_keys tăng liên tục (thiếu RAM so với tập dữ liệu nóng)
# - mem_fragmentation_ratio > 1.5 (bật activedefrag; restart chỉ là phương án cuối)
# - Tỉ lệ query DB / lượt đọc vượt baseline đã đo (cache không còn gánh tải)Bài học: hit rate chung có thể đẹp trong khi database vẫn quá tải; theo dõi eviction và số query DB, và cache bản nhỏ của dữ liệu nóng.
Phải nhớ
- Chọn structure theo access pattern (Sorted Set xếp hạng, Hash cho object, Stream cho queue cần ack); mỗi lệnh atomic nhưng lệnh O(N) (KEYS, SAVE) chặn mọi client.
- Chọn RDB, AOF hay cả hai theo lượng dữ liệu chấp nhận mất; BGSAVE và AOF rewrite đều fork nên chừa RAM cho copy-on-write và đặt
vm.overcommit_memory = 1. - BGSAVE lỗi thì mặc định Redis từ chối ghi (MISCONF): cảnh báo theo
rdb_last_bgsave_status; đặt TTL ngay trong lệnh ghi (SET key v EX 3600).
Tự kiểm: Lúc 2 giờ sáng app báo lỗi MISCONF ... unable to persist to disk trên mọi lệnh ghi, lệnh đọc vẫn chạy. Kiểm tra gì trước, và sửa tạm thế nào?
Đáp án
BGSAVE vừa lỗi và stop-writes-on-bgsave-error yes đang chặn ghi. Xem INFO persistence (rdb_last_bgsave_status:err) và log Redis: thường do đĩa đầy, mất quyền ghi thư mục, hoặc fork lỗi vì thiếu RAM. Sửa nguyên nhân rồi chạy BGSAVE lại, ghi sẽ mở. Chỉ đặt CONFIG SET stop-writes-on-bgsave-error no như biện pháp tạm, vì khi đó Redis nhận ghi mà không có snapshot.