Redis Expiration and Memory Eviction Strategies Explained
This article explains how to set key expiration times in Redis, the lazy and periodic deletion mechanisms for expired data, and the various memory eviction policies that Redis employs when the maxmemory limit is reached, providing a comprehensive guide for interview preparation.
Redis allows you to set expiration times for keys, either when creating them with commands such as SET key value EX [seconds] or SETEX key [seconds] value , or later using commands like EXPIRE , PEXPIRE , EXPIREAT , and PEXPIREAT . The remaining time-to-live can be queried with TTL (seconds) or PTTL (milliseconds).
When a key expires, Redis can delete it using two strategies: lazy deletion , which checks expiration only when the key is accessed and removes it then (controlled by lazyfree-lazy-eviction=yes ), and periodic deletion , which scans keys at intervals defined by the hz configuration (e.g., hz 10 means ten scans per second) to proactively remove expired keys while limiting CPU impact.
If memory usage reaches the maxmemory limit, Redis activates one of eight memory eviction policies . Policies prefixed with volatile apply only to keys with an expiration time, while those prefixed with allkeys consider all keys. The policies include variants of LRU (Least Recently Used) and LFU (Least Frequently Used) as well as random and no‑eviction options, allowing administrators to balance memory usage and performance.
In practice, combining lazy and periodic deletion provides a balance between CPU efficiency and memory cleanliness, while selecting an appropriate eviction policy ensures Redis can continue operating when memory is constrained.
For further reading, the article links to additional Redis topics such as Sentinel high‑availability, data persistence, and the full range of Redis data types.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
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.