Optimizing Memory Usage
1. Measuring Memory Consumption
| Command | Description |
INFO memory | used_memory, rss, fragmentation, peak |
MEMORY STATS | Detailed allocator breakdown |
MEMORY USAGE key [SAMPLES n] | Per-key estimate |
MEMORY DOCTOR | Heuristic advice |
2. Setting Max Memory
| Directive | Description |
maxmemory 4gb | Hard cap; triggers eviction policy |
maxmemory-policy | See section 38 |
3. Configuring Memory Policies
| Directive | Effect |
maxmemory-samples 5 | LRU/LFU sample size; higher = more accurate, more CPU |
lazyfree-lazy-eviction yes | Async free on eviction |
4. Using Smaller Encodings
| Type | Compact Encoding | Threshold Directive |
| Hash | listpack | hash-max-listpack-entries / hash-max-listpack-value |
| List | listpack/quicklist | list-max-listpack-size |
| Set | intset/listpack | set-max-intset-entries / set-max-listpack-entries |
| Sorted set | listpack | zset-max-listpack-entries / zset-max-listpack-value |
5. Reducing Key Size
| Tip | Detail |
| Short names | u:42:n instead of user:42:name |
| Hash grouping | Use one hash with many fields instead of many keys |
6. Sharing Common Strings
| Optimization | Detail |
| Shared integers | Small ints 0..OBJ_SHARED_INTEGERS reuse one object |
| Internalize enums | Store enum strings consistently |
7. Using Hash Field Expiration
| Command | Description |
HEXPIRE key seconds FIELDS n f1 ... | TTL on individual hash field 7.4+ |
HTTL key FIELDS n f1 ... | Inspect remaining TTL |
HPERSIST key FIELDS n f1 ... | Remove field expiration |
8. Avoiding Large Keys
Warning: Keys > 1 MB cause blocking on DEL, migration, and replication.
| Detection | Tool |
redis-cli --bigkeys | Find largest per type |
redis-cli --memkeys | Largest by memory |
9. Compressing Values
| Strategy | Detail |
| Client-side zstd/lz4 | Compress before SET; transparent to Redis |
| Tradeoff | CPU vs. memory + network |
10. Using EXPIRE for Cleanup
| Strategy | Effect |
| Always set TTL on cache keys | Prevents unbounded growth |
EXPIREAT | Align to wall-clock boundaries |
11. Analyzing Memory with MEMORY USAGE
MEMORY USAGE user:42 SAMPLES 0
| Param | Detail |
| SAMPLES 0 | Scan all sub-elements (accurate, slower) |
12. Sampling Memory Statistics
| Command | Description |
MEMORY STATS | Allocator buckets, dataset overhead, AOF buffers |
MEMORY MALLOC-STATS | jemalloc internals |
MEMORY PURGE | Reclaim memory back to OS |