Redis is a high-performance key-value storage system, widely used in caching, message queueing and other scenarios. To manage memory resources, Redis provides a key expiration mechanism, allowing users to set the time of survival (TTL) for the key. This article will explore Redis's expiration strategy, how to set the expiration time of keys, and the implementation principles behind these mechanisms.
1. Redis's expiration strategy
Redis handles expired keys through two main strategies: lazy deletion and periodic deletion.
1.1 Lazy Expiration
- Principle: When the client accesses a key, Redis will check whether the key has expired. If expired, delete the key immediately and return a null value.
- Advantages: The deletion operation will be triggered only when accessed, saving CPU resources.
- Disadvantages: If the expired key is not accessed for a long time, it will cause memory waste.
1.2 Active Expiration
- Principle: Redis will randomly check a certain number of keys regularly (default 10 times per second) and delete expired keys.
- Advantages: Expired keys can be cleaned in time to reduce memory usage.
- Disadvantages: If there are too many expired keys, it may occupy a certain amount of CPU resources.
1.3 Balance of expired strategies
Redis achieves a balance between memory management and performance by combining lazy deletion and periodic deletion. Lazy deletion ensures that expired keys are processed only when needed, while periodic deletion prevents expired keys from consuming memory for a long time.
2. How to set the expiration time of the key
Redis provides a variety of commands to set the expiration time of the key.
2.1 EXPIRE command
Sets a survival time in seconds for the key.
Syntax: EXPIRE key seconds
SET mykey "Hello" EXPIRE mykey 60 -- 60 Expired in seconds
2.2 PEXPIRE command
Sets a survival time in milliseconds for the key.
Syntax: PEXPIRE key millionseconds
Example:
SET mykey "Hello" PEXPIRE mykey 60000 -- 60000 millisecond(60 Second)Expired later
2.3 EXPIREAT Command
Sets an expiration time for the key in Unix timestamps (seconds).
Syntax: EXPIREAT key timestamp
Example:
redis
SET mykey “Hello”
EXPIREAT mykey 1672502400 – 2023-01-01 00:00:00 Expired
2.4 PEXPIREAT Command
Sets an expiration time for the key in Unix timestamps (milliseconds).
Syntax: PEXPIREAT key timestamp
Example:
SET mykey "Hello" PEXPIREAT mykey 1672502400000 -- 2023-01-01 00:00:00 Expired
2.5 TTL and PTTL commands
TTL: Return the remaining survival time (seconds) of the key.
PTTL: Returns the remaining survival time (milliseconds) of the key.
Example:
TTL mykey -- Returns the remaining seconds PTTL mykey -- Returns the remaining milliseconds
2.6 PERSIST command
Removes the expiration time of the key to make it permanent.
Syntax: PERSIST key
Example:
PERSIST mykey -- Remove mykey Expiration time
3. The principle of implementing the expiration mechanism
Redis's expiration mechanism is implemented based on the following data structures:
3.1 Expires Dictionary
- Redis uses a separate dictionary (hash table) to store the expiration time of all keys.
- The key is the key in the database, and the value is the corresponding expiration timestamp.
3.2 Deletion of expired keys
- Lazy Deletion: When accessing a key, Redis checks for an expired dictionary, and deletes the key if the current time is greater than the expiration time.
- Periodic Deletion: Redis will check a certain number of keys regularly and delete expired keys.
3.3 Memory recovery
When Redis's memory usage reaches the upper limit, a memory recovery mechanism (such as the maxmemory-policy configuration) is triggered, and expiration keys are removed first to free up memory.
4. Best Practices
4.1 Reasonably set the expiration time
- Set a reasonable expiration time according to business needs to avoid expiration of the key too early or too late.
- For cache scenarios, shorter expiration times (such as minutes or hours) can be used.
4.2 Monitor the number of expired keys
Use the INFO command to monitor the number of expired keys in Redis to ensure that memory resources are effectively managed.
INFO keyspace
4.3 Avoid expiration of a large number of keys at the same time
If a large number of keys expire at the same time, it may cause a degradation in Redis performance. This problem can be alleviated by randomizing expiration times.
4.4 Use maxmemory-policy to configure
Configure Redis's memory recovery policy, prioritizes the removal of expired keys or the least recently used keys (LRUs).
CONFIG SET maxmemory-policy volatile-lru
5. Summary
Redis's expiration mechanism realizes efficient management of memory resources through two strategies: lazy deletion and regular deletion. By reasonably setting the expiration time of keys, the performance and memory usage of Redis can be optimized. At the same time, understanding the implementation principles of the expiration mechanism will help better deal with scenarios with high concurrency and large data volume.
In practical applications, it is recommended to flexibly use Redis's expired commands according to business needs, and combine monitoring tools and configuration optimization to ensure the stability and efficiency of Redis.
References
Redis official documentation: /commands#expire
"Redis Design and Implementation" - Huang Jianhong
I hope this blog post can help you better understand Redis's expiration strategy and key expiration time settings! If you have any questions or suggestions, please leave a message to discuss.
This is the article about Redis's expiration strategy and key expiration time settings. For more related Redis expiration strategy content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!