Suppose you have a product endpoint that queries MongoDB every time someone opens a product page. The query is indexed, the application is reasonably well written, and everything works until a popular product starts attracting traffic.
You introduce Redis. Instead of querying MongoDB for every request, you store the product in Redis for a minute. The next request can retrieve it without touching the database.
It's a sensible optimisation. But what happens when the product's price changes? What if thousands of requests arrive just as the cached value expires? What if Redis runs out of memory, or the Redis container restarts during a busy afternoon?
None of those questions is answered by the two commands that originally made caching look so attractive: GET and SET.
Here are five things worth understanding before putting Redis between your application and its database. The examples use JavaScript and Node.js, but the decisions apply equally to applications written in Go, Python or other languages.
1. Redis doesn't decide what is worth caching — you do
A common starting point is cache-aside: the application checks Redis, retrieves missing data from the database, and saves the result for future reads. Redis's cache-aside documentation describes this pattern in detail.
Let's implement it using the official Node.js client.
npm install redis
import { createClient } from 'redis';
export const redis = createClient({
url: process.env.REDIS_URL,
disableOfflineQueue: true,
socket: { connectTimeout: 2000 }
});
redis.on('error', error => {
console.error('Redis connection error:', error.message);
});
await redis.connect();
Connect once during application startup, rather than opening a new Redis connection for each HTTP request. This minimal startup example assumes Redis is available; a service designed to start without its cache should handle connection failure separately.
Now imagine products is an existing MongoDB collection and product IDs are strings.
async function getProduct(id) {
const key = `cache:v1:product:${id}`;
const cached = await redis.get(key);
if (cached !== null) {
return JSON.parse(cached);
}
const product = await products.findOne({ _id: id });
if (product !== null) {
await redis.set(key, JSON.stringify(product), { EX: 60 });
}
return product;
}
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 270" width="760" height="270" role="img" aria-label="Cache-aside: two paths for the same read">
<rect x="0" y="0" width="760" height="270" rx="8" fill="#f6f4ee" stroke="none"/>
<text x="24" y="36" font-family="Arial, sans-serif" font-size="21" font-weight="600" text-anchor="start" fill="#242b25">Cache-aside: two paths for the same read</text>
<rect x="24" y="100" width="150" height="54" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="99.0" y="132.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Application</text>
<rect x="250" y="100" width="180" height="54" rx="8" fill="#e6eadd" stroke="#242b25"/>
<text x="340.0" y="132.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Redis lookup</text>
<rect x="550" y="100" width="186" height="54" rx="8" fill="#fffef9" stroke="#242b25"/>
<text x="643.0" y="132.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Database</text>
<line x1="174" y1="127" x2="250" y2="127" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="250.0,127.0 241.0,123.0 241.0,131.0" fill="#6d7268"/>
<line x1="430" y1="127" x2="550" y2="127" stroke="#ab4932" stroke-width="1.5"/>
<polygon points="550.0,127.0 541.0,123.0 541.0,131.0" fill="#ab4932"/>
<text x="490" y="114" font-family="Arial, sans-serif" font-size="13" font-weight="400" text-anchor="middle" fill="#ab4932">Miss</text>
<line x1="340" y1="154" x2="340" y2="197" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="340.0,197.0 344.0,188.0 336.0,188.0" fill="#6d7268"/>
<rect x="242" y="197" width="196" height="42" rx="8" fill="#e6eadd" stroke="#d9ddd2"/>
<text x="340.0" y="223.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Return cached data</text>
<text x="350" y="181" font-family="Arial, sans-serif" font-size="13" font-weight="400" text-anchor="start" fill="#6d7268">Hit</text>
<line x1="643" y1="100" x2="643" y2="76" stroke="#6d7268" stroke-width="1.5"/>
<line x1="643" y1="76" x2="340" y2="76" stroke="#6d7268" stroke-width="1.5"/>
<line x1="340" y1="76" x2="340" y2="100" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="340.0,100.0 344.0,91.0 336.0,91.0" fill="#6d7268"/>
<text x="490" y="68" font-family="Arial, sans-serif" font-size="13" font-weight="400" text-anchor="middle" fill="#6d7268">Store result + TTL</text>
</svg>Caption: A cache hit avoids a database read; a miss retrieves and stores the authoritative result.
The first request for a product performs the database query. Later requests can reuse the stored result until the entry expires or is removed.
But consider a different endpoint: an internal report that takes 20 milliseconds to generate and is requested only once a day. Adding a Redis lookup, serialization, network round trip and cache write might provide almost no benefit.
Caching is most attractive when the same result is expensive enough to produce and is reused often enough to justify the extra work. Measure query cost, request repetition, payload size and acceptable staleness before choosing an endpoint.
There is also a security dimension. If /api/account returns different information for different users, a cache key based only on the URL can leak one user's data to another. Include the relevant tenant, identity, locale and permission scope where applicable, and perform authorization independently. Never place raw access tokens or passwords in cache keys.
A Redis hit is not automatically a useful hit. The result must be appropriate for the caller, too.
2. A TTL is not a data consistency strategy
Consider a product that costs $89. Your application caches it for five minutes. Thirty seconds later, someone changes the price to $99.
For the remainder of the cache's lifetime, your application might still display $89.
Redis hasn't malfunctioned. It is doing what you asked it to do.
The TTL (time to live) controls the lifetime of the cached entry, not whether the source data has changed. Choose it according to the business consequences of stale information, rather than simply copying a value from another endpoint.
| Resource | Illustrative TTL | Consideration |
|---|---|---|
| Product categories | 10 minutes | Usually changes infrequently |
| Product descriptions | 5 minutes | Brief staleness may be acceptable |
| Displayed stock count | 10 seconds | Confirm actual stock during checkout |
| Account preferences | 60 seconds | Invalidate after changes |
| Payment authorization | Do not use this cache as authority | Verify against the authoritative system |
These are examples, not universal production defaults.
Use a single command to set the value and its expiration:
await redis.set(key, JSON.stringify(product), { EX: 60 });
Doing this in two separate commands introduces a small but avoidable failure window: the process might stop after writing the value but before setting its expiry. Also, an ordinary SET that overwrites an existing key removes its previous TTL unless you explicitly preserve or replace it. See the official SET and EXPIRE references.
Invalidate the cache after updating the database
async function updateProductPrice(id, price) {
await products.updateOne({ _id: id }, { $set: { price } });
await redis.del(`cache:v1:product:${id}`);
}
This is the basic happy-path implementation. In production, handle failure of the deletion separately: the database update may already have succeeded, so don't blindly retry the whole business operation. A durable outbox or change-stream consumer can help deliver invalidations reliably, although propagation is still asynchronous.
There is another, less obvious problem. Imagine a reader misses the cache and starts fetching the old product. A writer updates the database and deletes the cache key. The original reader then finishes and stores its old snapshot back in Redis.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 300" width="760" height="300" role="img" aria-label="The stale refill race">
<rect x="0" y="0" width="760" height="300" rx="8" fill="#f6f4ee" stroke="none"/>
<text x="24" y="36" font-family="Arial, sans-serif" font-size="21" font-weight="600" text-anchor="start" fill="#242b25">The stale refill race</text>
<rect x="25" y="55" width="190" height="40" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="120.0" y="80.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Reader</text>
<line x1="120" y1="95" x2="120" y2="265" stroke="#d9ddd2" stroke-width="1.5"/>
<rect x="285" y="55" width="190" height="40" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="380.0" y="80.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Writer</text>
<line x1="380" y1="95" x2="380" y2="265" stroke="#d9ddd2" stroke-width="1.5"/>
<rect x="545" y="55" width="190" height="40" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="640.0" y="80.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Database / Redis</text>
<line x1="640" y1="95" x2="640" y2="265" stroke="#d9ddd2" stroke-width="1.5"/>
<line x1="120" y1="120" x2="640" y2="120" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="640.0,120.0 631.0,116.0 631.0,124.0" fill="#6d7268"/>
<text x="380" y="112" font-family="Arial, sans-serif" font-size="14" font-weight="400" text-anchor="middle" fill="#242b25">Read old snapshot ($89)</text>
<line x1="380" y1="165" x2="640" y2="165" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="640.0,165.0 631.0,161.0 631.0,169.0" fill="#6d7268"/>
<text x="510" y="156" font-family="Arial, sans-serif" font-size="13" font-weight="400" text-anchor="middle" fill="#242b25">Update to $99; invalidate</text>
<line x1="120" y1="220" x2="640" y2="220" stroke="#ab4932" stroke-width="1.5"/>
<polygon points="640.0,220.0 631.0,216.0 631.0,224.0" fill="#ab4932"/>
<text x="380" y="211" font-family="Arial, sans-serif" font-size="14" font-weight="600" text-anchor="middle" fill="#ab4932">Delayed reader stores $89</text>
<text x="380" y="286" font-family="Arial, sans-serif" font-size="15" font-weight="400" text-anchor="middle" fill="#ab4932">The old value is back in the cache.</text>
</svg>Caption: A delayed cache fill can restore an old value even after the application invalidates the key.
A short TTL limits how long that particular stale refill survives after it is stored; it does not eliminate the race. For stricter requirements, consider version-aware cache writes with an authoritative version or generation marker and an atomic comparison, or bypass the cache for consistency-critical reads. A Redis transaction alone cannot make a MongoDB write and a Redis invalidation atomic together.
For an online shop, showing a slightly outdated product description may be harmless. Charging a customer an outdated price is not. The checkout operation should validate the price against the authoritative business state regardless of what the browsing cache contains.
3. Your Redis cache needs a memory budget — and an eviction policy
When developers first deploy Redis, they often concentrate on the TTL of each key while overlooking the total amount of memory the service can consume.
Imagine caching 100,000 responses, each averaging 8 KiB. The payloads alone occupy approximately 781 MiB. That excludes key names, metadata, allocation overhead, client buffers and other memory costs.
An expiration time doesn't guarantee the cache will fit in memory before entries expire.
For a dedicated, disposable Redis cache, a configuration might look like this:
maxmemory 512mb
maxmemory-policy allkeys-lru
These settings are illustrative. maxmemory is a threshold for Redis's eviction mechanism, not a hard operating-system or container memory ceiling. Leave measured headroom for allocator fragmentation, buffers and, if enabled, replication and persistence work. Don't set the container's memory limit to exactly the Redis maxmemory value.
You can inspect your running configuration with:
redis-cli CONFIG GET maxmemory maxmemory-policy
redis-cli INFO memory
redis-cli MEMORY USAGE cache:v1:product:123
Redis provides several eviction policies. Choosing one is a decision about which information you are prepared to lose under memory pressure.
| Policy | What it prioritizes |
|---|---|
allkeys-lru | Evict approximately least recently used keys |
allkeys-lfu | Evict approximately least frequently used keys |
volatile-lru | Evict less recently used keys that have an expiration |
volatile-ttl | Prefer expiring keys with shorter remaining lifetimes |
noeviction | Reject memory-growing writes when the limit prevents them |
LRU and LFU in Redis use approximations. No single policy is always optimal. A product catalog with a small set of consistently popular items might benefit from LFU, while an application with rapidly shifting interests might do well with LRU. Compare hit rates and eviction behavior under realistic traffic.
Don't mix disposable cache data with important queue state
Suppose your Node.js application already uses Redis for BullMQ background jobs. It is tempting to reuse the same Redis instance for caching API responses.
The problem is that memory pressure is shared. An allkeys-lru policy can evict queue keys as well as cached products. Key prefixes and numbered Redis logical databases do not create independent memory budgets or eviction policies.
BullMQ's production guide calls for noeviction to protect its queue state.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 245" width="760" height="245" role="img" aria-label="Separate cache and queue responsibilities">
<rect x="0" y="0" width="760" height="245" rx="8" fill="#f6f4ee" stroke="none"/>
<text x="24" y="36" font-family="Arial, sans-serif" font-size="21" font-weight="600" text-anchor="start" fill="#242b25">Separate cache and queue responsibilities</text>
<rect x="250" y="58" width="260" height="42" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="380.0" y="84.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Node.js application</text>
<line x1="380" y1="100" x2="380" y2="118" stroke="#6d7268" stroke-width="1.5"/>
<line x1="190" y1="118" x2="570" y2="118" stroke="#6d7268" stroke-width="1.5"/>
<line x1="190" y1="118" x2="190" y2="139" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="190.0,139.0 194.0,130.0 186.0,130.0" fill="#6d7268"/>
<line x1="570" y1="118" x2="570" y2="139" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="570.0,139.0 574.0,130.0 566.0,130.0" fill="#6d7268"/>
<rect x="24" y="139" width="332" height="82" rx="8" fill="#e6eadd" stroke="#242b25"/>
<rect x="404" y="139" width="332" height="82" rx="8" fill="#fffef9" stroke="#242b25"/>
<text x="190" y="165" font-family="Arial, sans-serif" font-size="16" font-weight="600" text-anchor="middle" fill="#242b25">Dedicated cache Redis</text>
<text x="190" y="190" font-family="Arial, sans-serif" font-size="14" font-weight="400" text-anchor="middle" fill="#6d7268">allkeys-lru / allkeys-lfu</text>
<text x="570" y="165" font-family="Arial, sans-serif" font-size="16" font-weight="600" text-anchor="middle" fill="#242b25">Dedicated queue Redis</text>
<text x="570" y="190" font-family="Arial, sans-serif" font-size="14" font-weight="400" text-anchor="middle" fill="#6d7268">noeviction + recovery plan</text>
</svg>Caption: Disposable cached responses and queue state have different memory and durability requirements.
A separate Redis instance for the cache lets you configure eviction independently from the queue. The queue instance still needs adequate memory, monitoring and an appropriate persistence and recovery strategy. Separate containers also need separate resource budgets; they can still compete for the same host's memory.
The distinction is not whether Redis is capable of holding both kinds of data. It is whether losing those kinds of data has the same consequences.
4. A popular key expiring can cause a cache stampede
Imagine a product that appears on your homepage. Five hundred requests arrive within a brief interval just after its cached value expires.
If the first database read hasn't completed, every caller might see a cache miss and initiate another read. Redis was supposed to protect the database, yet the expiry of one popular key has created a burst of work.
This is known as a cache stampede.
Start by deduplicating requests within a process
If you've read How a Simple JavaScript Cache Can Prevent Duplicate API Requests, the underlying idea will be familiar: share a promise representing an operation that is already running.
const pending = new Map();
function singleFlight(key, loader) {
if (pending.has(key)) return pending.get(key);
const promise = Promise.resolve()
.then(loader)
.finally(() => {
if (pending.get(key) === promise) {
pending.delete(key);
}
});
pending.set(key, promise);
return promise;
}
Wrap the cache miss path with this helper and recheck Redis inside the loader before querying the database. A failed load is removed from pending, allowing a future caller to try again. This helper limits duplicate work per key within one process; it doesn't limit concurrency across different keys.
Add some variation to expiration times
If a batch of products is loaded into Redis at the same moment with identical TTLs, many keys may expire together. A small amount of randomized variation can help spread that workload.
function cacheTTL(base = 60, spread = 15) {
return base + Math.floor(Math.random() * (spread + 1));
}
await redis.set(key, JSON.stringify(product), {
EX: cacheTTL()
});
Here the result is 60–75 seconds, assuming integer arguments. Make sure the maximum duration fits your freshness requirements. This addresses synchronized expiration across different keys, not simultaneous misses for one extremely popular key.
Coordinate across application instances when necessary
A local promise cache doesn't span multiple Node.js processes. For particularly expensive or popular resources, consider a short Redis lock for cache regeneration.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 284" width="760" height="284" role="img" aria-label="Cache stampede vs. coordinated refresh">
<rect x="0" y="0" width="760" height="284" rx="8" fill="#f6f4ee" stroke="none"/>
<text x="24" y="36" font-family="Arial, sans-serif" font-size="21" font-weight="600" text-anchor="start" fill="#242b25">Cache stampede vs. coordinated refresh</text>
<text x="24" y="66" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="start" fill="#ab4932">Uncoordinated misses</text>
<rect x="24" y="81" width="116" height="22" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="82.0" y="97.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Caller 1</text>
<line x1="140" y1="92" x2="550" y2="92" stroke="#ab4932" stroke-width="1.5"/>
<polygon points="550.0,92.0 541.0,88.0 541.0,96.0" fill="#ab4932"/>
<rect x="24" y="106" width="116" height="22" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="82.0" y="122.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Caller 2</text>
<line x1="140" y1="117" x2="550" y2="117" stroke="#ab4932" stroke-width="1.5"/>
<polygon points="550.0,117.0 541.0,113.0 541.0,121.0" fill="#ab4932"/>
<rect x="24" y="131" width="116" height="22" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="82.0" y="147.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Caller 3</text>
<line x1="140" y1="142" x2="550" y2="142" stroke="#ab4932" stroke-width="1.5"/>
<polygon points="550.0,142.0 541.0,138.0 541.0,146.0" fill="#ab4932"/>
<rect x="550" y="81" width="186" height="72" rx="8" fill="#fffef9" stroke="#ab4932"/>
<text x="643" y="108" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Database</text>
<text x="643" y="130" font-family="Arial, sans-serif" font-size="15" font-weight="400" text-anchor="middle" fill="#ab4932">3 reads</text>
<text x="24" y="176" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="start" fill="#242b25">Coordinated refresh</text>
<rect x="24" y="191" width="116" height="22" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="82.0" y="207.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Caller 1</text>
<line x1="140" y1="202" x2="190" y2="202" stroke="#6d7268" stroke-width="1.5"/>
<line x1="190" y1="202" x2="190" y2="227" stroke="#6d7268" stroke-width="1.5"/>
<rect x="24" y="216" width="116" height="22" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="82.0" y="232.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Caller 2</text>
<line x1="140" y1="227" x2="190" y2="227" stroke="#6d7268" stroke-width="1.5"/>
<line x1="190" y1="227" x2="190" y2="227" stroke="#6d7268" stroke-width="1.5"/>
<rect x="24" y="241" width="116" height="22" rx="8" fill="#fffef9" stroke="#d9ddd2"/>
<text x="82.0" y="257.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Caller 3</text>
<line x1="140" y1="252" x2="190" y2="252" stroke="#6d7268" stroke-width="1.5"/>
<line x1="190" y1="252" x2="190" y2="227" stroke="#6d7268" stroke-width="1.5"/>
<line x1="190" y1="227" x2="236" y2="227" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="236.0,227.0 227.0,223.0 227.0,231.0" fill="#6d7268"/>
<rect x="236" y="208" width="218" height="38" rx="8" fill="#e6eadd" stroke="#242b25"/>
<text x="345.0" y="232.0" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Shared refresh</text>
<line x1="454" y1="227" x2="550" y2="227" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="550.0,227.0 541.0,223.0 541.0,231.0" fill="#6d7268"/>
<rect x="550" y="191" width="186" height="72" rx="8" fill="#e6eadd" stroke="#242b25"/>
<text x="643" y="218" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="middle" fill="#242b25">Database</text>
<text x="643" y="240" font-family="Arial, sans-serif" font-size="15" font-weight="400" text-anchor="middle" fill="#242b25">1 read</text>
</svg>Caption: Coordinating refresh work can reduce the number of concurrent database queries for the same missing key.
The basic acquisition and release primitives are:
import { randomUUID } from 'node:crypto';
const token = randomUUID();
const lockKey = `lock:${key}`;
const acquired = await redis.set(lockKey, token, {
NX: true,
PX: 5000
});
if (acquired === 'OK') {
try {
// Recheck the cache, load if necessary, then populate it.
} finally {
await redis.eval(
`if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0`,
{ keys: [lockKey], arguments: [token] }
);
}
}
This snippet illustrates the lock primitives, not a complete distributed cache loader. Callers that don't acquire the lock should use bounded waiting with jitter and recheck the cache, serve acceptable stale data, or fail gracefully. Don't spin in a tight loop.
The token matters: if the lease expires and another worker acquires the lock, the original worker must not delete the new worker's lock. The conditional Lua script makes that ownership check and deletion atomic on the Redis instance.
A five-second lease does not guarantee exclusive work if a loader takes longer than five seconds, Redis evicts the lock, or failover loses the lock state. This pattern is useful for reducing redundant work where occasional overlap is tolerable, not for guaranteeing correctness of payments or other critical writes. See Redis's distributed locking guidance.
For many services, local deduplication, randomized TTLs and a database concurrency limit are a more reasonable starting point than distributed locks everywhere.
5. Design for the day Redis is unavailable
A cache should normally make an application faster, not make it impossible to use when the cache is unavailable.
Consider the first getProduct() implementation. If Redis fails during GET, the function throws without ever trying the database. If Redis fails during SET, the application throws even though it already retrieved the product successfully.
For a disposable read cache, neither behavior is particularly desirable.
async function getProduct(id) {
const key = `cache:v1:product:${id}`;
return singleFlight(key, async () => {
try {
const cached = await redis.get(key);
if (cached !== null) return JSON.parse(cached);
} catch (error) {
console.warn('Cache read failed:', error.message);
}
const product = await products.findOne({ _id: id });
if (product !== null) {
try {
await redis.set(key, JSON.stringify(product), {
EX: cacheTTL()
});
} catch (error) {
console.warn('Cache write failed:', error.message);
}
}
return product;
});
}
This example uses the helpers defined above and demonstrates fail-open behavior for cached reads. It is not a complete outage policy. Set bounded command deadlines as well as connection timeouts, and consider temporarily bypassing an unhealthy cache so each request doesn't wait for a failing dependency. Disabling the offline queue helps avoid indefinitely accumulating commands while disconnected, but it is not itself a command deadline. The node-redis production guide discusses connection and command handling.
There's an important trade-off here. If Redis normally absorbs 95% of your reads, suddenly sending every request to the database can be disastrous. Fail-open needs protection: cap concurrent database work, apply admission control, and return an appropriate temporary failure rather than accepting unlimited work. In some systems, serving a bounded stale response is better than a total outage.
Measure whether the cache is actually helping
Start with these Redis commands:
redis-cli INFO stats
redis-cli INFO memory
| Metric | What to investigate |
|---|---|
keyspace_hits and keyspace_misses | Whether reads frequently find cached values |
evicted_keys | Whether memory pressure is removing entries |
expired_keys | How frequently entries reach expiry |
used_memory and used_memory_rss | Redis-accounted memory and resident process memory |
| Application cache latency | Network and serialization cost |
| Database read rate | Whether caching actually reduces database workload |
For a meaningful hit ratio, use counter changes over the same observation window, not the lifetime totals from unrelated traffic.
function hitRate(hits, misses) {
const total = hits + misses;
return total === 0 ? null : hits / total * 100;
}
Suppose an application receives 1,000 eligible reads per second. With a 95% hit rate, around 50 reads per second reach the database in a simplified cache-aside model. At a 70% hit rate, that becomes 300 reads per second — six times as much database work. During a complete cache outage, it could reach 1,000 without other controls.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 260" width="760" height="260" role="img" aria-label="Database reads as cache hit rate falls">
<rect x="0" y="0" width="760" height="260" rx="8" fill="#f6f4ee" stroke="none"/>
<text x="24" y="36" font-family="Arial, sans-serif" font-size="21" font-weight="600" text-anchor="start" fill="#242b25">Database reads as cache hit rate falls</text>
<text x="24" y="61" font-family="Arial, sans-serif" font-size="14" font-weight="400" text-anchor="start" fill="#6d7268">Illustrative workload: 1,000 eligible reads per second</text>
<text x="24" y="108" font-family="Arial, sans-serif" font-size="14" font-weight="400" text-anchor="start" fill="#242b25">95% hits</text>
<rect x="190" y="90" width="470" height="24" rx="4" fill="#fffef9" stroke="#d9ddd2"/>
<rect x="190" y="90" width="23.5" height="24" rx="4" fill="#e6eadd" stroke="none"/>
<text x="736" y="108" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="end" fill="#242b25">50/s</text>
<text x="24" y="157" font-family="Arial, sans-serif" font-size="14" font-weight="400" text-anchor="start" fill="#242b25">70% hits</text>
<rect x="190" y="139" width="470" height="24" rx="4" fill="#fffef9" stroke="#d9ddd2"/>
<rect x="190" y="139" width="141.0" height="24" rx="4" fill="#e6eadd" stroke="none"/>
<text x="736" y="157" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="end" fill="#242b25">300/s</text>
<text x="24" y="206" font-family="Arial, sans-serif" font-size="14" font-weight="400" text-anchor="start" fill="#242b25">Cache unavailable</text>
<rect x="190" y="188" width="470" height="24" rx="4" fill="#fffef9" stroke="#d9ddd2"/>
<rect x="190" y="188" width="470.0" height="24" rx="4" fill="#ab4932" stroke="none"/>
<text x="736" y="206" font-family="Arial, sans-serif" font-size="15" font-weight="600" text-anchor="end" fill="#ab4932">1000/s</text>
<text x="24" y="246" font-family="Arial, sans-serif" font-size="13" font-weight="400" text-anchor="start" fill="#6d7268">Assumes one database read per miss and no additional controls.</text>
</svg>Caption: A falling hit rate can increase database workload sharply even when incoming traffic remains constant. Illustrative arithmetic, not benchmark results.
Redis's server-level counters include key lookups from other operations, so instrument application-specific cache hits, misses and errors too. Monitor end-to-end latency and test cold starts, evictions, Redis disconnections and recovery under realistic load.
A cache that performs beautifully on a normal day but overwhelms the database during a restart is not necessarily a successful optimization.
Final thoughts
Redis is an excellent tool when you have a workload that benefits from shared, fast access to reusable data. But installing it doesn't automatically solve freshness, memory management or reliability.
Before caching an endpoint, ask five questions:
- Is the result expensive and frequently reused?
- How stale can it safely become, and how will changes invalidate it?
- What should Redis remove when memory runs low?
- What happens when many callers miss the same key?
- Can the application survive when Redis is unavailable?
If you can answer those questions, you're designing a caching strategy rather than simply adding another service to your infrastructure.
Redis can save your database a tremendous amount of work. The real engineering challenge is ensuring that it continues to do so when conditions are less than ideal.
THE CONVERSATION
Comments
Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.
Loading comments…