Redis Memory Management and Eviction Policies

Understand Redis memory usage, configure a memory limit, and choose an eviction policy.

🎯 Introduction

By the end of this article, you will be able to set a memory limit for a cache instance, choose an eviction policy, and inspect memory usage from Node.js.


⚡ Why Redis Is Fast

Redis primarily accesses data in memory. Common commands operate directly on structures designed for their tasks, reducing general-purpose query processing overhead.

Common commands mainly execute sequentially on the main thread; background tasks and some network processing can use other threads or processes. Fast does not mean every operation is cheap: scanning large collections, transferring large values, and running long scripts can still slow other requests.


🧱 Memory Usage and maxmemory

maxmemory sets the memory limit Redis uses to manage data. When usage exceeds it, Redis frees space according to its eviction policy or rejects writes that need more memory. It is not an absolute operating-system limit on the entire process: leave headroom for replication buffers and other overhead.

Use cases: allocate a fixed cache memory budget so growing data does not crowd out other services on the same machine.

Using Redis 7.4.2, start a separate instance with a 128 MB limit and a cache eviction policy:

docker run -d --name redis-memory \
    -p 127.0.0.1:6381:6379 \
    redis:7.4.2 redis-server --save "" --appendonly no \
    --maxmemory 128mb --maxmemory-policy allkeys-lru

Port 6381 avoids the introductory instance's port. The next section explains allkeys-lru. The 128 MB limit is for practice; production capacity should follow data volume and load testing.


🧰 LRU, LFU, and Other Eviction Policies

Eviction removes existing data according to a policy when memory reaches its limit. LRU favors removing data not accessed recently; LFU favors removing infrequently accessed data. Redis uses approximate statistics rather than precisely comparing every key.

Use cases: a rebuildable cache with limited capacity should retain frequently accessed data where possible. The policy also determines which keys are eligible:

PolicyBehaviorWhen to consider it
allkeys-lruApproximately evict least recently used keys from all keysCaches whose hot data changes over time
allkeys-lfuApproximately evict least frequently used keys from all keysRetaining hot data based on sustained access frequency
volatile-lruApply LRU only to keys with expirationInstances that explicitly need a restricted candidate set
noevictionDo not evict; reject writes requiring allocation when memory is insufficientState that must not be arbitrarily removed, with write failures handled by the application

LFU frequency statistics decay over time, so old hot data does not remain solely because of historical traffic. Volatile policies may also reject writes when no expiring keys are eligible for eviction.

Sessions, rate-limit counters, and rebuildable caches have different costs of data loss. Prefer separate instances or explicit capacity policies rather than applying one cache eviction policy to all data. See Redis eviction policies.

Eviction differs from expiration in its trigger: memory pressure can evict a key before it expires.


💡 Inspect Redis Memory from Node.js

This section uses Node.js 22.9.0 and redis 5.9.0. Add the following blocks to memory.mjs in order and connect to the separate instance started above:

memory.mjs
import { redis } from './redis.mjs';

await redis.connect();
const info = await redis.info('memory');

INFO returns line-separated text. Extract only the relevant fields:

memory.mjs
const fields = ['used_memory_human:', 'used_memory_rss_human:', 'maxmemory_human:', 'maxmemory_policy:'];
console.log(info.split('\r\n').filter(line => fields.some(field => line.startsWith(field))).join('\n'));

maxmemory_human should be close to 128 MB, and the policy should be allkeys-lru. used_memory is memory allocated by Redis; used_memory_rss is resident memory reported by the operating system. A difference alone does not prove a leak.

Inspect the cumulative eviction count:

memory.mjs
const stats = await redis.info('stats');
console.log(stats.split('\r\n').find(line => line.startsWith('evicted_keys:')));
await redis.close();

An empty practice instance usually reports evicted_keys:0. Compare changes over an interval rather than looking only at the cumulative total.

REDIS_URL=redis://127.0.0.1:6381 node memory.mjs

❓ Questions and Answers

Q1: Do all commands fail after reaching maxmemory?

No. Reads and operations that free space can still execute. Whether writes needing more memory are rejected depends on the policy and eligible data.

Q2: Is LFU always better than LRU?

No. Observe hit rates and eviction counts under real access patterns. How quickly hot data changes affects the choice.

Q3: Can adding memory alone solve performance issues?

No. Large value transfers, slow commands, and poor connection management can still cause latency. Use the metrics in the troubleshooting article to investigate.


🧪 Exercise

Inspect allocated and resident memory on the same instance and record what each means. Explain why login sessions should not share the same policy as freely evictable cache entries.

// Write your code here
// Print the INFO fields you need to inspect

🎉 You now know how to choose Redis memory limits and eviction policies!