Video in progress
In `INFO memory`, `used_memory` shows 6 GB and `used_memory_rss` shows 11 GB. Where does the difference come from, and what do you do?
This is memory fragmentation: Redis uses 6 GB for data, but the allocator (jemalloc) hasn't returned the 11 GB it took from the OS. mem_fragmentation_ratio is about 1.8. The fixes are activedefrag, MEMORY PURGE, and as a last resort a failover to a replica and a restart.
📖 Answer
used_memory is the memory Redis asked the allocator for to hold its data. used_memory_rss is the memory the OS sees as actually assigned to the process. The ratio:
mem_fragmentation_ratio = used_memory_rss / used_memory # about 1.83 here
When does this happen: lots of keys were created and deleted, values changed to different sizes (for example, session JSON that grows and shrinks). The freed space stays scattered inside pages and the allocator can't return it to the OS. Or a big import ran at night, used_memory_peak went up to 11 GB, and then the data was deleted.
What I do:
redis-cli MEMORY DOCTOR # Redis diagnoses itself
redis-cli INFO memory | grep -E 'frag|peak|allocator'
If allocator_frag_ratio is high, it's real fragmentation. I turn on active defrag (in Redis built with jemalloc, which is usually the case on Linux):
activedefrag yes
active-defrag-ignore-bytes 100mb
active-defrag-threshold-lower 10 # starts when it's above 10%
active-defrag-cycle-max 25 # at most 25% of CPU
In the background it moves keys to new locations and frees pages. It eats CPU, so don't push cycle-max too high.
MEMORY PURGE asks jemalloc to return unused pages to the OS. It's fast, but it doesn't remove fragmentation completely.
If neither helps, promote a replica to be the new master and restart the old one. A clean process packs memory densely.
There's a reverse case too: if the ratio is below 1, part of the memory is in swap. That's much worse than fragmentation and ruins latency right away.
Sign up to mark studied questions and save your progress.