Memory Optimization
Big keys, hot keys, fragmentation, and reading INFO memory
Memory is Redis's scarcest resource and its most common source of incidents. This lesson covers reading where it goes, and the three problems you'll meet in production: big keys, hot keys, and fragmentation.
Reading INFO memory
MEMORY STATS breaks overhead down further, and MEMORY DOCTOR gives
a human-readable diagnosis.
Fragmentation
mem_fragmentation_ratio = RSS ÷ used memory.
| Ratio | Meaning |
|---|---|
| < 1.0 | The OS has swapped part of Redis to disk. Latency emergency. |
| 1.0 - 1.5 | Healthy |
| > 1.5 on a large dataset | Fragmentation: freed memory jemalloc can't return to the OS |
| Very high on a tiny dataset | Normal. A 2 MB dataset in a process with fixed allocator overhead. |
Fragmentation builds up when values of varying sizes are created and deleted, leaving holes. Redis can defragment live:
CONFIG SET activedefrag yes
CONFIG GET active-defrag-* # thresholds and CPU limits for the defrag cycle
INFO memory | grep allocator_fragA high fragmentation ratio on a near-empty instance (like this lab's
after startup) is not a problem. The ratio only means something when
used_memory is large. Many alerts fire on the ratio alone and
page people for a 2 MB Redis.
Big keys
A big key is a single key holding a huge value, such as a 100 MB string or a hash with 5 million fields. They cause:
- Latency spikes: any O(N) command on it (
HGETALL,DEL,SMEMBERS) blocks everyone. - Uneven memory in a cluster: one slot, one node, much bigger.
- Slow replication and failover: the whole value is transferred at once.
- Network saturation: reading it repeatedly fills the NIC.
Find them without blocking the server (both use SCAN):
redis-cli --user default --pass redis123 --bigkeys # largest key per type, by element count
redis-cli --user default --pass redis123 --memkeys # largest keys by memory
MEMORY USAGE app:feed:recent_orders SAMPLES 0 # exact size of one key (samples all elements)Fixes: split the key (user:42:events:2026-10 per month instead of one
forever-growing list), cap it (LTRIM, XTRIM), or move it out of
Redis. Delete big keys with UNLINK, not DEL, so the memory is
freed in the background.
Hot keys
A hot key is read or written far more than others, for example a global feature flag read on every request, or a celebrity's profile. It isn't a memory problem but a throughput one: one key lives on one thread (and in a cluster, on one node), so it caps out no matter how many nodes you add.
redis-cli --user default --pass redis123 --hotkeys # requires an LFU eviction policy (this repo uses volatile-lfu)Fixes, from simplest:
- Client-side caching: cache the value in app memory for a few
seconds. Redis 6+ supports tracking (
CLIENT TRACKING) so the server tells clients when a cached key changes. - Replicate the key: write copies to
flag:x:1…flag:x:8and read a random one, spreading load across cluster slots. - Read from replicas for data that tolerates slight staleness.
Reducing memory
In rough order of impact:
- Set TTLs on everything that's a cache, and check
INFO keyspaceforexpires=. - Remove data that shouldn't be there:
--memkeysoften finds one forgotten debug key or unbounded list holding half the memory. - Use compact encodings: small hashes instead of many keys, integer IDs in sets (Encodings).
- Compress large values client-side.
- Use probabilistic structures where exact answers aren't needed (HyperLogLog instead of a set of IDs).
- Shorten key names, only at very large key counts.
Swap and Transparent Huge Pages
Two Linux settings matter on real servers:
- Swap: if any of Redis is swapped out, accessing it takes
milliseconds instead of nanoseconds, and the single thread stalls.
Set
vm.swappinesslow and make sure the host has enough RAM. - Transparent Huge Pages (THP) make copy-on-write after
fork()copy 2 MB pages instead of 4 KB ones, causing latency spikes and memory blowups during saves. Redis logs a warning at startup if THP is enabled. Disable it on Redis hosts. vm.overcommit_memory = 1letsfork()succeed for background saves even when the host doesn't have enough free memory for a full copy. Redis warns at startup if it isn't set.
docker logs redis 2>&1 | grep -i warning # look for overcommit and THP warningsLab
- Read
INFO memoryandMEMORY DOCTOR. - Create a big key:
for i in $(seq 1 200000); do echo "RPUSH app:big $i"; done | docker exec -i redis redis-cli --user app --pass app123 >/dev/null. - Find it with
--bigkeysand--memkeys. CheckMEMORY USAGE app:big. - Time
LRANGE app:big 0 -1withredis-cli --latencyrunning in another terminal. Watch latency spike. - Delete it with
UNLINK app:big.