Common Redis Caching Problems and Solutions

Recognize cache penetration, breakdown, and avalanches, and protect core functionality when Redis is unavailable.

🎯 Introduction

By the end of this article, you will be able to reduce repeated queries for missing and popular records, and keep public profile queries working against the database during Redis failures.

This article uses Node.js 22.9.0, redis 5.9.0, mysql2 3.11.5, and Redis 7.4.2, with the previous article's MySQL environment. The protected version uses course:protected:* to stay separate from the basic caching exercise.


🧱 Cache Penetration and Negative Caching

Cache penetration occurs when requests repeatedly bypass the cache to query data that is also absent from the source. If the program caches only existing records, it must query the database again every time to confirm that a record is missing.

Negative caching briefly stores the result that a lookup found no record, so subsequent identical lookups can return an empty result directly.

Use cases: ID-based lookups such as user details that frequently receive nonexistent IDs. Negative caching only helps with repeated IDs; validate input and limit abnormal request rates as well.

Create read-through.mjs and first check whether cached contents are usable:

read-through.mjs
function decodeUser(raw) {
    if (raw === null) return { hit: false };
    try {
        const value = JSON.parse(raw);
        if (value === null || (Number.isInteger(value.id) && typeof value.name === 'string')) {
            return { hit: true, value };
        }
    } catch {
        // Treat corrupt JSON as a cache miss.
    }
    return { hit: false };
}

A Redis response of null means the key is absent; the JSON text "null" means a previous lookup found no record. Query again for corrupt data or invalid fields instead of returning incorrect profile contents.

Implement the read workflow:

read-through.mjs
export async function readThrough(cache, findUser, id, ttl = 60) {
    const key = `course:protected:user:${id}`;
    const cached = decodeUser(await cache.get(key));
    if (cached.hit) return cached.value;
    const user = await findUser(id);
    await cache.set(key, JSON.stringify(user), { EX: user === null ? 10 : ttl });
    return user;
}

cache accepts the Redis client, and findUser accepts the database query function, making it easier to substitute cache failure handling later. Missing users are cached for only 10 seconds; existing profiles use the supplied ttl.


🛠 Cache Breakdown and Request Coalescing

Cache breakdown occurs when a heavily accessed key becomes invalid and many requests query its source simultaneously. Until a new copy is written, all these requests see a miss, so one invalidation can cause many identical queries.

Request coalescing lets concurrent reads for the same key share one in-flight query, whose result is delivered to all waiting callers.

Use cases: popular profiles or hot content receiving concentrated traffic when cached data expires. The example uses a shared Promise within one Node.js process.

Create single-flight.mjs. Its module-level Map tracks in-flight queries:

single-flight.mjs
const pending = new Map();

export async function runOnce(key, load) {
    if (pending.has(key)) return pending.get(key);
    const task = Promise.resolve().then(load);
    pending.set(key, task);
    try {
        return await task;
    } finally {
        pending.delete(key);
    }
}

The Map entry is removed on both success and failure, preventing long-term reuse of a rejected Promise. Coordination is limited to this process; separate service instances may each still query the source.

Create protection-demo.mjs to prepare the test:

protection-demo.mjs
import { redis } from './redis.mjs';
import { pool } from './db.mjs';
import { findUser, metrics } from './user-repository.mjs';
import { readThrough } from './read-through.mjs';
import { runOnce } from './single-flight.mjs';

await redis.connect();
await redis.del('course:protected:user:1');

Start five queries concurrently:

protection-demo.mjs
const users = await Promise.all(Array.from({ length: 5 }, () =>
    runOnce('user:1', () => readThrough(redis, findUser, 1))
));
console.log(users.length, metrics.sourceReads);

A fresh process prints 5 1: five callers receive results, with only one database read. Regular requests must also pass through the same runOnce; wrapping only test calls does not protect a real endpoint.


🧰 Cache Avalanches and Staggered Expiration

A cache avalanche occurs when cached results become unavailable across a broad set of data, sending many queries back to the source. This can happen when many keys expire together or Redis becomes unavailable. Unlike breakdown concentrated on one hot key, an avalanche affects many records.

Use cases: add small random offsets to expiration times during bulk warming or cache imports so entries expire at different times. A Redis-wide outage also needs fallback behavior and limits on database traffic.

Add a little randomness to the TTL for existing profiles when calling the read function:

protection-demo.mjs
await redis.del('course:protected:user:1');
const ttl = 60 + Math.floor(Math.random() * 10);
console.log(await readThrough(redis, findUser, 1, ttl));
console.log(await redis.ttl('course:protected:user:1'));

Delete the practice key first to ensure a new copy is written. After the profile is returned, the TTL should be close to the generated value of 60 to 69 seconds. Generate a separate random offset for each key during batch writes to stagger expiration.

The next section covers Redis failures.


💡 Fallback When Redis Is Unavailable

Fallback uses an alternative path that still provides core functionality when a dependency is unavailable. When a cache is a copy, a failed read can fall back to the source, and a failed cache write need not discard a successfully fetched result. Failures of the source itself must not be disguised as successful results.

Use cases: public profile queries can continue against the database during a brief Redis outage. Limit concurrent queries and wait times, returning a busy response when capacity is exceeded.

In cache-access.mjs, start by setting a deadline for each cache operation:

cache-access.mjs
import { redis } from './redis.mjs';

async function withinDeadline(operation) {
    const controller = new AbortController();
    let timer;
    const timeout = new Promise((_, reject) => {
        timer = setTimeout(() => {
            reject(new Error('Cache operation timed out'));
            controller.abort();
        }, 200);
    });
    try {
        const client = redis.withCommandOptions({ abortSignal: controller.signal });
        return await Promise.race([operation(client), timeout]);
    } finally {
        clearTimeout(timer);
    }
}

The 200-millisecond budget is for practice; adjust it to the actual network. The abort signal attempts to remove commands that have not yet been sent.

Handle failures only around cache operations:

cache-access.mjs
async function attempt(operation) {
    try {
        if (!redis.isReady) throw new Error('Redis is not ready');
        return await withinDeadline(operation);
    } catch (error) {
        console.warn('Cache temporarily unavailable:', error.message);
        return null;
    }
}

isReady indicates that commands can currently execute, but disconnection can still occur after the check, so keep the catch at the call site. Aggregate error logs in real services to avoid repeated messages on every request during a sustained outage.

Export an interface matching the earlier read function:

cache-access.mjs
export const safeCache = {
    get: key => attempt(client => client.get(key)),
    set: (key, value, options) => attempt(client => client.set(key, value, options)),
};

Continue appending to protection-demo.mjs. Close this script's Redis connection deliberately and verify that database queries still work:

protection-demo.mjs
import { safeCache } from './cache-access.mjs';

await redis.close();
console.log(await readThrough(safeCache, findUser, 1));
await pool.end();

This closes the client connection; it does not stop the Redis server. Cache reads and writes log unavailability, while a healthy MySQL database still returns the profile. Run:

node --env-file=.env protection-demo.mjs

A real service that cannot connect at startup must explicitly choose between failing startup and starting with fallback support. Handling only disconnections after startup is insufficient.

This fallback applies to rebuildable cache copies. If sessions or rate-limit records are unavailable, do not allow requests through simply by ignoring Redis errors.

❓ Questions and Answers

Q1: Can negative caching prevent a newly created user from being found?

Briefly, yes. Keep negative-cache lifetimes short and invalidate the corresponding negative entry after successful creation.

Q2: Does request coalescing limit total queries for different users?

No. Coalescing by key only reduces identical queries. Different keys can still query the source simultaneously, so a separate concurrency limit is needed.

Q3: Does Promise.race alone stop a Redis command?

No. It only determines which result the caller waits for. Even an abort signal cannot undo an operation already executing on the server.


🧪 Exercise

Choose a user ID you know is absent. Query it twice and verify just one database read. Then supply a query function that throws, and confirm that database errors are not cached as missing records.

// Write your code here

🎉 You now understand negative caching, request coalescing, and cache failure handling!