An in-memory store that runs out of RAM either evicts data or fails writes; you must choose which.
maxmemory sets the memory limit (for example 4gb). When it is reached, maxmemory-policy decides what happens on a write:
noeviction(default): writes that need memory fail with an OOM error, reads still work; right for data you can't lose,allkeys-lru/allkeys-lfu: evict the least recently / least frequently used keys anywhere; right for caches,volatile-lru,volatile-lfu,volatile-ttl,volatile-random: only evict keys that have an expiry, so you can mix permanent and cache keys,allkeys-random.
LRU and LFU are approximated by sampling (maxmemory-samples, default 5) rather than tracking exact order, which is cheap and close enough. LFU suits workloads where a few keys are always hot.
Leave headroom below physical RAM for fragmentation, client buffers, replication buffers and forks.
Finding memory hogs:
INFO memoryshowsused_memory,used_memory_rssandmem_fragmentation_ratio,MEMORY USAGE keyreports bytes for one key,MEMORY DOCTORgives advice,redis-cli --bigkeysand--memkeyssample the keyspace for the largest keys.
Keep values small, prefer hashes for many small fields, set TTLs on cache keys, and avoid big keys (huge lists, sets, hashes) which also cause latency spikes when deleted or migrated.
Example
redis-cli CONFIG SET maxmemory 100mb # OK
redis-cli CONFIG SET maxmemory-policy allkeys-lfu # OK
redis-cli CONFIG GET maxmemory-policy
# 1) "maxmemory-policy" 2) "allkeys-lfu"
redis-cli SET big "$(head -c 100000 /dev/zero | tr '\0' x)" # OK
redis-cli MEMORY USAGE big # (integer) 114736 (bytes incl. allocator overhead)
redis-cli INFO memory | grep -E '^(used_memory_human|maxmemory_human|mem_fragmentation_ratio)'
# used_memory_human:2.42M (varies)
# maxmemory_human:100.00M
# mem_fragmentation_ratio:1.20 (varies)
redis-cli --bigkeys # scans and reports the biggest keysRemember
- maxmemory + maxmemory-policy decide what happens when RAM is full
- noeviction (default) fails writes; allkeys-lru/lfu suits caches
- volatile-* policies evict only keys with a TTL
- Use INFO memory, MEMORY USAGE and --bigkeys to find hogs
Watch out for
- Running a cache with the default noeviction policy and getting OOM errors on writes once it fills.