1. What is Key's expiration strategy?
In Redis, the expiration strategy of a Key refers to the mechanism that manages the key lifecycle. By setting the expiration time (TTL - Time To Live), Redis can automatically delete expired keys, thereby freeing up memory space.
This is especially important for caching scenarios, as it ensures that data does not permanently occupy memory while keeping the system running efficiently.
2. The core concept of expiration strategy
Time to survive (TTL):
- TTL represents the length of time a bond survives in Redis.
- Can be passed
EXPIRE
andPXPIRE
The command sets TTL in seconds and milliseconds respectively.
Expiry Timestamp:
- Each key with an expiration time will be given a specific expiration timestamp indicating when the key will expire.
-
EXPIREAT
andPEXPIREAT
The command sets the expiration timestamp in seconds and milliseconds respectively.
3. Deletion strategy for expired keys
Redis provides two main strategies to handle expired keys:
Lazy Deletion
How it works:
- When a key expires, it will not be deleted immediately.
- Redis checks that it has expired only the next time the key is accessed.
- If it has expired, the key will be deleted.
advantage:
- Reduces CPU and memory usage because frequent scanning and deletion of expired keys are not required.
- Suitable for application scenarios that are not sensitive to delay.
shortcoming:
- Expired keys may exist in memory for a long time
- Take up unnecessary space
Active Deletion
How it works:
- Redis runs background tasks regularly, actively scanning and deleting expired keys.
- This strategy ensures that memory is not consumed by too many expired keys.
advantage:
- Free up memory space in time to avoid expired key accumulation affecting system performance.
- Suitable for high concurrency and latency-sensitive application scenarios.
shortcoming:
- Increased CPU load
- Because background scanning tasks require certain computing resources
4. Command to set expiration time
Redis provides a variety of commands to set the expiration time of a key:
EXPIRE key seconds
:
- Set keys in seconds
key
survival time. - Example:
EXPIRE myKey 3600
expressmyKey
Expired after 3600 seconds.
PXPIRE key milliseconds
:
- Set keys in milliseconds
key
The survival time provides higher accuracy. - Example:
PXPIRE myKey 1800000
expressmyKey
Expired after 1,800,000 milliseconds (i.e. 30 minutes).
EXPIREAT key timestamp
:
- Setting key
key
The expiration time of the specified Unix timestamp in seconds. - Example:
EXPIREAT myKey 1728000000
expressmyKey
It will expire at the time point corresponding to timestamp 1,728,000,000.
PEXPIREAT key timestamp
:
- Setting key
key
The expiration time of the specified Unix timestamp in milliseconds. - Example:
PEXPIREAT myKey 1728000000000
expressmyKey
It will expire at the time point corresponding to timestamp 1,728,000,000,000.
5. Check the remaining survival time
Redis provides two commands to query the remaining survival time of the key:
TTL key
:
- Returns the key in seconds
key
remaining survival time. - Example:
TTL myKey
Possible to return300
, indicating that the key has not expired for 300 seconds.
PTTL key
:
- Returns the key in milliseconds
key
remaining survival time. - Example:
PTTL myKey
Possible to return180000
, indicating that the key has 180,000 milliseconds (i.e. 3 minutes) not expired.
6. Batch setting and processing
In practical applications, multiple keys may need to be batched out-of-date or managed. To do this, you can use Redis's Pipeline function to improve operational efficiency:
Pipeline:
Send multiple commands to the Redis server at one time to reduce the number of network round trips and improve performance.
Example:
import redis r = (host='localhost', port=6379, db=0) pipe = () # Set expiration time in batches('key1', 3600) ('key2', 3600) ('key3', 3600) # Execute commands in the pipeline()
7. Choose the appropriate deletion strategy
In actual applications, the deletion strategy of expired keys should be selected according to specific requirements and system load conditions:
Lazy deletion:
- Suitable for scenarios that are not sensitive to latency and have sufficient memory resources.
- Can be adjusted
maxmemory
andmaxmemory-policy
To optimize memory usage.
Actively delete:
- Suitable for high concurrency and fast response applications.
- It should be noted that aggressive deletion will increase the load on the CPU, so the usage of system resources should be weighed when configuring.
8. Things to note
Precision of expiration time:
- use
PXPIRE
andPEXPIREAT
The command can set more accurate expiration time and is suitable for application scenarios where strict time control is required.
Behavior when the key does not exist:
- Redis returns an error if you try to set an expiration time for a non-existent key.
- Therefore, the existence of the key should be ensured before operation, or use
SET
Wait for commands to set the value and expiration time at the same time.
Memory management:
- The expired key will not be deleted immediately, but will be cleaned up by Redis's background tasks within a certain period of time.
- To avoid insufficient memory, it is recommended to configure it reasonably
maxmemory
and choose the right memory elimination strategy.
Summarize
Redis provides flexible expiration time settings and multiple deletion strategies to meet the needs of different application scenarios.
In actual use, appropriate commands and strategies should be selected based on the load conditions of the system and the characteristics of the application to optimize performance and resource utilization.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.