CodeBodh

Redis Caching Patterns: Stampede Prevention & Eviction

Master Redis caching patterns at scale using cache-aside, singleflight mutexes, probabilistic early expiration, and LFU eviction for backends.

Team CodeBodh By Team CodeBodh
Nov 30, 2026
7 min read
2 views
Redis Caching Patterns: Stampede Prevention & Eviction

Executive Summary: Preventing Cache Stampedes and Memory Eviction Storms

When a popular product catalog key or tenant configuration expires at 12:00:00 UTC under 8,000 requests per second, naive cache-aside code routes all 8,000 concurrent cache misses straight into PostgreSQL simultaneously. Within two seconds, database CPU hits 100%, PgBouncer connection pools saturate, and even unrelated endpoints begin returning 504 Gateway Timeouts.

Production-grade Redis caching patterns prevent both thundering-herd stampedes and silent hit-rate collapse. By combining distributed singleflight mutexes, probabilistic early expiration (XFetch), negative caching with jittered TTLs, and properly tuned allkeys-lfu eviction policies, backend systems maintain sub-millisecond read latency while shielding primary databases from sudden recomputation storms.


1. Anatomy of a Cache Stampede, Penetration & Avalanche

Most caching outages stem from three distinct failure modes that require different architectural defenses:

  • Cache Stampede (Thundering Herd): A single hot key with expensive database computation expires, causing hundreds of concurrent workers to miss Redis and execute the identical SQL aggregation simultaneously.
  • Cache Penetration: Malicious or buggy clients repeatedly query non-existent IDs (such as GET /users/-1 or random UUIDs). Because the database returns null and nothing is written to Redis, every single probe bypasses the cache and hits PostgreSQL.
  • Cache Avalanche: Thousands of keys seeded during a batch job share an identical TTL (for example, 3600 seconds) and expire at the exact same second, creating a synchronized latency spike across the entire cluster.
+-----------------------------------------------------------------------+

|       Stampede-Resistant Redis Cache-Aside & Singleflight Flow        |
|---|
  App Request (GET tenant:42:catalog)
                      |
                      v
+-----------------------------------------------------------------------+
|  1. Redis Read (GET + PTTL / Probabilistic XFetch Check)              |
|     - If Hit & Not Early-Expired -> Return Cached Payload (< 0.5 ms)  |
|     - If Sentinel "__NULL__" -> Return 404 / Empty Immediately        |
+-----------------------------------------------------------------------+
                      | (Miss or Single Worker Elected for Early Refresh)
                      v
+-----------------------------------------------------------------------+
|  2. Distributed Singleflight Lock (SET lock:key token NX PX 3000)     |
+-----------------------------------------------------------------------+
        |                                               |
  [Lock Acquired]                                [Lock Held by Peer]
        |                                               |
        v                                               v
  Query PostgreSQL Primary/Replica               Sleep 25ms + Retry Read
  SETEX with Jittered TTL (300s + rand(0,45s))   (Or Serve Stale Copy)
  Release Lock via Atomic Lua Script

2. Cache-Aside, Write-Through & Client-Side Tracking

Selecting the right read/write topology depends on your staleness tolerance and write-to-read ratio:

  • Cache-Aside (Lazy Loading): The application checks Redis first, queries PostgreSQL on a miss, and populates Redis. It keeps Redis memory lean because only actively requested items are cached, though cold misses incur an extra round trip.
  • Write-Through: Application writes update PostgreSQL and immediately refresh the corresponding Redis key (or invalidate it cleanly via the transactional outbox pattern). This guarantees fresh reads at the cost of caching items that may never be read again.
  • Redis Client-Side Tracking: As documented in the Redis client-side caching reference, RESP3 and CLIENT TRACKING ON (or BCAST prefix mode) allow application nodes to keep ultra-hot keys in local APCu/in-process RAM while receiving push invalidations whenever another writer modifies those keys.

3. Tuning Redis Key Eviction: allkeys-lru vs. allkeys-lfu

Running a cache instance with maxmemory-policy noeviction causes every SET command to fail with OOM command not allowed the moment memory fills. Conversely, picking the wrong eviction policy silently drops hot working-set keys in favor of one-time background scans.

As detailed in the official Redis key eviction documentation, Redis offers approximated LRU, approximated LFU (using a probabilistic Morris counter with configurable decay), and Least Recently Modified (LRM, introduced in Redis 8.6) policies:

Eviction Policy Selection Criteria Scan Resistance Best Production Workload
noeviction Rejects writes at maxmemory N/A Persistent queues, job ledgers, primary state stores
allkeys-lru Oldest last-read/write timestamp Moderate (one-off scans can evict older hot keys) General power-law caching with uniform TTLs
allkeys-lfu Lowest access frequency (Morris counter) High (protects hot keys from batch scans) Multi-tenant SaaS catalogs, config, session metadata
allkeys-lrm Longest time since last write modification Low–Moderate Write-skewed caches prioritizing recently updated keys
volatile-ttl Shortest remaining TTL among expiring keys Low Mixed cache + persistent keyspace (when separation is impossible)

Raise maxmemory-samples from the default 5 to 10 on dedicated cache nodes to sharpen eviction accuracy at negligible CPU cost, and keep persistent queues or Redis rate-limiting buckets on a separate Redis instance from your general eviction cache.


4. Stampede Defenses: Singleflight Locks & Probabilistic Early Expiration

To prevent 500 PHP-FPM workers from hitting PostgreSQL simultaneously on a cache miss, combine two complementary mechanisms:

  1. Distributed Singleflight Mutex: On a cache miss, each worker attempts SET lock:{key} {owner_token} NX PX 3000. Only the single winning worker queries PostgreSQL and writes the result back; peer workers pause 25–40 ms and re-read Redis once the winner populates it. Always release the lock using an atomic Lua check-and-delete script so a slow worker never deletes a peer's newer lock.
  2. Probabilistic Early Expiration (XFetch): Store the computation duration (delta) alongside the cached JSON payload. As the key approaches expiration, individual requests evaluate now - (delta * beta * ln(rand())) >= expiry_ts. One lucky request recomputes the value in the background before the TTL actually hits zero, eliminating cold-miss stalls on ultra-hot keys entirely.

5. Production PHP 8.3 Singleflight Cache & Redis Configs

The following PHP 8.3 service implements stampede-safe cache-aside loading with distributed singleflight locking, atomic Lua lock release, negative sentinel caching, and randomized TTL jitter:

<?php

declare(strict_types=1);

namespace App\Cache;

use Redis;

final readonly class StampedeSafeCache
{
private const NULL_SENTINEL = 'CACHE_NULL';
private const UNLOCK_LUA = <<<'LUA'
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
LUA;

public function __construct(private Redis $redis) {}

/**
 * Fetches a cached value with singleflight lock protection and TTL jitter.
 *
 * @template T
 * @param callable(): (T|null) $loader
 * @return T|null
 */
public function remember(string $key, int $baseTtlSeconds, callable $loader): mixed
{
    $cached = $this->redis->get($key);
    if (is_string($cached)) {
        return $cached === self::NULL_SENTINEL
            ? null
            : json_decode($cached, true, 512, JSON_THROW_ON_ERROR);
    }

    $lockKey = 'lock:' . $key;
    $ownerToken = bin2hex(random_bytes(16));

    // Attempt singleflight lock for up to 3 seconds
    $acquired = $this->redis->set($lockKey, $ownerToken, ['NX', 'PX' => 3000]);

    if (!$acquired) {
        // Peer worker waits briefly and retries cache read
        for ($i = 0; $i < 6; $i++) {
            usleep(30_000);
            $retry = $this->redis->get($key);
            if (is_string($retry)) {
                return $retry === self::NULL_SENTINEL
                    ? null
                    : json_decode($retry, true, 512, JSON_THROW_ON_ERROR);
            }
        }
    }

    try {
        $value = $loader();
        if ($value === null) {
            // Negative cache prevents cache penetration on missing IDs
            $this->redis->setex($key, random_int(20, 40), self::NULL_SENTINEL);
            return null;
        }

        // Add 0-15% jitter to prevent synchronized cache avalanches
        $jitter = random_int(0, max(1, (int) ($baseTtlSeconds * 0.15)));
        $encoded = json_encode($value, JSON_THROW_ON_ERROR);
        $this->redis->setex($key, $baseTtlSeconds + $jitter, $encoded);

        return $value;
    } finally {
        if ($acquired) {
            $this->redis->eval(self::UNLOCK_LUA
, [$lockKey, $ownerToken], 1);
}
}
}
}

On the Redis server side, configure dedicated cache nodes with allkeys-lfu, higher sampling accuracy, and lazy freeing so deleting multi-megabyte cached collections never stalls the single-threaded event loop:

# /etc/redis/redis-cache.conf
maxmemory 4gb
maxmemory-policy allkeys-lfu
maxmemory-samples 10

# Tune LFU Morris counter decay (1-minute decay, moderate saturation)
lfu-log-factor 10
lfu-decay-time 1
Offload large key unlinks & expirations to background BIO threads
lazyfree-lazy-eviction yes
lazyfree-lazy-expire yes
lazyfree-lazy-server-del yes

Verify live cache efficiency and eviction health from your ops console by calculating the real-time hit ratio and checking for unexpected eviction spikes:

#!/usr/bin/env bash
set -euo pipefail

redis-cli INFO stats | awk -F: '
  /^keyspace_hits:/   { hits=$2 }
/^keyspace_misses:/ { misses=$2 }
/^evicted_keys:/    { evicted=$2 }
/^expired_keys:/    { expired=$2 }
END {
total = hits + misses;
ratio = (total > 0) ? (hits / total) * 100 : 0;
printf "Hit Ratio: %.2f%% | Hits: %d | Misses: %d | Evicted: %d | Expired: %d\n",
ratio, hits, misses, evicted, expired;
}
'

6. Developer FAQs on Redis Caching Patterns

1. What is a healthy Redis cache hit ratio in production?

For read-heavy SaaS catalogs, user profiles, and API responses, aim for a hit ratio above 90% to 95%. If your hit ratio drops below 80% while evicted_keys climbs rapidly, either increase maxmemory, switch from allkeys-lru to allkeys-lfu, or stop caching unbounded one-off search permutations.

2. Why should I avoid calling KEYS * or large SMEMBERS for cache invalidation?

KEYS * blocks the entire Redis event loop in O(N) time and can stall all clients for seconds on million-key instances. Use versioned key prefixes (for example, incrementing a tiny integer epoch v:tenant_42 so old keys age out naturally) or bounded SCAN cursors during background maintenance.

3. Should Redis caches use RDB snapshots or AOF persistence?

For pure ephemeral caches backed by PostgreSQL, disabling disk persistence (save "" and appendonly no) eliminates fork-induced latency spikes and copy-on-write memory overhead. Pair that with stampede protection so a cold restart warms cleanly without overwhelming your database.

4. How do I prevent large serialized payloads from bloating Redis RAM?

Compress JSON payloads larger than 2 KB with zstd or lz4 before writing to Redis, project only the columns your endpoint actually renders instead of full ORM models, and track top memory consumers with redis-cli --bigkeys.


7. Summary & Production Rollout Checklist

Effective Redis caching patterns protect database stability under peak concurrency while keeping read latency predictable. Isolate pure caches on dedicated instances with allkeys-lfu, wrap hot loaders in singleflight mutexes with jittered TTLs, and cache negative lookups briefly to stop penetration probes.

  1. Separate Cache & State Instances: Run rate limiters and job queues on noeviction Redis nodes, and run ephemeral caches on allkeys-lfu with lazyfree-lazy-eviction yes.
  2. Eliminate Stampedes & Avalanches: Replace raw get/set wrappers with singleflight locks, randomized TTL jitter, and negative sentinel values.
  3. Monitor Hit Ratios & Big Keys: Export keyspace_hits, keyspace_misses, and evicted_keys to Prometheus and OpenTelemetry dashboards alongside PostgreSQL query latency metrics.

Related Architectural & Engineering Guides

Team CodeBodh

CodeBodh Team creates high quality scripts, SaaS applications and developer tools to help you build faster.

Comments (0)

Security check against automated spam
11 + 6 = ?