Dùng appropriate data type: Hash thay vì nhiều String key riêng lẻ cho object nhỏ (Redis tự động dùng listpack encoding khi Hash nhỏ hơn hash-max-listpack-entries entries và mỗi value nhỏ hơn hash-max-listpack-value bytes — memory efficient hơn hashtable).
- Lưu ý: Redis 7.0 đổi tên ziplist thành listpack; config hiện tại dùng
hash-max-listpack-entriesvàhash-max-listpack-value. - Compressed encoding: Redis tự optimize encoding dựa trên size (listpack, intset, skiplist).
- Dùng
OBJECT ENCODING keyđể xem encoding. - Giảm key size:
usr:1001:prfthay vìuser:1001:profiletiết kiệm memory nhân với hàng triệu key. - Set TTL cho tất cả cache key tránh memory leak.
- Dùng
MEMORY USAGE keyđể đo memory một key,MEMORY DOCTORđể chẩn đoán vấn đề memory. - Nén value ở application layer (gzip JSON trước khi lưu) giảm 70-80% với JSON lớn.
- Monitor
used_memory,mem_fragmentation_ratio(>1.5 là vấn đề fragmentation — có thể bậtactivedefrag yeshoặc dùngMEMORY PURGEđể defragment).
Use appropriate data types: Hash instead of many individual String keys for small objects (Redis automatically uses listpack encoding when a Hash has fewer than hash-max-listpack-entries entries and each value is smaller than hash-max-listpack-value bytes — more memory-efficient than a hashtable).
- Note: Redis 7.0 renamed ziplist to listpack; the current config keys are
hash-max-listpack-entriesandhash-max-listpack-value. - Compressed encodings: Redis automatically selects efficient encodings based on size (listpack, intset, skiplist).
- Use
OBJECT ENCODING keyto inspect the encoding. - Shorten key names:
usr:1001:prfinstead ofuser:1001:profilesaves memory when multiplied across millions of keys. - Set a TTL on all cache keys to prevent memory leaks.
- Use
MEMORY USAGE keyto measure a single key andMEMORY DOCTORto diagnose memory issues. - Compress values at the application layer (gzip JSON before storing) to achieve 70-80% size reduction for large JSON payloads.
- Monitor
used_memoryandmem_fragmentation_ratio(> 1.5 indicates fragmentation — enableactivedefrag yesor runMEMORY PURGEto defragment).