Databases 14 min read

Redis Memory Management: Expiration, Eviction Policies, and LRU/LFU Algorithms

This article explains how Redis handles memory exhaustion by using key expiration commands, describes the three expiration strategies, details the eight maxmemory eviction policies, and dives into the internal LRU and LFU algorithms with their configuration parameters and code examples.

Top Architect
Top Architect
Top Architect
Redis Memory Management: Expiration, Eviction Policies, and LRU/LFU Algorithms

When a Redis server runs out of memory, it can continue to receive commands, but the way it handles those commands depends on whether keys have expiration times set. Redis provides four commands— expire , pexpire , expireat , and pexpireat —to assign a time‑to‑live (TTL) to a key in seconds or milliseconds.

After a key is given a TTL, its remaining lifetime can be queried with ttl (seconds) or pttl (milliseconds). If a key has no expiration, these commands return -1 ; if the expiration is invalid, they return -2 .

Redis implements three expiration strategies for keys that have passed their TTL:

Timed deletion: a timer is set for each expiring key, which is memory‑friendly but consumes CPU resources.

Lazy deletion: keys are only removed when accessed; this can waste memory if many expired keys are never accessed.

Periodic scanning: the server periodically scans the dataset and deletes expired keys, balancing CPU and memory usage.

In practice, Redis combines the lazy deletion (strategy 2) and periodic scanning (strategy 3) approaches.

When the dataset is full and no keys have an expiration, Redis relies on eviction policies configured via the maxmemory and maxmemory-policy settings. The eight built‑in policies are:

volatile-lru : LRU eviction of keys with an expiration.

allkeys-lru : LRU eviction of any key.

volatile-lfu : LFU eviction of keys with an expiration.

allkeys-lfu : LFU eviction of any key.

volatile-random : Random eviction of keys with an expiration.

allkeys-random : Random eviction of any key.

volatile-ttl : Evicts keys that are closest to expiring.

noeviction : Default; commands that would increase memory fail with an error.

These policies can be changed at runtime with CONFIG SET maxmemory-policy <policy> . The maxmemory-samples parameter (default 5) controls how many random keys are sampled when applying LRU/LFU eviction.

Redis’s LRU implementation is a sampled approximation rather than a true global LRU. It stores a 24‑bit lru field in each object, representing the last access time in minutes. A global lru_clock is updated every 100 ms by the server cron, allowing fast updates without calling the system clock for each key.

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;

Because the 24‑bit lru field wraps after about 194 days, Redis uses the difference between the global lru_clock and the object's lru , handling wrap‑around by adding the maximum value when necessary.

Redis also supports an LFU (Least Frequently Used) eviction algorithm. The low 8 bits of the same lru field store a counter that records access frequency, while the high 16 bits store the last decrement time (in minutes). The counter grows probabilistically: on each access a random number R is drawn, and the counter is incremented only if R < 1/(baseval * lfu_log_factor + 1) . The lfu_log_factor (default 10) controls how quickly the counter can increase.

lfu_log_factor 10

To prevent the counter from saturating at 255, Redis periodically decays it based on the lfu_decay_time parameter (default 1 minute). The decay algorithm converts the stored timestamp to minutes, computes the idle time, divides it by lfu_decay_time , and subtracts that many periods from the counter.

lfu-decay-time 1

In summary, Redis provides a rich set of mechanisms for managing memory pressure: key expiration commands, three expiration handling strategies, eight configurable eviction policies, and two sophisticated eviction algorithms (sampled LRU and probabilistic LFU) with tunable parameters for fine‑grained control.

Memory ManagementRedisLRUdatabasesLFUeviction policies
Top Architect
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.