Skip to main content
Why CacheeHow It Works
All Verticals5G TelecomAd TechAI InfrastructureFraud DetectionGamingTrading
PricingDocsBlogSchedule DemoLog InStart Free Trial
← Back to Blog

Cache Stampede Prevention Techniques

December 22, 2025 • 7 min read • Reliability

It's 3 AM. Your database just crashed. The cause? A popular cache key expired, and 10,000 concurrent requests all tried to regenerate it at once. This is a cache stampede—also called the thundering herd or dog pile effect.

What Is a Cache Stampede?

When a cached value expires under high traffic:

  1. Request 1 finds cache empty, starts regenerating
  2. Requests 2-10,000 arrive before Request 1 finishes
  3. All 10,000 requests query the database simultaneously
  4. Database overwhelmed, response times spike, possibly crashes
Real impact: We've seen stampedes bring down production databases in under 30 seconds. A single expired cache key can cascade into full outage.

Technique 1: Cache Locking

Only one request regenerates the cache; others wait or use stale data:

async function getWithLock(key, generateFn, ttl) {
    // Try to get cached value
    let value = await cache.get(key);
    if (value) return value;

    // Try to acquire lock
    const lockKey = `lock:${key}`;
    const acquired = await cache.set(lockKey, '1', { nx: true, ex: 10 });

    if (acquired) {
        try {
            // We have the lock - regenerate
            value = await generateFn();
            await cache.set(key, value, { ex: ttl });
            return value;
        } finally {
            await cache.del(lockKey);
        }
    } else {
        // Another request is regenerating - wait and retry
        await sleep(100);
        return cache.get(key);  // Return whatever is there
    }
}

Technique 2: Request Coalescing

Deduplicate concurrent requests for the same key:

const inflight = new Map();

async function getCoalesced(key, generateFn, ttl) {
    // Check cache first
    const cached = await cache.get(key);
    if (cached) return cached;

    // Check if request already in flight
    if (inflight.has(key)) {
        return inflight.get(key);  // Return existing promise
    }

    // Create promise for this regeneration
    const promise = (async () => {
        try {
            const value = await generateFn();
            await cache.set(key, value, { ex: ttl });
            return value;
        } finally {
            inflight.delete(key);
        }
    })();

    inflight.set(key, promise);
    return promise;
}

Now 10,000 concurrent requests result in 1 database query, not 10,000.

Technique 3: Probabilistic Early Expiration

Randomly refresh cache before it actually expires:

async function getWithEarlyExpiration(key, generateFn, ttl) {
    const data = await cache.get(key);

    if (data) {
        const { value, cachedAt } = JSON.parse(data);
        const age = (Date.now() - cachedAt) / 1000;
        const remaining = ttl - age;

        // Probability of refresh increases as expiration approaches
        // At 80% of TTL, 20% chance to refresh
        // At 95% of TTL, 50% chance to refresh
        const refreshProbability = Math.max(0, 1 - (remaining / (ttl * 0.2)));

        if (Math.random() < refreshProbability) {
            // Refresh in background, return current value
            regenerateInBackground(key, generateFn, ttl);
        }

        return value;
    }

    // Cache miss - regenerate synchronously
    const value = await generateFn();
    await cache.set(key, JSON.stringify({ value, cachedAt: Date.now() }), { ex: ttl });
    return value;
}
Why this works: Random early refresh spreads regeneration over time instead of everyone hitting expiration at once.

Technique 4: Stale-While-Revalidate

Serve stale data while refreshing in background:

async function getWithSWR(key, generateFn, { freshTTL, staleTTL }) {
    const data = await cache.get(key);

    if (data) {
        const { value, cachedAt } = JSON.parse(data);
        const age = (Date.now() - cachedAt) / 1000;

        if (age < freshTTL) {
            return value;  // Fresh - return immediately
        }

        if (age < staleTTL) {
            // Stale but usable - refresh in background
            setImmediate(() => regenerate(key, generateFn, freshTTL, staleTTL));
            return value;  // Return stale value immediately
        }
    }

    // Too stale or missing - must regenerate synchronously
    return regenerate(key, generateFn, freshTTL, staleTTL);
}

Technique 5: Scheduled Background Refresh

For critical data, don't wait for expiration—refresh proactively:

// Refresh popular data every 5 minutes, TTL is 10 minutes
// Data never actually expires in practice

setInterval(async () => {
    const popularKeys = await getPopularKeys();

    for (const key of popularKeys) {
        try {
            const value = await regenerateData(key);
            await cache.set(key, value, { ex: 600 }); // 10 min TTL
        } catch (err) {
            console.error(`Failed to refresh ${key}:`, err);
            // Existing cached value will continue serving
        }
    }
}, 5 * 60 * 1000);  // Every 5 minutes

Choosing the Right Technique

In practice, combine multiple techniques for defense in depth.

Automatic stampede protection

Cachee.ai includes built-in stampede prevention with request coalescing and smart refresh.

Start Free Trial

Related Reading

The Numbers That Matter

Cache performance discussions get philosophical fast. Here are the actual measured numbers from production deployments running on documented hardware, so you can compare against your own infrastructure instead of trusting marketing copy.

The compounding effect matters more than any single number. A 28-nanosecond L0 hit means your application spends almost zero time on cache lookups in the hot path, leaving the CPU free for the actual business logic that generates revenue.

When Caching Actually Helps

Caching isn't free. It introduces a consistency problem you didn't have before. Before adding any cache layer, the question to answer is whether your workload actually benefits from caching at all.

Caching helps when three conditions hold simultaneously. First, your reads dramatically outnumber your writes — typically a 10:1 ratio or higher. Second, the same keys get read repeatedly within a window where a cached value remains valid. Third, the cost of computing or fetching the underlying value is meaningfully higher than the cost of a cache lookup. Database queries that hit secondary indexes, RPC calls to slow upstream services, expensive computed aggregations, and rendered template fragments all qualify.

Caching hurts when those conditions don't hold. Write-heavy workloads suffer because every write invalidates a cache entry, multiplying your work. Workloads with poor key locality suffer because the cache wastes memory storing entries that never get reused. Workloads where the underlying fetch is already fast — well-indexed primary key lookups against a properly tuned database, for example — gain almost nothing from caching and inherit the consistency complexity for no reason.

The honest first step before any cache deployment is measuring your actual read/write ratio, key access distribution, and underlying fetch latency. If your read/write ratio is below 5:1 or your underlying database is already returning results in single-digit milliseconds, the engineering time is better spent elsewhere.

Memory Efficiency Is The Hidden Cost Lever

Throughput numbers get the headlines but memory efficiency determines your monthly bill. A cache that stores the same hot data in less RAM lets you run a smaller instance class — and on AWS that's the difference between profitable and breakeven for a lot of services.

Redis stores each key as a Simple Dynamic String with 16 bytes of header overhead, plus dictEntry pointers in the main hashtable, plus embedded TTL metadata. For 1KB values, per-entry overhead lands around 1100-1200 bytes once you account for hashtable load factor and slab fragmentation. At a million keys, that's roughly 1.2 GB of resident memory just for the data.

Cachee's L1 layer uses sharded DashMap entries with compact packing — a 64-bit key hash, value bytes, an 8-byte expiry timestamp, and a small frequency counter for the CacheeLFU admission filter. Per-entry overhead lands at roughly 40 bytes of structural data on top of the value itself. For the same million-key workload, that's about 13% smaller resident memory. On AWS ElastiCache pricing, that gap is the difference between needing a cache.r7g.large versus a cache.r7g.xlarge for borderline workloads.

What This Actually Costs

Concrete pricing math beats hypothetical. A typical SaaS workload with 1 billion cache operations per month, average 800-byte values, and a 5 GB hot working set currently runs on AWS ElastiCache cache.r7g.xlarge primary plus a read replica — roughly $480 per month for the two nodes, plus cross-AZ data transfer charges that quietly add another $50-150 per month depending on access patterns.

Migrating the hot path to an in-process L0/L1 cache and keeping ElastiCache as a cold L2 fallback drops the dedicated cache spend to $120-180 per month. For workloads where the hot working set fits inside the application's existing memory budget, you can eliminate the dedicated cache tier entirely. The cache becomes a library you link into your binary instead of a separate service to operate.

Compounded over twelve months, that's $3,600 to $4,500 per year on a single small workload. Multiply across a fleet of services and the savings start showing up in finance team conversations. The bigger savings usually come from eliminating cross-AZ data transfer charges, which Redis-as-a-service architectures incur on every read that crosses an availability zone.