Redis Expiration and Eviction Strategies: Memory Management, LRU and LFU Algorithms
This article explains how Redis handles memory exhaustion by setting key expirations with commands like expire and pexpire, describes its lazy and periodic expiration strategies, details the eight configurable eviction policies, and dives into the internal LRU and LFU algorithms used for key eviction.
Redis stores data in memory, which is finite, so when memory is exhausted it must handle expired keys and eviction.
Keys can be given a time‑to‑live using four commands: expire , pexpire , expireat , and pexpireat . The ttl and pttl commands query remaining time.
Redis uses two primary expiration strategies: lazy deletion (checking expiration on access) and periodic scanning of keys with an expiry, combining both for efficiency.
When memory is full, Redis applies one of eight eviction policies configured via maxmemory-policy : volatile-lru , allkeys-lru , volatile-lfu , allkeys-lfu , volatile-random , allkeys-random , volatile-ttl , and noeviction . The maxmemory setting limits total memory usage.
typedef struct redisDb {
dict *dict; // all key‑value pairs
dict *expires; // keys with an expiration time
dict *blocking_keys; // keys blocked by commands like BLPOP
dict *watched_keys; // WATCHed keys
int id; // database ID
/* ... other fields omitted ... */
} redisDb;The LRU (Least Recently Used) policy in Redis is implemented by sampling a configurable number of keys (default 5) and evicting the least recently accessed among the sample. A global lru_clock updated every 100 ms avoids per‑key system calls.
typedef struct redisObject {
unsigned type:4; // object type (4 bits)
unsigned encoding:4; // encoding (4 bits)
unsigned lru:LRU_BITS; // last access time (24 bits)
int refcount; // reference count
void *ptr; // pointer to the actual data structure
} robj;Redis also supports an LFU (Least Frequently Used) policy. Each object stores a 24‑bit LRU field split into a 16‑bit last‑decrement‑time and an 8‑bit access counter. The counter grows probabilistically based on lfu_log_factor and decays according to lfu-decay-time .
Overall, the article explains how Redis manages key expiration, the available eviction policies, and the inner workings of its LRU and LFU algorithms.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.