Optimizing Memory Usage

1. Measuring Memory Consumption

CommandDescription
INFO memoryused_memory, rss, fragmentation, peak
MEMORY STATSDetailed allocator breakdown
MEMORY USAGE key [SAMPLES n]Per-key estimate
MEMORY DOCTORHeuristic advice

2. Setting Max Memory

DirectiveDescription
maxmemory 4gbHard cap; triggers eviction policy
maxmemory-policySee section 38

3. Configuring Memory Policies

DirectiveEffect
maxmemory-samples 5LRU/LFU sample size; higher = more accurate, more CPU
lazyfree-lazy-eviction yesAsync free on eviction

4. Using Smaller Encodings

TypeCompact EncodingThreshold Directive
Hashlistpackhash-max-listpack-entries / hash-max-listpack-value
Listlistpack/quicklistlist-max-listpack-size
Setintset/listpackset-max-intset-entries / set-max-listpack-entries
Sorted setlistpackzset-max-listpack-entries / zset-max-listpack-value

5. Reducing Key Size

TipDetail
Short namesu:42:n instead of user:42:name
Hash groupingUse one hash with many fields instead of many keys

6. Sharing Common Strings

OptimizationDetail
Shared integersSmall ints 0..OBJ_SHARED_INTEGERS reuse one object
Internalize enumsStore enum strings consistently

7. Using Hash Field Expiration

CommandDescription
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.
DetectionTool
redis-cli --bigkeysFind largest per type
redis-cli --memkeysLargest by memory

9. Compressing Values

StrategyDetail
Client-side zstd/lz4Compress before SET; transparent to Redis
TradeoffCPU vs. memory + network

10. Using EXPIRE for Cleanup

StrategyEffect
Always set TTL on cache keysPrevents unbounded growth
EXPIREATAlign to wall-clock boundaries

11. Analyzing Memory with MEMORY USAGE

MEMORY USAGE user:42 SAMPLES 0
ParamDetail
SAMPLES 0Scan all sub-elements (accurate, slower)

12. Sampling Memory Statistics

CommandDescription
MEMORY STATSAllocator buckets, dataset overhead, AOF buffers
MEMORY MALLOC-STATSjemalloc internals
MEMORY PURGEReclaim memory back to OS