Redis Object Cache Memory Eviction

Printed circuit board pathways under studio lighting
Printed circuit board pathways under studio lighting (Photo via Unsplash)

At 14:22 on a Tuesday afternoon, our main editorial CMS slowed to a crawl. Median time to first byte jumped from 94 milliseconds to 4.1 seconds across four PHP-FPM application nodes. MariaDB primary CPU pinned itself at 89%, active threads climbed past 140, and editors couldn't save a draft without hitting a gateway timeout. Meanwhile, our dedicated Redis 7.2 node on Debian 12 sat practically idle at 5% CPU and 18 Mbps of traffic.

That mismatch sends most teams down the wrong path. Slack immediately blamed a morning plugin release or exhausted PHP-FPM workers. We ruled out kernel backlog drops fast—we'd already raised listen queue ceilings during our earlier systemd socket tuning for high load work. PHP process pools weren't starving either; per-pool memory boundaries had held steady since our OpenLiteSpeed vs Nginx PHP isolation audit. PHP wasn't waiting on sockets. It was hammering MariaDB because our object cache had quietly stopped accepting writes.

How noeviction Turns an Object Cache Into a Database Hammer

The PHP-FPM error log gave us the answer in ten seconds. Thousands of lines per minute repeated the exact same warning from phpredis:

PHP Warning: Redis::setEx(): OOM command not allowed when used memory > 'maxmemory' in /var/www/cms/wp-content/object-cache.php on line 842

Nobody saw HTTP 500s, which made the slowdown harder to spot early. Most CMS object cache drop-ins wrap writes in a try/catch block and swallow exceptions so a brief cache blip doesn't take the site down. That defensive pattern turns nasty when Redis hits its configured maxmemory ceiling under the default noeviction policy.

When we provisioned that cache box six months earlier, we had explicitly set maxmemory 4gb on an 8 GB VM so the daemon couldn't starve the OS—a habit left over from fixing the Linux OOM killer on web nodes. What slipped through our Ansible role was maxmemory-policy. Debian's stock redis.conf leaves it commented out, defaulting to noeviction.

Once memory crossed 4.00 GB, Redis kept serving GET requests for older keys already in RAM while rejecting every SET, SETEX, and HSET. Newly published stories, updated taxonomy queries, and refreshed navigation blocks failed to cache. Worse, every miss paid three costs in a row: a Redis lookup, a full MariaDB query, and a failed Redis write. Our hit ratio collapsed from 96.4% to 38.7% in eighteen minutes. MariaDB wasn't broken; it was absorbing ten times its normal read load.

An object cache running noeviction isn't a cache. It's a slow-motion thundering herd waiting for your working set to grow by one megabyte.

Reading INFO memory and Catching jemalloc Fragmentation

Before flipping the eviction policy, I wanted to know how 180,000 published articles had filled 4 GB of RAM when the entire MariaDB dataset on disk was only 6.8 GB. Running redis-cli INFO memory exposed two problems at once:

# Memory
used_memory_human:4.00G
used_memory_rss_human:5.57G
used_memory_peak_human:4.00G
maxmemory_human:4.00G
maxmemory_policy:noeviction
mem_fragmentation_ratio:1.39
allocator_frag_ratio:1.34
allocator_frag_bytes:1418912256
mem_allocator:jemalloc-5.3.0

Look at mem_fragmentation_ratio:1.39 and used_memory_rss_human:5.57G. Redis tracked 4.00 GB of allocated data, yet the kernel had committed 5.57 GB of resident pages to redis-server. Nearly 1.6 GB of physical RAM sat stranded in partially empty jemalloc slabs.

That fragmentation ratio tells three distinct operational stories:

  • 1.00 to 1.15: Normal jemalloc overhead. Leave it alone.
  • Below 1.00: The kernel is swapping Redis pages to disk. Expect ugly tail latency spikes; shrink maxmemory or add RAM immediately.
  • Above 1.30 on multi-gigabyte nodes: Churn across wildly different key sizes is punching holes in jemalloc arenas that the OS can't reclaim.

CMS object caches fragment allocators reliably. Tiny 90-byte post-meta flags sit right beside multi-megabyte serialized option blobs rewritten every time an editor updates a widget. Turning on activedefrag yes lets jemalloc compact sparse pages online without a restart, provided you bound its CPU share so defrag cycles don't fight traffic bursts.

Hunting Keyspace Bloat With redis-cli --bigkeys

Fragmentation explained the extra 1.57 GB of RSS, not why used_memory itself had hit 4.00 GB. I ran redis-cli -i 0.05 --bigkeys to inspect the keyspace. Always pass -i 0.05 on a live node—that 50-millisecond sleep between SCAN calls keeps the single-threaded event loop responsive while walking millions of keys.

[00.00%] Biggest string found so far 'wp:posts:148291' with 14218 bytes
[04.12%] Biggest string found so far 'wp:options:alloptions' with 1894420 bytes
[31.88%] Biggest hash   found so far 'wp:term_relationships:cache_map' with 4120 fields
[78.40%] Biggest string found so far 'wp:transient:sitemap_index_v4' with 2310944 bytes

Sampled 2248190 keys in the keyspace!
2241012 strings with 3812401920 bytes (99.68% of keys, avg size 1701.19)
   7178 hashes  with 184210 fields (00.32% of keys, avg size 25.66)

Two problems jumped off the screen. First, spot-checking twenty random wp:post_meta:* keys with TTL returned -1—no expiration. Four months of bot crawls across ancient archive pages had parked 2.24 million permanent strings in RAM. Second, wp:options:alloptions weighed 1.89 MB. Because the CMS fetches alloptions on every uncached PHP worker bootstrap, each worker dragged nearly two megabytes over the private VLAN just to boot.

Keep one limit of --bigkeys in mind: it highlights the single largest key per type and overall averages, not aggregate memory per prefix. Pair it with MEMORY USAGE key on suspect groups—or inspect an offline RDB dump on staging—when averages look harmless.

Why allkeys-lfu Beats LRU and volatile Policies

Picking properly among Redis cache eviction policies isn't academic on a busy CMS. The common trap is volatile-lru or volatile-lfu, which only evict keys with an explicit TTL. Most CMS object caches write options, user meta, and post metadata with no expiration because the application invalidates them on save. Once Redis evicts the few keys carrying TTLs, any volatile-* policy runs out of candidates and reverts to returning OOM write errors—just like noeviction.

That narrows it to allkeys-lru versus allkeys-lfu. Pure LRU works until an aggressive scraper sweeps 60,000 archive posts from 2017 in ten minutes. Under recency-only eviction, one-hit archive keys look newer than a hot homepage menu untouched for four seconds, evicting high-value objects.

allkeys-lfu fixes that with a logarithmic Morris counter tucked inside each key's header. One-off crawler entries stay at a low frequency score and get evicted first, while hot menus, options, and breaking-news queries keep climbing in frequency and remain pinned in RAM. That matches enterprise CMS performance benchmarks on CMS Connection, where LFU holds p99 latency steady during bot storms that make LRU caches thrash.

We applied the change live and wrote it back to /etc/redis/redis.conf:

CONFIG SET maxmemory-policy allkeys-lfu
CONFIG SET lfu-log-factor 10
CONFIG SET lfu-decay-time 1
CONFIG SET activedefrag yes
CONFIG SET active-defrag-ignore-bytes 100mb
CONFIG SET active-defrag-threshold-lower 15
CONFIG SET active-defrag-cycle-min 2
CONFIG SET active-defrag-cycle-max 15
CONFIG REWRITE

Within ninety seconds, the PHP OOM warnings stopped, MariaDB CPU fell from 89% to 14%, and median TTFB returned to 105 milliseconds. Forty minutes later, background defragmentation had pulled mem_fragmentation_ratio from 1.39 down to 1.11.

Cutting Cache Footprint Nearly in Half With igbinary

Fixing eviction restored stability, yet burning 4 GB for 2.2 million keys still looked sloppy. Native PHP serialize() emits verbose ASCII full of repeated field names like post_author, post_status, and comment_count. Across millions of cached post objects, you pay RAM for the same strings over and over.

Switching phpredis to igbinary stores a compact binary tree that deduplicates repeated strings per payload, and igbinary_unserialize() actually runs faster than native PHP unserialize() on nested arrays. Pairing igbinary with Zstandard compression (COMPRESSION_ZSTD) shrinks oversized blobs like alloptions and sitemap transients before they leave PHP:

define( 'WP_REDIS_CLIENT', 'phpredis' );
define( 'WP_REDIS_IGBINARY', true );
define( 'WP_REDIS_COMPRESSION', 'zstd' );
define( 'WP_REDIS_PREFIX', 'cms_v2_' );

Don't forget that prefix bump or a clean FLUSHDB ASYNC during cutover. If workers running Redis::SERIALIZER_IGBINARY read leftover keys serialized with plain PHP, phpredis fails to decode them cleanly and throws noisy warnings until old keys expire. Bumping the prefix gives workers a clean binary namespace while LFU evicts the orphaned cms_v1_ entries.

After 24 hours of normal production traffic, the numbers spoke for themselves:

  • Total used_memory: Dropped from 4.00 GB capped down to 2.21 GB with igbinary alone, and 1.44 GB with Zstd compression enabled.
  • wp:options:alloptions size: Fell from 1.89 MB raw PHP serialization to 1.04 MB under igbinary, and 386 KB with igbinary plus Zstd.
  • Hit ratio and fragmentation: Settled at 97.9% hits with zero OOM rejections and a steady mem_fragmentation_ratio of 1.09.
  • CPU trade-off: PHP-FPM CPU ticked up roughly 1.8% for Zstd writes while Redis network egress dropped 64%—an easy trade on a multi-node cluster.

Guardrails That Keep It From Happening Twice

We baked five non-negotiable defaults into our base Redis Ansible role so no new box ships stock again:

  • Disable disk persistence on object caches. Set save "" and appendonly no. Ephemeral caches don't need RDB snapshots, and BGSAVE forks trigger copy-on-write spikes that can double RSS under heavy writes.
  • Cap maxmemory at 65%–70% of box RAM. Leave headroom for jemalloc overhead, client output buffers, and OS page cache.
  • Hard-code maxmemory-policy allkeys-lfu. Never trust distro defaults, and skip volatile-* whenever your CMS writes keys without TTLs.
  • Alert on failure precursors. In Prometheus with redis_exporter, page on any OOM error or rejected_connections spike, warn when mem_fragmentation_ratio > 1.35 for 15 minutes, and track evicted_keys beside hit ratio.
  • Run --bigkeys quarterly. Plugins quietly grow autoloaded options over months; catching a 2 MB blob on a quiet Friday beats finding it during Tuesday peak traffic.

Redis rarely crashes dramatically on its own. Left on stock settings, it politely enforces noeviction while your database absorbs the damage. Switch to allkeys-lfu, enable active defragmentation, ditch verbose ASCII serialization, and your cache goes back to doing its only job—staying invisible.

Comments

Popular posts from this blog

PHP FPM Max Children Sizing on Linux

Systemd Socket Tuning for High Load