Skip to content

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.

PolicyDescriptionUse Case
noevictionNo eviction; return errors when memory is fullScenarios where data loss is unacceptable
allkeys-lruEvict least recently used keysMost common! General-purpose caching
allkeys-lfuEvict least frequently used keysScenarios with obvious hot data
allkeys-randomRandomly evict keysUniform access frequency across keys
volatile-lruEvict LRU among keys with TTL setMixed storage (cache + persistent)
volatile-lfuEvict LFU among keys with TTL setMixed storage, considering access frequency
volatile-randomRandomly evict among keys with TTLMixed storage
volatile-ttlEvict keys with smallest TTL firstWant 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 4gb
bash
1) "maxmemory-policy"
2) "noeviction"
OK
OK

6.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:1001
bash
(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