Danh sách bài viết

Bài 103: Monitoring Redis — INFO, SLOWLOG, MEMORY

Biết Redis đang chạy chưa đủ; cần biết Redis đang chạy như thế nào. Bài này đi qua bộ công cụ introspection có sẵn trong Redis: INFO (server, clients, memory, persistence, stats, replication, commandstats, keyspace), SLOWLOG để phát hiện câu lệnh chậm, CLIENT LIST để kiểm tra kết nối đang hoạt động, nhóm MEMORY USAGE / DOCTOR / STATS để debug memory growth, LATENCY commands để bắt latency spike. Tiếp theo là redis-cli helpers (--stat, --latency, --bigkeys, --hotkeys) cho interactive diagnostics, và cuối cùng là tích hợp Prometheus với redis_exporter để có metrics liên tục. Bài kết với danh sách alert thresholds thực tế, anti-patterns phổ biến, và best practices.

01/06/2026
0 lượt xem
1

Mục Tiêu Bài Học

  • Đọc và hiểu các section quan trọng của INFO: memory, clients, stats, replication, commandstats.
  • Dùng SLOWLOG để xác định câu lệnh nào gây latency cao.
  • Dùng CLIENT LIST để phát hiện connection bị treo hoặc output buffer quá lớn.
  • Dùng MEMORY USAGE, MEMORY DOCTOR, MEMORY STATS để debug memory growth.
  • Dùng LATENCY commands để bắt latency spike theo event.
  • Biết các redis-cli flag hữu ích cho diagnostics thủ công (--stat, --latency, --bigkeys, --hotkeys).
  • Cài đặt redis_exporter và hiểu các metrics Prometheus quan trọng cần theo dõi.
  • Xây dựng được danh sách alert thresholds thực tế cho production.
2

Bài Toán: Giám Sát Proactive Trong Production

Redis chạy trong production gặp nhiều loại vấn đề khác nhau, nhưng phần lớn không tự báo lỗi cho đến khi đã nghiêm trọng. Các symptom phổ biến:

  • High latency: p99 request time tăng vọt. Có thể do slow command, fragmentation, fork từ RDB/AOF, hay just memory pressure.
  • Out of Memory (OOM): Redis hit maxmemory và bắt đầu evict key theo policy, hoặc từ chối write.
  • Hot key: một key bị đọc/ghi hàng triệu lần mỗi giây, làm single-thread CPU của Redis trở thành bottleneck.
  • Slow query: SMEMBERS trên Set có 1 triệu phần tử chặn event loop hàng chục milli-giây.
  • Connection leak: application không close connection đúng cách, số connected_clients tăng dần cho đến khi chạm maxclients.
  • Replication lag: replica tụt sau master, read-from-replica trả về stale data.

Giám sát proactive nghĩa là phát hiện các dấu hiệu này trước khi chúng gây incident, thay vì đợi user report lỗi rồi mới điều tra. Redis cung cấp đủ công cụ built-in để làm điều đó — không cần agent đặc biệt cho monitoring cơ bản.

3

INFO — Cấu Trúc & Cách Đọc

INFO là lệnh tổng hợp trả về toàn bộ thông tin trạng thái của Redis instance theo dạng plain text, mỗi dòng là một cặp field:value, nhóm theo section bằng dòng tiêu đề # SectionName.

# Toàn bộ info
INFO

# Chỉ một section cụ thể
INFO memory
INFO stats
INFO replication
INFO clients
INFO server
INFO keyspace
INFO commandstats
INFO persistence
INFO cpu

Các section chính:

  • server: version, uptime, OS, port.
  • clients: số kết nối, blocked clients, maxclients.
  • memory: used_memory, RSS, fragmentation ratio, maxmemory, eviction policy.
  • persistence: RDB last save, AOF enabled, AOF size, rewrite stats.
  • stats: ops/sec, cache hit/miss, evicted keys, rejected connections, network I/O.
  • replication: role, connected replicas, replication offset, lag.
  • cpu: cumulative CPU time của Redis process và children.
  • commandstats: per-command call count, total time, time per call.
  • keyspace: số key theo DB, số key có TTL, avg TTL.

Output của INFO là snapshot tại thời điểm gọi — không stream. Polling mỗi 10–30 giây là hợp lý cho monitoring background; tần suất cao hơn thêm overhead không đáng kể nhưng không cần thiết nếu đã có Prometheus scrape.

4

INFO server & INFO clients

INFO server

Section này dùng để xác nhận identity của instance và theo dõi uptime.

127.0.0.1:6379> INFO server
# Server
redis_version:7.2.4
redis_mode:standalone
os:Linux 5.15.0-101-generic x86_64
arch_bits:64
multiplexing_api:epoll
process_id:1234
tcp_port:6379
uptime_in_seconds:864000
uptime_in_days:10
hz:10

Các field cần chú ý:

  • redis_version: xác nhận phiên bản đang chạy khớp với expected.
  • uptime_in_seconds: alert nếu uptime đột ngột reset về 0 (unexpected restart).
  • hz: tần suất (Hz) của Redis background task (expire scan, resize, etc.). Default 10, có thể tăng lên 100 trên server mạnh. Ảnh hưởng đến độ chính xác expire và CPU nhẹ.
  • multiplexing_api: epoll (Linux), kqueue (macOS/BSD). Thông tin diagnostics, không cần thay đổi.

INFO clients

127.0.0.1:6379> INFO clients
# Clients
connected_clients:248
cluster_connections:0
maxclients:10000
client_recent_max_input_buffer:20480
client_recent_max_output_buffer:0
blocked_clients:5
tracking_clients:0

Các field cần chú ý:

  • connected_clients: số kết nối TCP đang mở hiện tại. Alert khi vượt 80% maxclients (mặc định 10000).
  • maxclients: giới hạn cấu hình. Khi đầy, Redis từ chối kết nối mới và tăng rejected_connections trong stats.
  • blocked_clients: số client đang chờ blocking commands (BLPOP, BRPOP, XREAD BLOCK). Số cao bất thường có thể chỉ ra queue không được consume.
  • client_recent_max_output_buffer: output buffer lớn nhất gần đây. Nếu cao (hàng MB), có thể có Pub/Sub consumer chậm.
5

INFO memory — Các Chỉ Số Quan Trọng

127.0.0.1:6379> INFO memory
# Memory
used_memory:1073741824
used_memory_human:1.00G
used_memory_rss:1610612736
used_memory_rss_human:1.50G
used_memory_peak:1207959552
used_memory_peak_human:1.13G
used_memory_peak_perc:88.97%
mem_fragmentation_ratio:1.50
mem_fragmentation_bytes:536870912
maxmemory:2147483648
maxmemory_human:2.00G
maxmemory_policy:allkeys-lru
allocator_frag_ratio:1.23
allocator_rss_ratio:1.21

Giải thích từng field:

  • used_memory: số byte Redis allocate cho data (theo allocator). Đây là view của Redis.
  • used_memory_rss: Resident Set Size — bộ nhớ thực sự OS cấp cho process Redis (bao gồm overhead, fragmentation). Đây là số trong top/htop.
  • mem_fragmentation_ratio = used_memory_rss / used_memory:
    • Lý tưởng: 1.0–1.2.
    • > 1.5: fragmentation cao. Allocator giữ nhiều bộ nhớ hơn Redis thực sự dùng. Trong Redis 4.0+, có thể chạy MEMORY PURGE để defragment hoặc cấu hình activedefrag yes.
    • < 1.0: Redis đang swap ra disk (memory pressure). Đây là tình huống nghiêm trọng — latency sẽ tăng đột biến.
  • used_memory_peak: mức cao nhất từ khi start. So sánh với used_memory hiện tại để biết bộ nhớ có đang giảm sau load spike không.
  • maxmemory: giới hạn cấu hình. 0 nghĩa là không giới hạn (lấy hết RAM — nguy hiểm trong production).
  • maxmemory_policy: policy eviction khi chạm giới hạn (noeviction, allkeys-lru, volatile-lru, v.v.).

Rule of thumb: đặt maxmemory ở 70–80% RAM vật lý của server (dành phần còn lại cho OS, AOF buffer, replication backlog). Alert khi used_memory vượt 85% maxmemory — eviction sắp bắt đầu hoặc đã bắt đầu.

6

INFO persistence & INFO stats

INFO persistence

127.0.0.1:6379> INFO persistence
# Persistence
loading:0
rdb_changes_since_last_save:12543
rdb_last_bgsave_status:ok
rdb_last_save_time:1748750000
rdb_last_bgsave_time_sec:3
aof_enabled:1
aof_current_size:2147483648
aof_base_size:1073741824
aof_pending_rewrite:0
aof_last_rewrite_time_sec:45
aof_last_bgrewrite_status:ok

Các field cần chú ý:

  • rdb_changes_since_last_save: số write chưa được persist vào RDB. Alert nếu số này quá lớn và rdb_last_bgsave_statuserr — data sẽ mất nếu crash.
  • aof_current_size vs aof_base_size: khi ratio lớn (ví dụ > 2x), AOF cần rewrite. Redis tự rewrite theo auto-aof-rewrite-percentage, nhưng alert nếu aof_current_size tăng liên tục mà không có rewrite.
  • aof_last_rewrite_time_sec: thời gian rewrite cuối. Nếu rất lâu (hàng trăm giây), disk I/O đang là bottleneck.
  • loading:1: Redis đang load RDB/AOF khi khởi động — trong giai đoạn này sẽ không phục vụ request.

INFO stats

127.0.0.1:6379> INFO stats
# Stats
total_connections_received:1543200
total_commands_processed:98765432
instantaneous_ops_per_sec:12543
total_net_input_bytes:10737418240
total_net_output_bytes:21474836480
rejected_connections:0
expired_keys:234521
evicted_keys:0
keyspace_hits:87654321
keyspace_misses:9876543

Các field quan trọng:

  • instantaneous_ops_per_sec: throughput tức thời. Baseline bình thường của hệ thống là bao nhiêu — lệch nhiều so với baseline là dấu hiệu bất thường.
  • rejected_connections: số kết nối bị từ chối vì maxclients. Bất kỳ giá trị > 0 đều là incident cần điều tra.
  • evicted_keys: số key bị xoá vì memory pressure. Với cache thì eviction là expected, nhưng với data store thì > 0 là vấn đề.
  • Cache hit ratio: keyspace_hits / (keyspace_hits + keyspace_misses). Alert khi ratio giảm đột ngột — có thể do TTL quá ngắn, key naming thay đổi, hay cold cache sau restart. Lưu ý: đây là cumulative counter kể từ khi start, nên tốt hơn là tính delta giữa hai lần scrape.
  • expired_keys: cumulative số key đã expire. Số này tăng nhanh bất thường có thể chỉ ra TTL quá ngắn hoặc churn key cao.
7

INFO replication & INFO commandstats

INFO replication

127.0.0.1:6379> INFO replication
# Replication
role:master
connected_slaves:2
slave0:ip=10.0.0.2,port=6379,state=online,offset=98765432,lag=0
slave1:ip=10.0.0.3,port=6379,state=online,offset=98765410,lag=1
master_replid:a1b2c3d4e5f6...
master_repl_offset:98765432
repl_backlog_active:1
repl_backlog_size:1048576

Replication monitoring thực tế cần kiểm tra:

  • connected_slaves: phải khớp với số replica expected. Alert khi < expected — một replica đã disconnect.
  • lag trong từng slave entry: số giây kể từ lần replica gửi heartbeat cuối. Lag = 0 là đang sync. Lag > 10s là có vấn đề.
  • master_repl_offset - slave_repl_offset: replication lag tính theo bytes. Alert khi lag quá cao so với repl_backlog_size — nếu vượt, replica sẽ phải full sync lại.
  • Trên replica: master_link_status:up phải là up. master_last_io_seconds_ago phải thấp.

INFO commandstats

Section này cho thấy mỗi command được gọi bao nhiêu lần và tốn bao nhiêu thời gian tổng cộng:

127.0.0.1:6379> INFO commandstats
# Commandstats
cmdstat_get:calls=1000000,usec=500000,usec_per_call=0.50
cmdstat_set:calls=200000,usec=180000,usec_per_call=0.90
cmdstat_hgetall:calls=5000,usec=250000,usec_per_call=50.00
cmdstat_smembers:calls=100,usec=80000,usec_per_call=800.00

usec_per_call là trung bình thời gian mỗi lần gọi (microseconds). Trong ví dụ trên, SMEMBERS tốn trung bình 800µs mỗi lần — đây là command cần điều tra nếu Set lớn. HGETALL tốn 50µs mỗi lần cũng đáng xem lại nếu Hash có nhiều field.

Commandstats rất hữu ích để xác định command nào đang consume nhiều CPU nhất (tổng usec), không chỉ command nào chậm nhất per call.

8

SLOWLOG — Phát Hiện Câu Lệnh Chậm

SLOWLOG ghi lại các command vượt ngưỡng thời gian thực thi vào một circular buffer trong memory. Khác với commandstats (aggregate), SLOWLOG giữ từng entry cụ thể kèm arguments — rất hữu ích để biết chính xác key nào, value nào là thủ phạm.

Cấu hình

# redis.conf hoặc dùng CONFIG SET (không cần restart)
slowlog-log-slower-than 10000   # ngưỡng: 10ms = 10000 microseconds
slowlog-max-len 128             # giữ 128 entry gần nhất

# Thay đổi runtime
CONFIG SET slowlog-log-slower-than 10000
CONFIG SET slowlog-max-len 256

Giá trị slowlog-log-slower-than 0 ghi mọi command (dùng để debug). -1 tắt hoàn toàn SLOWLOG.

Đọc SLOWLOG

# Lấy 10 entry gần nhất
SLOWLOG GET 10

# Kết quả mẫu cho 1 entry:
# 1) (integer) 42              ← entry ID
# 2) (integer) 1748750000      ← Unix timestamp khi xảy ra
# 3) (integer) 25430           ← thời gian thực thi (microseconds): 25.4ms
# 4) 1) "SMEMBERS"             ← command
#    2) "users:active:2026-06" ← argument
# 5) "10.0.0.5:54321"          ← client addr
# 6) "worker-1"                ← client name (nếu đặt CLIENT SETNAME)

# Xem số entry hiện tại
SLOWLOG LEN

# Xoá toàn bộ
SLOWLOG RESET

Patterns thường gặp

  • SMEMBERS / LRANGE 0 -1 trên collection lớn: thường gây slow nhất. Giải pháp: phân trang, scan từng phần, hoặc dùng cấu trúc khác.
  • KEYS *: quét toàn bộ keyspace, block event loop. Thay bằng SCAN.
  • SORT trên List lớn không có LIMIT: O(N log N).
  • ZUNIONSTORE / ZINTERSTORE trên Sorted Set lớn: O(N + M*log(M)).
  • Script Lua chạy quá lâu: block toàn bộ server trong suốt thời gian script chạy.

Khi gặp SLOWLOG entry, không chỉ fix command đó — cần hiểu tại sao collection đó lớn và liệu design có vấn đề không.

9

CLIENT LIST — Kiểm Tra Kết Nối

CLIENT LIST trả về danh sách tất cả client đang kết nối, mỗi client một dòng với nhiều field:

CLIENT LIST

# Kết quả mẫu (1 client):
# id=12 addr=10.0.0.5:54321 laddr=10.0.0.1:6379 fd=23 name=api-worker
# age=3600 idle=0 flags=N db=0 sub=0 psub=0 ssub=0 multi=-1
# qbuf=0 qbuf-free=32768 argv-mem=10 multi-mem=0 tot-mem=61466
# rbs=16384 rbp=16384 obl=0 oll=0 omem=0 events=r cmd=get
# user=default library-name=ioredis library-ver=5.3.2

Các field quan trọng:

  • age: số giây client đã kết nối. Client có age rất cao kết hợp với idle cao có thể là connection bị leak (application giữ connection nhưng không dùng).
  • idle: số giây kể từ lệnh cuối. Client idle > vài trăm giây thường là candidate để close (nếu application không dùng connection pooling có keepalive).
  • flags: trạng thái client. N=normal, S=subscriber (Pub/Sub), M=master replication, O=MONITOR mode, b=blocking command.
  • omem: output buffer size (bytes). Nếu cao (hàng MB) trên subscriber, consumer đang xử lý không kịp — Redis sẽ disconnect client này khi client-output-buffer-limit bị vượt.
  • cmd: lệnh cuối cùng client gửi. Nếu nhiều client stuck ở cùng một lệnh, đó là điểm cần điều tra.
  • multi: số command trong MULTI/EXEC transaction đang mở. Giá trị > 0 kéo dài lâu chỉ ra transaction bị stuck.
# Filter client theo flags (ví dụ chỉ subscriber)
CLIENT LIST TYPE pubsub

# Đóng một connection cụ thể (theo ID)
CLIENT KILL ID 12

# Đặt tên cho connection hiện tại (trong application code)
CLIENT SETNAME my-worker-1

Best practice: luôn đặt CLIENT SETNAME trong application code khi khởi tạo connection. Điều này giúp CLIENT LIST trở nên có ý nghĩa thay vì chỉ thấy địa chỉ IP.

10

MEMORY USAGE, DOCTOR, STATS

MEMORY USAGE key

Trả về số byte bộ nhớ mà một key tiêu thụ, bao gồm cả overhead của data structure và encoding:

# Đo memory của 1 key
MEMORY USAGE user:12345
# (integer) 248  ← 248 bytes

# SAMPLES N: lấy sample N phần tử để ước tính (cho collection lớn)
# Default SAMPLES 5; SAMPLES 0 = đo toàn bộ (chậm hơn với collection lớn)
MEMORY USAGE product:catalog SAMPLES 10

Dùng MEMORY USAGE kết hợp với SCAN để tìm big keys trong keyspace lớn mà không block server:

# Scan tìm key lớn hơn 10KB
redis-cli --scan --pattern "*" | while read key; do
  size=$(redis-cli MEMORY USAGE "$key" 2>/dev/null)
  if [ "$size" -gt 10240 ] 2>/dev/null; then
    echo "$size $key"
  fi
done | sort -rn | head -20

MEMORY DOCTOR

MEMORY DOCTOR phân tích trạng thái memory và trả về chẩn đoán tự động dưới dạng văn bản tiếng Anh:

MEMORY DOCTOR
# "Sam, I detected a few issues with this Redis instance memory implants:
#  * High fragmentation: mem_fragmentation_ratio is 1.7. Consider restarting
#    Redis or running MEMORY PURGE."
# Hoặc nếu không có vấn đề:
# "Sam, everything looks fine. I can't detect any memory problems."

Các chẩn đoán phổ biến: fragmentation cao, peak ratio cao (nhiều bộ nhớ đã dùng rồi được giải phóng nhưng allocator chưa trả OS), và thiếu maxmemory.

MEMORY STATS

MEMORY STATS trả về breakdown chi tiết hơn INFO memory, phân loại memory theo mục đích sử dụng:

MEMORY STATS

# Các field quan trọng:
# peak.allocated         ← peak allocation từ allocator
# total.allocated        ← tổng allocator đang giữ
# startup.allocated      ← overhead Redis baseline khi start
# replication.backlog    ← replication backlog buffer
# clients.slaves         ← output buffer cho replica connections
# clients.normal         ← output buffer cho normal clients
# aof.buffer             ← AOF write buffer
# dbXXX.overhead.hashtable.main  ← overhead hash table của DB
# dbXXX.keys.count       ← số key trong DB
# dataset.bytes          ← ước tính bytes dữ liệu thuần

Khi used_memory tăng liên tục không rõ lý do, MEMORY STATS giúp xác định phần nào đang grow: dataset thật, AOF buffer, hay replication backlog.

11

LATENCY Commands

Redis có hệ thống latency monitoring riêng, độc lập với SLOWLOG. Nó track các "event" nội bộ gây latency spike như fork cho RDB/AOF, fsync, hay AOF rewrite. Cần bật trong config:

# redis.conf
latency-monitor-threshold 100  # ms; event > 100ms được ghi

# Hoặc runtime
CONFIG SET latency-monitor-threshold 100

Các lệnh LATENCY

# Xem latency spike gần nhất cho mỗi event
LATENCY LATEST
# Kết quả mẫu:
# 1) 1) "fork"
#    2) (integer) 1748750000  ← timestamp spike gần nhất
#    3) (integer) 320         ← latency (ms) của spike đó
#    4) (integer) 320         ← max latency từ trước đến nay

# Xem lịch sử latency của một event
LATENCY HISTORY fork
# Trả về danh sách (timestamp, latency_ms) pairs

# Chẩn đoán tự động
LATENCY DOCTOR
# Giải thích nguyên nhân và gợi ý fix từng event

# Reset latency history
LATENCY RESET
LATENCY RESET fork  # chỉ reset event cụ thể

Các event quan trọng

  • fork: Redis fork process con để ghi RDB hay AOF rewrite. Trên Linux với CoW (Copy-on-Write), fork chậm tỷ lệ thuận với memory đang dirty. Fork 500ms+ trên instance 20GB là bình thường; trên instance nhỏ thì cần điều tra.
  • aof-fsync-always: khi dùng appendfsync always — mỗi write đều fsync. Rất chậm nếu disk I/O yếu.
  • aof-stat: gọi stat() system call khi check AOF file.
  • rdb-unlink-temp-file: xoá RDB file tạm sau khi ghi xong. Trên Linux, unlink file lớn có thể chậm.
  • loading-rdb-used-mem: spike khi load RDB vào memory khi startup.

LATENCY DOCTOR giải thích từng event tìm thấy và đề xuất hành động cụ thể (ví dụ: "Consider using a faster disk", "Consider disabling THP"). Nên chạy sau mỗi latency incident trước khi điều tra thêm.

12

redis-cli Helpers

redis-cli có nhiều flag chạy chế độ diagnostics thay vì interactive shell. Hữu ích cho debugging nhanh và script automation.

--stat: live stats

redis-cli --stat
# In dòng stats mỗi 1 giây:
# ------- data ------ --------------------- load -------------------- - child -
# keys       mem      clients blocked requests            connections
# 1234567    1.01G    248     5       98765432 (+12543)   1543200

Cột requests (+N) là delta từ lần trước — đây là instantaneous ops/sec. Dùng để xem trend nhanh mà không cần setup Prometheus.

--latency và --latency-history

# Đo latency round-trip liên tục (PING-based)
redis-cli --latency
# min: 0, max: 1, avg: 0.14 (1543 samples)

# Latency sample mỗi 15 giây, kèm timestamp
redis-cli --latency-history -i 15

Đây là latency từ góc nhìn client (network + processing), khác với LATENCY built-in theo dõi event nội bộ.

--bigkeys: tìm key lớn

redis-cli --bigkeys
# Quét toàn bộ keyspace bằng SCAN (không block server)
# In summary khi xong:
# Biggest string found 'product:image:12345' has 524288 bytes
# Biggest list   found 'feed:user:789' has 50000 items
# Biggest set    found 'tags:all' has 12000 members

Chạy --bigkeys vào off-peak. Nó dùng SCAN nên không block server, nhưng tăng thêm load do phải gọi DEBUG OBJECT (hoặc MEMORY USAGE trong version mới) cho mỗi key.

--hotkeys: tìm key được truy cập nhiều nhất

redis-cli --hotkeys
# Yêu cầu maxmemory-policy là LFU (allkeys-lfu hoặc volatile-lfu)
# CONFIG SET maxmemory-policy allkeys-lfu

# Kết quả:
# hot key found with counter: 9841   keyname: product:100

--hotkeys dựa vào LFU counter của Redis 4.0+. Nếu đang dùng policy LRU hoặc noeviction, phải đổi sang LFU trước — hoặc dùng MONITOR (nhưng MONITOR có overhead rất cao, xem lưu ý bên dưới).

MONITOR — chỉ dùng khi debug

redis-cli MONITOR
# Stream mọi command thực thi realtime:
# 1748750000.123456 [0 10.0.0.5:54321] "GET" "user:12345"
# 1748750000.123789 [0 10.0.0.5:54322] "SET" "session:abc" "..." "EX" "3600"

Cảnh báo: MONITOR có thể giảm throughput của Redis 50% hoặc hơn trong production tải cao vì phải serialize và gửi mọi command cho client đang MONITOR. Chỉ dùng trong môi trường development hoặc debug ngắn hạn, và ngắt ngay sau khi xong.

13

Prometheus & Grafana — redis_exporter

redis_exporter (oliver006/redis_exporter) là standard tool để expose Redis metrics sang Prometheus. Nó scrape INFO định kỳ và convert từng field thành Prometheus metric.

Cài đặt và chạy

# Docker
docker run -d \
  --name redis_exporter \
  -p 9121:9121 \
  oliver006/redis_exporter \
  --redis.addr redis://10.0.0.1:6379 \
  --redis.password ""

# Kiểm tra metrics đang expose
curl http://localhost:9121/metrics | grep redis_memory

prometheus.yml scrape config

scrape_configs:
  - job_name: redis
    static_configs:
      - targets: ['redis-exporter:9121']
    scrape_interval: 15s

Các metrics quan trọng

# Memory
redis_memory_used_bytes
redis_memory_max_bytes
redis_mem_fragmentation_ratio

# Throughput
rate(redis_commands_total[1m])
redis_instantaneous_ops_per_sec

# Cache hit ratio (tính từ delta)
rate(redis_keyspace_hits_total[5m]) /
  (rate(redis_keyspace_hits_total[5m]) + rate(redis_keyspace_misses_total[5m]))

# Connections
redis_connected_clients
redis_rejected_connections_total

# Evictions
rate(redis_evicted_keys_total[1m])

# Replication lag
redis_replication_offset  # so sánh master vs replica

# Persistence
redis_rdb_changes_since_last_save
redis_aof_current_size_bytes

Grafana dashboard

Grafana có dashboard template sẵn cho redis_exporter tại Dashboard ID 763 (Redis Dashboard for Prometheus Redis Exporter). Import bằng cách vào Grafana → Dashboards → Import → nhập ID 763.

Dashboard này cover: memory usage, hit ratio, connected clients, commands/sec, latency, persistence status, và replication. Đây là starting point tốt — điều chỉnh thêm theo đặc thù của hệ thống.

14

Alert Thresholds Thực Tế

Danh sách dưới đây là starting point — các con số cụ thể cần điều chỉnh theo đặc thù của từng hệ thống (SLO, pattern traffic, role của Redis instance).

Metric Warning Critical Ghi chú
used_memory / maxmemory > 75% > 90% Eviction sắp xảy ra
mem_fragmentation_ratio > 1.5 > 2.0 Consider MEMORY PURGE hoặc restart
mem_fragmentation_ratio < 1.0 < 0.9 Đang swap — cần scale ngay
connected_clients / maxclients > 80% > 95% Connection pool exhausted
rejected_connections (rate) > 0 Bất kỳ giá trị nào cũng là incident
Cache hit ratio < 90% < 70% Tùy use case; cold cache sau restart là ngoại lệ
evicted_keys (rate) > 0 Chỉ alert nếu Redis là data store, không phải pure cache
Replication lag (bytes) > 10% backlog size > 50% backlog size Risk của full sync
Replication heartbeat lag > 5s > 30s Replica gần offline
connected_slaves < expected 0 Replica đã disconnect
SLOWLOG entry count (rate) Tăng đột biến Cần đọc entries để diagnose
rdb_last_bgsave_status err RDB persist thất bại
aof_last_bgrewrite_status err AOF rewrite thất bại
LATENCY event (fork, fsync) > 100ms > 500ms Tùy workload và disk speed

Application-side metrics

Không phải mọi vấn đề Redis đều thấy được từ server-side. Nên đo thêm ở tầng application:

  • Per-command latency p50/p95/p99: từ góc nhìn application, bao gồm network. Phân biệt được "Redis chậm" vs "mạng chậm".
  • Connection pool wait time: thời gian chờ lấy connection từ pool. Cao = pool size không đủ hoặc Redis quá tải.
  • Redis error rate per route: timeout, connection refused, LOADING. Giúp pinpoint impact thực tế lên user.
  • Cache hit ratio per key group: tổng hit ratio ẩn đi detail. user:* có thể đang 99% nhưng product:* chỉ 40%.
15

Anti-patterns & Best Practices

Anti-patterns

  • MONITOR trong production: overhead CPU rất lớn, có thể giảm throughput 50%+. Chỉ dùng khi thực sự cần và ngắt ngay sau khi xong.
  • SLOWLOG max-len quá lớn: đặt 10000 hay 1000000 thì buffer đó nằm trong memory. Default 128 thường đủ; 512–1024 nếu cần history dài hơn.
  • Poll INFO tần suất cao: mỗi 100ms hay 500ms không cần thiết và tạo overhead. 10–30s là hợp lý; Prometheus scrape 15s là chuẩn.
  • Chỉ monitor memory: bỏ qua latency, hit ratio, replication lag. Memory ổn không có nghĩa là Redis đang hoạt động đúng.
  • Alert trên cumulative counter: evicted_keys là counter tăng mãi. Alert phải dựa trên rate (delta / thời gian), không phải absolute value.
  • Không đặt CLIENT SETNAME: làm cho CLIENT LIST khó đọc. Mọi connection pool nên đặt tên.
  • Không có alert: silent degradation. Redis có thể evict key hàng giờ trước khi user báo lỗi.

Best practices

  • Stack chuẩn cho production: redis_exporter + Prometheus + Grafana. Setup một lần, có metrics liên tục, alert qua Alertmanager.
  • Đặt slowlog-log-slower-than 10000 (10ms) làm baseline. Review SLOWLOG entries mỗi ngày trong 2 tuần đầu sau deploy để biết normal pattern.
  • Đặt latency-monitor-threshold 100 để bắt event nội bộ > 100ms.
  • Chạy redis-cli --bigkeys định kỳ (weekly, off-peak). Lưu kết quả để so sánh trend key size.
  • Với instance dùng LFU policy: redis-cli --hotkeys mỗi khi nghi ngờ hot key.
  • Document SLO của Redis instance: hit ratio tối thiểu bao nhiêu, latency p99 tối đa bao nhiêu. Alert thresholds phải dẫn xuất từ SLO đó, không phải số ngẫu nhiên.
  • Bật activedefrag yes trên Redis 4.0+ để tự động defrag background nếu fragmentation thường xuyên cao. Cần monitor CPU overhead của defrag.

Bài tiếp theo

Bài 104 đo lường throughput và latency của Redis instance với redis-benchmarkmemtier_benchmark — cách thiết lập test scenario sát với workload thực, diễn giải kết quả, và benchmarking trong môi trường có TLS.

Tham khảo