Redis provides multiple approaches for handling expired data:
Immediate Expiration Handling
A timer-based mechanism deletes keys precisely when their expiration time is reached.
Benefits: Optimal memory usage Drawbacks: Increased CPU overhead that impacts server response times and throughput
Periodic Cleanup Process
The activeExpireCycle() funcsion systematically examines each database's expiration set. During each database scan:
- Randomly selects W keys for inspection
- Removes expired keys immediately
- If more than W×25% keys are deleted, continues scanning the same database
- If fewer key are removed, proceeds to the next database
- The W parameter equals ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP
The current_db parameter tracks the last processed database, enabling continuation from the correct point when execution time limits are reached.
Characteristics: Random sampling with focused inspection Benefits: Configurable check frequency with moderate memory consumption Drawbacks: Incomplete cleanup of expired data
Lazy Deletion Mechanism
Expired data remains untouched until accessed during query operations.
Benefits: Minimal CPU resource consumption Drawbacks: High memory consumption due to persistent expired data
Memory Eviction Policies
Every command execution triggers memory availability checks. When minimum storage requirements aren't met, the eviction algorithm activates. If sufficient space cannot be reclaimed, the system returns an error:
(error) OOM command not allowed when used memory > 'maxmemory'
Configuration parameters:
# Maximum memory allocation
maxmemory # Percentage of physical memory, defaults to 0 (unlimited). Production environments typically set above 50%
# Number of random samples for deletion candidates
maxmemory-samples # Avoids full database scans that cause performance degradation
# Eviction strategy selection
maxmemory-policy # Algorithm for selecting which data to remove after reaching memory limits
Eviction strategies:
# Volatile data examination (potentially expiring datasets in server.db[i].expires)
1. volatile-lru: Eliminate least recently used data
2. volatile-lfu: Remove least frequently accessed data
3. volatile-ttl: Delete data with nearest expiration times
4. volatile-random: Random data elimination
# Global dataset examination (all data in server.db[i].dict)
5. allkeys-lru: Eliminate least recently used entries
6. allkeys-lfu: Remove least frequently accessed entries
7. allkeys-random: Random entry deletion
# Disable eviction
8. no-eviction: Prevent data removal (default in Redis 4.0), triggers OOM errors
maxmemory-policy volatile-lru