Learn Labs
Expiration & Memory

Eviction

maxmemory, every eviction policy, and approximate LRU and LFU

RAM runs out. maxmemory decides when Redis considers itself full, and maxmemory-policy decides what happens next: refuse writes, or delete something to make room. Getting this wrong either takes your app down or silently deletes data you needed.

maxmemory

CONFIG GET maxmemory          # 268435456 (256mb in this repo)
INFO memory | grep -E "used_memory_human|maxmemory_human|maxmemory_policy"

With maxmemory 0 (the default outside containers on 64-bit systems), Redis grows until the OS kills it or starts swapping. Always set it, leaving headroom for the overheads that maxmemory doesn't count: client output buffers, replication backlog, and copy-on-write during a fork. A common rule is 60-75% of the memory available to the process.

The policies

PolicyEvictsWhen there's nothing to evict
noevictionNothing. Writes that need memory fail.OOM command not allowed
allkeys-lruLeast recently used, any key—
allkeys-lfuLeast frequently used, any key—
allkeys-randomRandom, any key—
volatile-lruLeast recently used, only keys with a TTLOOM error
volatile-lfuLeast frequently used, only keys with a TTLOOM error
volatile-randomRandom, only keys with a TTLOOM error
volatile-ttlThe key closest to expiringOOM error

Reads and deletes always work, even at the limit; only commands that grow memory are refused.

Choosing

Pure cache (everything can be rebuilt from the database): allkeys-lfu or allkeys-lru. Redis keeps the hottest data, and "full" is a normal steady state, not an incident.

Data store (sessions you can't lose, queues, streams, leaderboards): noeviction. Better to fail a write loudly than to silently drop a user's session or a queued job. Alert well before the limit.

Mixed (this repo's lab instance): volatile-lfu. Cache keys have TTLs and can be evicted; keys without TTLs are kept. It works only if every cache key reliably has a TTL. Remember that a plain SET clears one.

What it looks like

Run against a throwaway instance with a 4 MB limit:

docker run -d --rm --name redis-evict redis:8.8.3 \
redis-server --maxmemory 4mb --maxmemory-policy noeviction

# write 3000 x 1KB values
... (error) OOM command not allowed when used memory > 'maxmemory'.
DBSIZE                                  # 2573: writes stopped at the limit

CONFIG SET maxmemory-policy allkeys-lru
# write 3000 more
DBSIZE                                  # 2497: still about the same size...
INFO stats | grep evicted_keys          # evicted_keys:3076 ...because old keys were evicted

Approximate LRU and LFU

Tracking exact LRU order for millions of keys would need a linked list updated on every access, which is too expensive. Instead, each value object stores a 24-bit clock:

  • LRU: the last access time.
  • LFU: an 8-bit logarithmic access counter plus a decay time. The counter grows probabilistically (it takes about a million hits to saturate it), and halves after periods of no access, so a key that was hot yesterday doesn't stay "frequent" forever.

To evict, Redis samples maxmemory-samples keys (5 by default), adds them to a small pool of eviction candidates, and evicts the best candidate. Sampling 10 is very close to true LRU at a little more CPU.

CONFIG GET maxmemory-samples5CONFIG GET lfu-log-factor10: how slowly the LFU counter growsCONFIG GET lfu-decay-time1: minutes per counter decay stepOBJECT FREQ app:product:1001LFU counter (requires an LFU policy)OBJECT IDLETIME app:product:1001seconds since last access (requires an LRU policy)

LFU vs LRU in practice. LRU is fooled by scans: one batch job that reads every key once makes them all "recent", flushing your real hot set. LFU resists that, because one access barely moves a key's counter. For caches with a stable hot set, LFU usually gives a better hit ratio.

Signals to watch

INFO stats
evicted_keys:3076           # rising = Redis is at its limit and deleting
keyspace_hits / keyspace_misses   # hit ratio: did eviction hurt the cache?

INFO memory
used_memory / maxmemory     # how close to the limit

The Prometheus stack alerts on these as RedisMemoryNearLimit and RedisEvictingKeys. For a pure cache, evictions are normal and the hit ratio is what matters. For a data store, any eviction is data loss.

Lab

  1. Start the throwaway container above and reproduce the OOM error.
  2. Switch to allkeys-lru and confirm DBSIZE stays flat while evicted_keys climbs.
  3. Switch to allkeys-lfu. Read 10 keys a hundred times each, write 3,000 new keys, and check whether those 10 survived (EXISTS).
  4. docker stop redis-evict when done.

On this page