Databases 10 min read

Mastering Redis Expiration and Memory Eviction: Strategies & Best Practices

This article explains how Redis handles key expiration, the TTL and TTI concepts, periodic and lazy deletion strategies, their impact on persistence and replication, and the various memory eviction policies—including LRU and LFU—so developers can efficiently manage data and improve system performance.

Architecture & Thinking
Architecture & Thinking
Architecture & Thinking
Mastering Redis Expiration and Memory Eviction: Strategies & Best Practices

In program development, Redis is a high‑performance in‑memory database widely used for caching, message queues, and more. As data volume grows, effective management of key expiration and memory eviction is crucial.

1. Redis Data Expiration Mechanism

Redis allows setting an expiration time for a key, e.g., using the setex command:

setex key_n 50 value_n  # key expires after 50 seconds

Redis uses a TTL (Time To Live) strategy based on creation time: once an expiration time is set, the key is removed after the time elapses regardless of access. For scenarios requiring idle‑time expiration (TTI), developers can emulate it with expire commands to refresh the timeout.

Example of token renewal using expire:

After a user logs in, generate a token with a 30‑minute TTL.

On each authenticated request, execute expire to reset the TTL to 30 minutes.

If no request is received for 30 minutes, the token expires.

image
image

2. Redis Expiration Deletion Strategies

Redis combines periodic deletion and lazy deletion.

2.1 Periodic Deletion

A background task runs by default 10 times per second (configurable via hz) and samples a random set of keys, deleting those that are expired. If more than 25 % of sampled keys are expired, the process repeats. The scan time is limited to 25 ms to avoid blocking.

image
image

2.2 Lazy Deletion

When a key is accessed, Redis checks its expiration; if expired, the key is deleted and an empty response is returned. This is CPU‑friendly but may leave many expired keys in memory if they are never accessed.

The source file src/db.c implements this logic in the expireIfNeeded function (excerpt shown).

int expireIfNeeded(redisDb *db, robj *key, int force_delete_expired) {
    // Return 0 for non‑expired keys
    if (!keyIsExpired(db,key)) return 0;
    // ... additional logic for slaves, client pause, etc.
    deleteExpiredKeyAndPropagate(db,key);
    return 1;
}

3. Impact of Expired Keys on Persistence

RDB : Expired keys are omitted from the snapshot file; during loading, the master skips them, while replicas may receive them and later delete them via synchronization.

AOF : Until a key is removed, it does not affect the AOF file. When deletion occurs, a DEL command is appended. During AOF rewrite, expired keys are not written.

Replication : The master sends DEL commands for expired keys to replicas. Replicas keep expired keys until they receive the deletion command.

4. Redis Memory Eviction Policies

When memory exceeds the configured limit ( maxmemory <bytes>), Redis evicts keys according to the selected policy:

noeviction : No eviction; writes return OOM error.

volatile‑lru : LRU eviction of keys with an expiration time.

allkeys‑lru : LRU eviction of any key.

volatile‑lfu : LFU eviction of keys with an expiration time.

allkeys‑lfu : LFU eviction of any key.

volatile‑random : Random eviction of keys with an expiration time.

allkeys‑random : Random eviction of any key.

volatile‑ttl : Evicts keys with the nearest expiration time first.

5. LRU and LFU Algorithms Explained

LRU (Least Recently Used) approximates true LRU by sampling a subset of keys and evicting the least recently accessed ones.

LFU (Least Frequently Used) tracks access frequency with a counter that decays over time; keys with lower frequency are evicted first.

By properly configuring expiration times and choosing an appropriate memory eviction policy, developers can manage Redis data efficiently, improving system performance and stability.

RedisTTLLRUdatabasesLFUExpirationmemory eviction
Architecture & Thinking
Written by

Architecture & Thinking

🍭 Frontline tech director and chief architect at top-tier companies 🥝 Years of deep experience in internet, e‑commerce, social, and finance sectors 🌾 Committed to publishing high‑quality articles covering core technologies of leading internet firms, application architecture, and AI breakthroughs.

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.