Databases 7 min read

Configuring Redis Memory Size and Eviction Policies (LRU and LFU)

Redis caches can fill up, requiring memory eviction; this guide explains how to set Redis maxmemory (e.g., 5GB), choose appropriate eviction policies such as allkeys-lru or allkeys-lfu, and details the underlying LRU and LFU algorithms and their configuration commands.

Top Architect
Top Architect
Top Architect
Configuring Redis Memory Size and Eviction Policies (LRU and LFU)

Generally, cache capacity is smaller than the total data size, so when Redis cache grows it will eventually be filled, triggering Redis's memory eviction mechanism to free space for new data.

Configuring Redis Memory Size

Set the Redis memory limit according to the 80/20 principle or a range of 15%–30% of total data; for example, to allocate 5 GB:

config set maxmemory 5gb

Verify the setting with:

config get maxmemory

Redis Eviction Policies

Redis provides several eviction strategies. The default is noeviction , which never removes data and raises an error when memory is exhausted. Other policies include:

noeviction

allkeys-random

allkeys-lru

allkeys-lfu

volatile-random

volatile-ttl

volatile-lru

volatile-lfu

Policies prefixed with volatile affect only keys with an expiration time, while allkeys policies consider every key in the dataset.

LRU Algorithm

LRU (Least Recently Used) evicts the least recently accessed keys. Redis implements LRU by recording a timestamp for each key and, when eviction is needed, sampling a configurable number of keys (default 5) and removing the one with the smallest timestamp. The sample size can be adjusted with config set maxmemory-samples <N> .

LFU Algorithm

LFU (Least Frequently Used) was added in Redis 4.0. It extends LRU by adding an 8‑bit counter to each key, tracking access frequency. The 24‑bit lru field is split into a 16‑bit timestamp (ldt) and an 8‑bit access counter. When evicting, Redis prefers keys with the lowest counter, breaking ties with the timestamp.

LFU is useful when some data is accessed very rarely; it can evict such infrequently used keys even if they were accessed recently, addressing scenarios where pure LRU would retain them.

Memory ManagementDatabaseRedisLRULFUEviction Policy
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.