Enterprise Cloud Architecture, Zero Trust Cybersecurity, LLMOps & High-Scale Systems

Software Architecture

Distributed Caching Strategies: Redis Multi-Cluster Invalidation, Stampede Protection, and Eviction Policies

November 2, 2026 · By writer

technology.efektifpro.com – As backend services scale past 50,000 requests per second, database read replication alone cannot absorb traffic bursts without catastrophic latency spikes. A well-designed distributed caching layer absorbs 95–99% of read queries, dropping database load and delivering sub-2ms response times. However, poorly managed caches introduce dangerous failure modes: cache penetration, cache avalanches, and cache stampedes that can take down primary database clusters within seconds of a cold restart.

Cache Stampede Prevention: The XFetch Probabilistic Algorithm

A cache stampede occurs when a heavily requested hot key expires. Suddenly, thousands of concurrent requests find a cache miss and simultaneously query the database to recompute the value, overwhelming connection pools. The optimal mitigation is probabilistic early expiration (XFetch) — worker threads proactively recompute and refresh the cached item before it expires, with probability increasing as expiration nears:

import math
import random
import time
import json
import redis

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

def xfetch_get_or_compute(key: str, ttl_seconds: int, compute_func, beta: float = 1.0):
    # XFetch algorithm: Probabilistically recomputes cache before expiry.
    # beta: Controls aggressiveness (>1 means earlier proactive recomputation).
    raw_data = r.get(key)
    
    if raw_data:
        record = json.loads(raw_data)
        val = record["val"]
        delta = record["delta"]       # Time taken to compute in seconds
        expiry = record["expiry"]     # Absolute timestamp of expiration
        
        # Probabilistic condition: -delta * beta * ln(rand) > (expiry - now)
        now = time.time()
        time_left = expiry - now
        
        if time_left > 0 and (-delta * beta * math.log(random.random())) < time_left:
            # Cache is still valid and not chosen for early refresh
            return val
            
    # Key is missing OR early refresh condition triggered
    start = time.time()
    new_val = compute_func()
    compute_time = time.time() - start
    
    new_record = {
        "val": new_val,
        "delta": compute_time,
        "expiry": time.time() + ttl_seconds
    }
    r.setex(key, ttl_seconds + 30, json.dumps(new_record))
    return new_val

Cache Invalidation Patterns: Cache-Aside vs Write-Through

PatternHow It WorksProsCons
Cache-AsideApp reads from cache; on miss, queries DB and populates cache. Writes update DB and evict key.Resilient; cache failure doesn't block DB writes.Eventual inconsistency window between DB write and cache eviction.
Write-ThroughApp writes to cache; cache synchronously writes to DB before returning.Strong read consistency; no stale data.Higher write latency; requires robust write failure handling.
Write-Behind (Write-Back)App writes to cache; cache batches writes to DB asynchronously.Ultra-fast writes; absorbs heavy ingestion bursts.Risk of data loss if cache node crashes before flushing to DB.

Memory Eviction Policies in Redis

When Redis reaches its maxmemory limit, the configured eviction policy dictates which keys are purged:

  • volatile-lru / allkeys-lru: Evicts Least Recently Used keys. Ideal when access distribution follows a Pareto (80/20) power law.
  • volatile-lfu / allkeys-lfu: Evicts Least Frequently Used keys. Better than LRU at retaining hot items that experience temporary pauses in traffic.
  • noeviction: Returns out-of-memory errors on write operations. Use only when Redis is employed as an authoritative in-memory datastore rather than a disposable cache.

Production Caching Checklist

  • ✅ All cache keys have explicit TTLs — no unbounded permanent keys
  • ✅ Key expiration times are jittered (randomized ±10%) to prevent simultaneous expirations
  • ✅ Stampede protection implemented on hot aggregate keys via XFetch or distributed locks
  • ✅ Multi-AZ Redis Cluster with automatic sentinel failover enabled
  • ✅ Compression applied for payload values exceeding 10KB (Snappy or zstd)