6. Memory Management
6.1 Key Expiration Strategies
Redis uses two expiration strategies working together:
- 🕐 Lazy deletion: A key is only checked for expiration when accessed; if expired, it's deleted
- 🔄 Periodic deletion: Every 100ms, a random batch of keys is sampled and expired ones are deleted
📝 Note: Why not scan all expired keys directly? Because there could be hundreds of thousands of keys — a full scan would block the main thread. The lazy + periodic combination is a trade-off between performance and accuracy.
6.2 Memory Eviction Policies (8 options)
When maxmemory reaches its limit, Redis needs to free up space for new data — that's when eviction policies come into play.
| Policy | Description | Use Case |
|---|---|---|
| noeviction | No eviction; return errors when memory is full | Scenarios where data loss is unacceptable |
| allkeys-lru | Evict least recently used keys | Most common! General-purpose caching |
| allkeys-lfu | Evict least frequently used keys | Scenarios with obvious hot data |
| allkeys-random | Randomly evict keys | Uniform access frequency across keys |
| volatile-lru | Evict LRU among keys with TTL set | Mixed storage (cache + persistent) |
| volatile-lfu | Evict LFU among keys with TTL set | Mixed storage, considering access frequency |
| volatile-random | Randomly evict among keys with TTL | Mixed storage |
| volatile-ttl | Evict keys with smallest TTL first | Want soon-to-expire keys removed first |
bash
# View current eviction policy
CONFIG GET maxmemory-policy
# Set eviction policy
CONFIG SET maxmemory-policy allkeys-lru
# Set maximum memory
CONFIG SET maxmemory 4gbbash
1) "maxmemory-policy"
2) "noeviction"
OK
OK6.3 Memory Optimization Tips
bash
# 1. Use Hash instead of multiple Strings (small Hash uses ziplist encoding, lower memory)
# Bad: SET user:1001:name "Alice" / SET user:1001:age "28"
# Good: HSET user:1001 name "Alice" age 28
# 2. Keep key names short (key names also consume memory!)
# Bad: user_profile_information_for_user_1001
# Good: u:1001:p
# 3. Use integer sets instead of Sets (auto-enabled when elements are all integers and count is small)
SADD status_set 0 1 2 3
# 4. Use integer enums instead of string values
# Bad: SET user:1001:gender "male"
# Good: SET user:1001:gender 1 (1=male, 2=female)
# 5. Set reasonable expiration times to avoid unused data consuming memory
EXPIRE temp:data 3600
# 6. View memory usage
INFO memory
MEMORY USAGE user:1001bash
(integer) 4
(integer) 1
# Memory
used_memory:1520840
used_memory_human:1.45M
used_memory_rss:5234688
used_memory_rss_human:4.99M
mem_fragmentation_ratio:3.44
(integer) 80