Databases 17 min read

Understanding Redis Eviction Policies and Memory Management

This article explains Redis's in‑memory database architecture, detailing data locality, various eviction policies such as LRU, LFU, random and TTL, their configuration via maxmemory settings, and provides code examples of the eviction process and memory‑freeing functions.

Top Architect
Top Architect
Top Architect
Understanding Redis Eviction Policies and Memory Management

Redis Database Overview

Redis is a mature in‑memory data store offering features such as key expiration and eviction strategies.

Data Locality Principle

The locality principle explains why recently used data is more likely to be accessed again, forming the basis for cache eviction.

Eviction Strategies

Redis supports LRU (Least Recently Used), LFU (Least Frequently Used), random, and TTL‑based eviction. LRU removes the least recently accessed keys, LFU removes keys with the lowest access frequency, and TTL removes keys with the smallest remaining time‑to‑live.

Expiration Policies

Two expiration mechanisms exist: periodic deletion (every 100 ms a random set of expiring keys is checked) and lazy deletion (keys are removed when accessed).

Memory Eviction Mechanism

When memory usage exceeds server.maxmemory , Redis selects a policy (e.g., allkeys-lru ) and evicts keys until the limit is satisfied. The process involves sampling keys, building an eviction pool, and deleting selected keys synchronously or lazily.

Configuration Example

In redis.conf you can set maxmemory 100mb and maxmemory-policy allkeys-lru to enable LRU eviction.

Key Functions

int processCommand(client *c) {
    …
    if (server.maxmemory) {
        int retval = freeMemoryIfNeeded();
        …
    }
    …
}
static int isSafeToPerformEvictions(void) {
    if (server.lua_timedout || server.loading) return 0;
    …
    return 1;
}
int performEvictions(void) {
    …
    while (mem_freed < mem_tofree) {
        …
    }
    …
}

Additional helper functions such as freeMemoryIfNeeded , evictionPoolPopulate , and LFU counter updates illustrate the internal mechanics of Redis's memory management.

Memory ManagementRedisTTLLRUdatabasesLFUeviction
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.