Redis BigKeys and Memory Fragmentation: Why jemalloc Never Returned Memory to Linux
Deleting a 5-million-element Hash with DEL stalls the Redis event loop for seconds, while jemalloc memory fragmentation keeps OS RSS pinned at 90 percent. How UNLINK, stream slicing, and active defragmentation restore memory efficiency.
During a high-traffic flash sale, a mission-critical caching cluster running Redis 7 began experiencing severe latency spikes. Client connection timeouts climbed past 5 percent, p99 response times surged from 0.8 ms to 4,200 ms, and the Linux kernel Out-Of-Memory (OOM) killer unexpectedly terminated the primary Redis daemon. Curiously, Redis reported only 6.2 GB of key data in used_memory, but the host operating system showed the process RSS (Resident Set Size) exceeding 28 GB.
The post-mortem revealed a dual failure mode common in large-scale caching topologies: the presence of massive BigKeys blocking the single-threaded event loop, combined with extreme memory fragmentation inside the underlying memory allocator (jemalloc).
1. The Anatomy of a BigKey Bottleneck
Redis operates on a single-threaded event loop for command execution. While simple operations on Strings, small Hashes, or Sets run in O(1) time and complete in sub-microsecond intervals, operating on large collections scales linearly with the number of elements: O(N).
A classic anti-pattern is storing an unbounded collection (such as user session histories, audit logs, or tracking sets) inside a single Redis Hash or Set. When an application attempts to clean up or expire such a key using the standard DEL command:
# An innocent-looking command in application code:
DEL user_events:tenant_9821
If user_events:tenant_9821 contains 4 million entries, the single-threaded engine must traverse and free 4 million memory nodes synchronously. During this deallocation cycle, the event loop cannot read incoming socket buffers, process heartbeats, or answer cluster pings. Redis becomes completely deaf, causing client timeouts and triggering false sentinel failovers.
2. The jemalloc Fragmentation Trap
Even after large keys are removed, Redis memory usage reported by the operating system often remains abnormally high. This discrepancy is caused by memory fragmentation:
mem_fragmentation_ratio = used_memory_rss / used_memory
Redis delegates memory allocation to jemalloc. jemalloc allocates memory in fixed-size quantum bins (e.g., 8, 16, 32, 48, 64 bytes) grouped into 4 KB or 2 MB pages (arenas). When keys with varying sizes are continuously created, updated, and deleted, jemalloc frees individual slots within pages. However, the operating system can only reclaim memory at the physical page level (4 KB on Linux). If a 4 KB page contains just one active 32-byte object, the entire 4 KB page remains committed to process RSS.
When millions of small elements from an expired BigKey are deleted, jemalloc ends up with thousands of sparse, partially occupied pages. The memory is free from jemalloc's perspective for future Redis allocations, but it cannot be released back to the Linux kernel. If the host kernel faces system-wide memory pressure, it invokes the OOM killer against the Redis process because of its massive RSS footprint.
3. Scanning for BigKeys Without Stalling
Never run KEYS * or manual high-cardinality queries on a production node. Instead, utilize the non-blocking --bigkeys scan utility provided by the Redis CLI:
# Scan keyspace using incremental cursor-based iterations (SCAN):
redis-cli -h 127.0.0.1 -p 6379 --bigkeys
This command systematically scans each keyspace segment with a low batch size, outputting the largest keys found across each data type (String, List, Hash, Set, ZSet) without stalling the primary engine.
4. Remediation Strategies
A. Asynchronous Deletion with UNLINK
Starting in Redis 4.0, Redis introduced non-blocking memory reclamation. Replace all occurrences of DEL with UNLINK when dealing with unknown or potentially large data structures:
# Unlinks the key from keyspace immediately (O(1)), then frees memory in a background thread:
UNLINK user_events:tenant_9821
To automate this across all key evictions and TTL expirations, enable lazy freeing in redis.conf:
lazyfree-lazy-eviction yes
lazyfree-lazy-expire yes
lazyfree-lazy-server-del yes
replica-lazy-flush yes
B. Active Memory Defragmentation
Modern Redis releases bundle jemalloc active defragmentation. When enabled, Redis inspects sparse pages, allocates contiguous memory blocks for the remaining live objects, rewrites their pointers, and releases the fully evacuated pages back to Linux:
# Enable active defragmentation dynamically:
CONFIG SET activedefrag yes
# Configure sensible thresholds to prevent CPU spikes:
CONFIG SET active-defrag-ignore-bytes 100mb
CONFIG SET active-defrag-threshold-lower 10
CONFIG SET active-defrag-threshold-upper 30
CONFIG SET active-defrag-cycle-min 5
CONFIG SET active-defrag-cycle-max 25
C. Partitioning BigKeys into Sharded Buckets
Rather than placing 10 million items in a single Hash, shard the items deterministically across multiple sub-keys using a hash-modulo scheme:
// Compute deterministic shard bucket:
function getBucketKey(userId, fieldId) {
const shard = crc32(fieldId) % 100;
return 'user_events:' + userId + ':shard_' + shard;
}
// Write to the smaller bucket:
await redis.hset(getBucketKey(userId, eventId), eventId, payload);
Each shard holds fewer than 10,000 entries, keeping memory layouts uniform, preventing single-key locking, and ensuring seamless background deallocation.
Summary
Massive keys and memory fragmentation represent two sides of the same scalability coin in Redis. By replacing blocking DEL calls with UNLINK, enabling lazy-freeing defaults, turning on jemalloc active defragmentation, and architecting collections into bounded shards, engineering teams can maintain predictable sub-millisecond latencies under demanding workloads.