Determination of expired keys:
1) Check whether the given key exists in the expired dictionary: if so, get the expiration time of the key.
2) Check whether the current UNIX timestamp is greater than the expiration time of the key: if so, the key is expired; Otherwise, the key is expired.
Redis uses both lazy deletion and periodic deletion.
1. Lazy deletion
Lazy delete means that all read/write Redis commands check the input key before executing:
- If the input key has expired, the input key is removed from the database.
- If the input key is not expired, the actual command is executed.
2. Delete it periodically
The periodic deletion policy deletes expired keys at intervals. By limiting the duration and frequency of the deletion operation, the impact of the deletion operation on CPU time and the memory waste caused by expired keys are reduced.
Specific implementation: in the specified time, points for many times through the server of each database, from a certain amount of database to take out a certain amount of random keys for inspection, and delete expired keys.
Refer to Redis Design and Implementation