How Does Redis Delete Expired Keys? Lazy vs Periodic Strategies Explained
Redis uses both lazy and periodic deletion strategies to remove expired keys, balancing CPU usage and memory efficiency, and these strategies also affect how persistence mechanisms like RDB and AOF as well as master‑slave replication handle expired keys.
Deletion Strategies
Lazy Deletion : Redis checks a key's expiration only when the key is accessed. This approach is CPU‑friendly because it limits work to the specific key being used, but it can waste memory if many keys expire without further access.
Periodic Deletion : Redis runs a background task at intervals that scans a random subset of keys in each database's expiration dictionary, deleting those that have expired. This method reduces memory waste while keeping CPU impact moderate.
Persistence Handling of Expired Keys
RDB : When generating an RDB snapshot, Redis skips expired keys, so they are not saved to the dump file.
AOF : Every command execution checks for key expiration; if a key is expired, Redis issues a delete command, which is then recorded in the AOF log.
AOF Rewrite : Similar to RDB, the rewrite process filters out expired keys before writing the new AOF file.
Replication Handling of Expired Keys
Master : Executes the standard deletion strategies (lazy or periodic) on its own data.
Slave : Deletion of expired keys on a replica is driven by the master. After the master deletes an expired key, it sends an explicit delete command to the slave; the slave will not delete the key on its own until it receives this command, though it will still serve client requests for the key until then.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
