Databases 14 min read

Mastering Redis Expiration and Eviction: 8 Strategies, LRU & LFU Explained

Redis handles key expiration using commands like EXPIRE, PEXPIRE, EXPIREAT, and PEXPIREAT, offers TTL queries, and employs three deletion strategies—timed, lazy, and periodic scanning—while its eight eviction policies (e.g., volatile‑lru, allkeys‑lfu, noeviction) and refined LRU/LFU algorithms manage memory pressure efficiently.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
Mastering Redis Expiration and Eviction: 8 Strategies, LRU & LFU Explained

Memory Expiration

When a Redis server runs out of memory, keys can be given a time‑to‑live (TTL) to free memory automatically. Redis provides four commands to set expiration:

EXPIRE key ttl : set expiration in seconds.

PEXPIRE key ttl : set expiration in milliseconds.

EXPIREAT key timestamp : set expiration at a specific Unix timestamp (seconds).

PEXPIREAT key timestamp : set expiration at a specific Unix timestamp (milliseconds).

All of these ultimately invoke the internal pexpireat implementation. The SET command can also set an expiration atomically.

After an expiration is set, the TTL and PTTL commands return the remaining time (‑1 if no expiration, ‑2 if the timeout is invalid).

Expiration Strategies

Redis can delete expired keys using three strategies:

Timed deletion : a timer per key removes it exactly when the TTL expires (memory‑friendly but CPU‑intensive).

Lazy deletion : keys are checked for expiration only when accessed; expired keys are removed on read.

Periodic scanning : Redis periodically scans keys with an expiration and deletes those that have expired (a compromise between the first two).

Redis combines lazy deletion and periodic scanning. The periodic scan only examines keys that have an expiration, because such keys are stored separately.

typedef struct redisDb {
  dict *dict;            // all key‑value pairs
  dict *expires;        // keys with an expiration
  dict *blocking_keys;  // blocked keys (e.g., BLPOP)
  dict *watched_keys;   // WATCHed keys
  int id;               // database ID
  // ... other fields omitted
} redisDb;

8 Eviction Policies

If the memory limit is reached and no keys have an expiration, Redis applies one of eight eviction policies, configured via maxmemory-policy:

Policy

Description

volatile-lru

Evicts least‑recently‑used keys with an expiration.

allkeys-lru

Evicts least‑recently‑used keys among all keys.

volatile-lfu

Evicts least‑frequently‑used keys with an expiration.

allkeys-lfu

Evicts least‑frequently‑used keys among all keys.

volatile-random

Randomly evicts keys with an expiration.

allkeys-random

Randomly evicts any key.

volatile-ttl

Evicts keys with the shortest remaining TTL.

noeviction

Rejects write commands when memory is exhausted.

The maxmemory directive sets the memory limit (e.g., maxmemory 1GB), and can be changed at runtime with CONFIG SET maxmemory ….

LRU Algorithm

Redis uses a modified LRU (Least Recently Used) algorithm. Instead of tracking every access, it samples a configurable number of keys (default maxmemory_samples 5) and evicts the least‑recently‑used among the sample.

The global lru_clock is updated every 100 ms by the server cron, avoiding per‑key system calls.

Object structures store a 24‑bit lru field (≈194 days). When the global clock wraps, Redis adjusts the idle‑time calculation accordingly.

LRU comparison diagram
LRU comparison diagram

LFU Algorithm

LFU (Least Frequently Used) stores usage frequency in the same lru field: the high 16 bits record the last decrement time, the low 8 bits store a logarithmic counter.

Counter Increment

When a key is accessed, the counter is increased probabilistically based on the formula P = 1 / (baseval * lfu_log_factor + 1), where baseval is the difference between the current counter and a base value (default 5). lfu_log_factor 10 Higher lfu_log_factor values make the counter grow more slowly; the default of 10 allows the counter to reach its maximum (255) after about one million accesses.

LFU counter growth
LFU counter growth

Counter Decrement

The counter decays over time, controlled by lfu-decay-time (default 1 minute). The decay algorithm computes the idle period and subtracts idle_time / lfu_decay_time from the counter.

lfu-decay-time 1

Summary

This article explains how Redis manages key expiration, the three expiration deletion strategies, the eight configurable eviction policies, and the internal LRU and LFU algorithms that balance performance and memory usage.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

redisLRULFUExpirationEviction Policies
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

0 followers
Reader feedback

How this landed with the community

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.