ML
Redis

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.

November 27, 202611 min readRedisCachingPerformanceMemory ManagementSystem Design

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.

SharePostLinkedIn

Reader Discussion

9 replies// weighed in

TopNewestAuthor
Add to the thread
Disagree, agree harder, or share your own experience…
Email instead →markdown okbe kind
  1. Highlighted by author
    Elena Ricci· Platform Eng · Booking infraFrom experience

    XFetch quietly killed our daily cache stampede. 6h TTL on a product catalog, three-instance API, used to brown-out for 90 seconds every refresh. Shipped XFetch on a Friday afternoon and forgot it existed. That's the highest praise I can give a fix.

    Nov 29, 2026·2 days later
  2. Sơn Nguyễn🇻🇳 Hà Nội· Senior BackendStory

    +1 cho UNLINK. FLUSHDB SYNC làm prod đứng 39s, alert pager kêu vang nhà — sau đó mình đổi qua UNLINK + SCAN chunked, không bao giờ thấy spike lại. Mọi dev junior team mình bắt buộc đọc cái incident này.

    Dec 02, 2026·5 days later
  3. Luca Bianchi· Tech LeadPushback

    fwiw — hash tags bị overuse là footgun thật. Cluster bọn mình từng có 1 slot ăn 41% traffic vì ai đó nghĩ {tenant} làm key prefix là idea hay. Cluster slowlog từ 12ms lên 800ms trong 1 đêm. Cluster rebalance không cứu được vì cùng 1 slot.

    Dec 03, 2026·6 days later·edited
  4. Huyền Lê· Software EngineerAgrees

    viết postmortem tiêu đề 'WAIT did not wait' xong 1 tuần sau gặp đoạn này trong post. cười ra nước mắt. cái phần WAIT không phải consensus primitive cần tô đỏ trong docs official.

    Nov 30, 2026·3 days later
  5. Amir Shah· InfraAsks

    Q: pre-warm hot keys — internal cron inside the app vs external scheduler (k8s cronjob etc)? We've shipped both. Internal is simpler but you fight clock skew across replicas; external is reliable but adds a moving piece.

    Dec 01, 2026·4 days later
    • ML
      Minh LeAuthor

      External, every time. The number of "why is the warmup not running" tickets I've seen with internal crons is not funny anymore. Make it boring infra.

      Dec 02, 2026
    • Carla Pérez· Backend

      we do external + a redis lock so only one instance actually runs the warmup. simple and observable.

      Dec 03, 2026
  6. Rachel Gold· Staff SREAgrees

    the on-call framing throughout this piece is what makes it land. too many infra articles assume you never get paged. those are written by people who never got paged.

    Nov 30, 2026·3 days later
  7. Omar Khalil· Senior SWEKind words

    this is the third article from this blog I've sent to my team this month. you're cooking. don't switch to crypto.

    Dec 02, 2026·5 days later

Worked on something similar? Email ducminhldm@gmail.com — I read every one. The good ones become future posts.

Comments seeded · live discussion via email