Key cleaning of Redis, that is, memory reclamation, is mainly divided into two parts: expired deletion strategy and memory elimination strategy.
Expired Deletion Policy
Delete keys that reached the expiration date.
The first is to periodically check the deletion
A timer is created for each key whose expiration time is set. Once the expiration time is reached, the key is deleted. This way to immediately clear out outdated data, better for memory,
However, the disadvantage is that it consumes a lot of CPU resources to process expired data, which will affect the throughput and response time of Redis.
Second: lazy check delete
When a key is accessed, the system checks whether the key is expired. If the key is expired, the system deletes it. This mode saves CPU resources to the maximum extent.
Not so good for memory, however, there is an extreme case where a large number of expired keys are not accessed again because they will not be cleared, resulting in a large amount of memory usage.
Third: check regularly delete
Every once in a while, scan the dictionary of expired keys in Redis and remove some expired keys. This approach is a compromise between the first two. Under different circumstances, adjust the periodic scan interval to optimize CPU and memory.
Memory flushing strategy
Redis memory flushing strategy refers to the use of some algorithm to determine which data to clean up to ensure that new data is stored when maxmemory limit is reached.
The first type is not processed and waits for an error (default configuration)
- Noeviction, won’t remove key when memory is out of order, error message will be returned when write command is executed. Redis default configuration is noeviction
The second type is culled from the keys in all result sets
- Allkeys-random is a random selection of keys from allkeys
- Allkeys-lru selects the most recently used key from all the keys and removes it
- Allkeys-lfu selects the least frequently used key from allkeys to eliminate. (This is a new policy since Redis 4.0)
The third type is selected from keys that have an expiration date
In this way, a portion of the key is eliminated from the result set with an expires time. The selection algorithm includes:
-
Volatile -random Deletes randomly selected keys from the result set with expiration time.
-
Volatile -lru selects the most recent key from the result set with an expiration date and deletes it
-
Volatile – TTL Selects the keys with the shortest lifespan from the result set with the expiration date and deletes them (i.e. deletes the keys that are about to expire first)
-
Volatile – lFU selects the least frequently used key from the result set at expiration time and starts removing it (a new policy since Redis 4.0)