Your Redis process holds 13 GB of resident memory while INFO memory insists the dataset is 8 GB, and mem_fragmentation_ratio reads 1.69. The reflex is to set activedefrag yes and hope. That is right about a third of the time. The other two thirds, the gap is swap, copy-on-write pages from a background save, or client and replication buffers that were never fragmentation at all — and active defragmentation will burn main-thread CPU without moving the number. This guide separates the four causes using fields you already have, then covers the safe rollout of activedefrag with its tuning parameters, and the failover-and-restart path for the cases where defragmentation cannot win.
What you’ll accomplish
- Read
used_memory,used_memory_rss,allocator_frag_ratioandrss_overhead_ratioas four different measurements of four different layers, instead of trusting one blended ratio. - Rule out swapping, background-save copy-on-write, and buffer growth before touching allocator settings.
- Enable and tune
activedefragon a live instance without a latency incident, and know what the counters should do if it is working. - Recognise the point at which defragmentation has stopped paying and a failover plus restart is the cheaper fix.
- Stop a container from being OOM-killed by memory that
maxmemorywas never watching.
Prerequisites
- Redis 4.0 or newer for active defragmentation; the implementation matured through 5.x and 6.2 extended it to more object encodings. The tuning parameter names in this guide are the ones present in Redis 6 and 7.
- A jemalloc build with the defragmentation hint.
INFO memorymust reportmem_allocator:jemalloc-<version>. Redis’s own build links a patched jemalloc that exposes the hint API. Some distribution packages link the system jemalloc or plain libc instead, and on thoseCONFIG SET activedefrag yesis refused outright. Check before planning around it. - Shell access on the host, because two of the four causes are only visible from
/procand from the kernel’s own view of the process. - A replica or Sentinel setup if you want the restart path to be an option rather than an outage. If you do not have one, see Redis Sentinel for high availability before you need it at 3 a.m.
- Managed-service caveat. ElastiCache, Azure Cache for Redis and similar expose
activedefragas a parameter-group value at best, andMEMORY PURGEor host-level/procinspection not at all. Most of the diagnosis below still applies; some of the remedies do not.
How it works
Redis reports memory at four different layers, and each layer includes something the one below it cannot see.
The detail that surprises people: jemalloc size-class rounding is already inside used_memory. Redis asks the allocator for the usable size of every block it allocates, so a 100-byte value that lands in jemalloc’s 112-byte size class is counted as 112 bytes. That internal waste never appears as “fragmentation” in any ratio — it shows up as used_memory being larger than the arithmetic sum of your values, which is a data-modelling problem, not a defragmentation one.
What allocator_frag_ratio measures is different: free space stranded inside partly-used extents. A workload that writes and deletes objects of varying sizes leaves runs that are, say, 40% occupied. jemalloc cannot return those pages while a single live object sits in them. Active defragmentation exists precisely for this: it asks jemalloc whether a given pointer lives in a sparse run, and if so reallocates the object so the allocator can place it in a fuller run, eventually emptying the sparse one. That is the only cause on the list it addresses.
rss_overhead_ratio covers everything outside jemalloc’s accounting: the binary and stacks, memory not allocated through zmalloc, and — the big one — copy-on-write pages left over from a forked child during BGSAVE or an AOF rewrite.
And mem_fragmentation_ratio, the field everyone quotes, is simply used_memory_rss / used_memory. It is the product of all three effects. It is a fine smoke alarm and a useless diagnosis.
Step-by-step
-
Take one snapshot, not four. Every field below must come from the same
INFOcall or the ratios will not reconcile.redis-cli INFO memory > /tmp/redis-mem.txtPull out the fields that matter:
used_memory:8589934592 used_memory_rss:14495514624 used_memory_overhead:268435456 used_memory_dataset:8321499136 allocator_allocated:8598323200 allocator_active:12884901888 allocator_resident:13421772800 allocator_frag_ratio:1.50 allocator_rss_ratio:1.04 rss_overhead_ratio:1.08 mem_fragmentation_ratio:1.69 mem_allocator:jemalloc-5.3.0Read it as a chain: 8.0 GB live, 12.0 GB of active extents (real fragmentation), 12.5 GB resident, 13.5 GB RSS. The 1.69 headline is 1.50 of genuine fragmentation multiplied by a little allocator retention and a little process overhead.
-
Rule out swap first, because a ratio below 1.0 is not fragmentation. If
mem_fragmentation_ratiois under 1.0, RSS is smaller than the heap Redis thinks it owns, which means the kernel has paged part of it out. Latency will already be terrible.pid=$(redis-cli INFO server | awk -F: '/^process_id/{print $2}' | tr -d '\r') grep VmSwap /proc/"$pid"/statusVmSwap: 0 kBAnything other than
0 kBon a Redis host is a problem to fix at the memory-sizing level. Enabling defragmentation here makes it worse: it touches cold pages, which forces them back in. -
Use the decision tree rather than the headline number. With the snapshot in hand, the branch is mechanical.
-
Confirm no fork is in flight before you believe the RSS number. A
BGSAVEor AOF rewrite can double apparent RSS for the duration of the child.redis-cli INFO persistence | grep -E 'rdb_bgsave_in_progress|aof_rewrite_in_progress|rdb_last_cow_size'If either
in_progressfield is1, your snapshot is contaminated — re-measure when it is0.rdb_last_cow_sizetells you how much the previous fork actually cost; if that is a large fraction of the dataset, transparent huge pages are usually the reason, because copy-on-write then duplicates 2 MB at a time instead of 4 KB.cat /sys/kernel/mm/transparent_hugepage/enabledalways [madvise] neverRedis logs a startup warning when this reads
[always]. Set it toneverand the fork cost usually drops sharply. That is a copy-on-write fix, not a defragmentation one. -
Check whether the “fragmentation” is really buffers. Client output buffers, the replication backlog and the AOF buffer inflate
used_memory, which lowers the ratio while total memory climbs — so a healthy-looking 1.1 can hide a runaway replica buffer.redis-cli INFO memory | grep -E 'mem_clients_normal|mem_clients_slaves|mem_replication_backlog|mem_aof_buffer'Compare
used_memory_overheadagainstused_memory. If overhead is a double-digit percentage, chase the buffer, not the allocator.MEMORY DOCTORwill often name it for you in one line. -
Enable active defragmentation conservatively. Only proceed if
allocator_frag_ratiois above roughly 1.4 andallocator_frag_bytesis worth reclaiming. Start with the defaults, which are deliberately timid.redis-cli CONFIG SET active-defrag-ignore-bytes 100mb redis-cli CONFIG SET active-defrag-threshold-lower 10 redis-cli CONFIG SET active-defrag-threshold-upper 100 redis-cli CONFIG SET active-defrag-cycle-min 1 redis-cli CONFIG SET active-defrag-cycle-max 25 redis-cli CONFIG SET activedefrag yesEach call returns
OK.active-defrag-ignore-bytesis the floor below which Redis will not bother; the twothresholdvalues map the fragmentation percentage onto an effort curve, andcycle-minandcycle-maxcap that effort as a percentage of main-thread CPU. On a latency-sensitive instance, loweractive-defrag-cycle-maxto 10 or 15 before you enable anything. -
Watch the first ten minutes. Defragmentation runs on the main thread, so it competes directly with command execution.
redis-cli --latency-history -i 5The output prints a rolling
min / max / avgin milliseconds. Ifavgclimbs materially and stays there, dropactive-defrag-cycle-maxor turn it off; a slow reclaim is better than a latency regression. -
Persist the settings once you are satisfied.
CONFIG SETis runtime only.redis-cli CONFIG REWRITEThis returns
OKonly if the server was started with a config file; otherwise it errors and you must editredis.confyourself. -
If defragmentation stalls, fail over and restart. A restarted process rebuilds its heap from a compact load and starts at a ratio near 1.0. With Sentinel, promote a replica first so the client-visible outage is a reconnect rather than a downtime window.
redis-cli -p 26379 SENTINEL FAILOVER mymasterConfirm the roles have swapped with
redis-cli INFO replicationon both nodes before restarting the old primary. It will come back as a replica, resync, and hold a clean heap.
Validate it works
Sample the counters twice, ten minutes apart, and compare:
redis-cli INFO stats | grep -E 'active_defrag_(hits|misses|key_hits|key_misses)'
redis-cli INFO memory | grep -E 'allocator_frag_ratio|allocator_frag_bytes|used_memory_rss|active_defrag_running'
Defragmentation is working when active_defrag_hits is climbing, allocator_frag_bytes is falling, and used_memory_rss follows it down within a few minutes. active_defrag_running is 0 when idle and non-zero while a cycle is in flight.
If allocator_frag_ratio has dropped but RSS has not, jemalloc is holding the freed pages rather than returning them. Push them back:
redis-cli MEMORY PURGE
It returns OK and only does anything under jemalloc. allocator_rss_ratio should fall afterwards. If RSS still does not move, the remaining gap is rss_overhead_ratio territory — buffers or copy-on-write, not the allocator.
Redis’s official guidance on the memory model and these fields is at redis.io.
Troubleshooting
CONFIG SET activedefrag yes is rejected. The error names the allocator: active defragmentation needs a jemalloc build that exposes the defragmentation hint, which is what Redis ships in its own source tree. Distribution packages linked against the system jemalloc or against libc cannot do it. Confirm with redis-cli INFO memory | grep mem_allocator; if it says libc, your only levers are restart, data-model changes, and buffer control.
active_defrag_misses vastly exceeds active_defrag_hits. Redis is scanning objects and finding almost none worth moving. That means the fragmentation is not the kind defragmentation fixes — often a few very large allocations, or a heap that is genuinely mostly live. Turn it off; you are paying CPU for nothing.
Defragmentation never finishes and CPU sits high. A write-heavy instance can create fragmentation as fast as it is reclaimed. Look at active-defrag-threshold-upper: if actual fragmentation is above it, Redis runs at cycle-max effort permanently. Either accept a higher steady-state ratio by raising active-defrag-ignore-bytes, or plan a restart.
The container is OOM-killed even though used_memory is below maxmemory. maxmemory is evaluated against used_memory, not RSS. Every byte of fragmentation, buffer and copy-on-write sits outside that budget, and the cgroup limit counts all of it. Set maxmemory to a fraction of the container limit — leaving room for a fork if you run RDB snapshots — and read how the Linux OOM killer chooses a victim so the kill message is not a surprise.
Fragmentation returns within days of a restart. That is usually eviction churn: a working set sitting right at maxmemory under allkeys-lru constantly evicts and reinserts objects of different sizes, which is the exact recipe for stranded extents. More headroom fixes it more reliably than defragmentation does.
When this is the wrong approach
A ratio between 1.0 and 1.5 is what a healthy jemalloc instance looks like. Chasing it wastes CPU and risks a latency regression for a number nobody sees. Below 1.0, the problem is swap and defragmentation actively harms.
If the instance is small enough that a restart costs seconds, restart it. Active defragmentation is a tool for instances too large or too hot to bounce casually, not a general hygiene setting to switch on everywhere.
If used_memory itself is what surprised you — not the gap between it and RSS — the answer is in the data model, not the allocator. Millions of tiny keys carry per-key overhead that dwarfs the values; consolidating them into hashes that stay within the listpack encoding thresholds routinely cuts memory by more than any defragmentation pass will. Measure with MEMORY USAGE on a representative key before assuming.
And if the RSS gap only appears during backups, you have a fork sizing problem. Disable transparent huge pages, provision headroom for the child, or move snapshotting to a replica.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.