Skip to content
LRU Eviction — Memory Management
step 1/3

Reading — step 1 of 3

Memory Management

~1 min readAdvanced Features

LRU Eviction — Memory Management

Redis lives in RAM, and RAM is finite. What happens when you run out? Redis uses eviction policies to automatically remove keys.

Eviction Policies

PolicyDescription
noevictionReturn errors when memory limit is reached
allkeys-lruEvict least recently used key (most common)
allkeys-lfuEvict least frequently used key
volatile-lruOnly evict keys with TTL set
allkeys-randomEvict random keys

LRU — Least Recently Used

The idea: keys that haven't been accessed recently are less likely to be needed. When memory is full, evict the stalest key.

Real Redis doesn't use a true LRU (too expensive — requires a linked list of all keys). Instead, it uses approximated LRU: sample 5 random keys and evict the one with the oldest access time. This is O(1) and surprisingly accurate.

What You'll Build

  • MAXKEYS <n> — set the key limit
  • Track last-access time for every key
  • When at capacity, evict the LRU key before adding new ones
  • INFO memory — report current state

This is the same concept used in CPU caches, page replacement (OS), and CDN caches. Understanding LRU here transfers to every layer of the stack.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

LRU Eviction — Memory Management — Build Redis from Scratch