Memory Reclamation#
The main reason for Redis's strong performance is its memory-based storage. However, the memory size of a single-node Redis should not be too large, as it can affect persistence or master-slave synchronization performance.
In the configuration file, you can set the maximum memory for Redis using maxmemory <bytes>
, such as maxmemory 1gb
. When the memory reaches the limit, it can no longer store data.
This leads to the memory reclamation strategy.
Expiration Strategy#
expire <key> <expireTime>
can set a time-to-live (TTL) for a key. When it expires, accessing it will return nil.
How does Redis know if a key has expired?
It uses two dictionaries to record key-value and key-ttl separately.
Does it delete immediately when the TTL expires?
For example:
Lazy deletion
Periodic deletion
Lazy Deletion#
It does not delete immediately when the TTL expires, but checks the key's lifespan when accessing the key. If it is expired, it deletes it.
Periodic Deletion#
Periodic deletion: This is done through a scheduled task that periodically samples some expired keys and then executes deletion. There are two execution cycles:
- Redis sets a scheduled task
serverCron()
during initialization, which cleans expired keys at the frequency ofserver.hz
, in SLOW mode. - Before each event loop in Redis, the
beforeSleep()
function is called to clean expired keys, in FAST mode.
Eviction Strategy#
Memory eviction: When Redis memory usage reaches the set threshold, it actively selects some keys to delete in order to free up more memory.
When processing commands, if memory is insufficient, and maxmemory
is set and it is not a Lua script being executed, it will first attempt to evict memory.
Eviction Strategy
How to know LRU and LFU?
Eviction Strategy Flowchart
For TTL, the longer the lifespan, the more it should be deleted; for LRU, the less recently accessed, the more it should be deleted; for LFU, the less frequently accessed, the more it should be deleted.
This article is synchronized and updated to xLog by Mix Space. The original link is https://blog.0xling.cyou/posts/redis/redis-6