Caching usually starts with a modest goal. A query takes 120 milliseconds, the result rarely changes, and thousands of users ask for the same thing. Put Redis in front of it and the request takes a few milliseconds. Database load falls, costs drop and the product feels faster.
Six months later, Redis goes down. The application falls back to the database exactly as designed, and the database falls over. At that point the cache wasn't just a performance optimisation anymore. It had become part of how the system stays up.
This is easy to miss because caching changes the workload everything behind it sees. If the database once handled 10,000 reads a second and the cache reaches a 95% hit rate, the database now sees about 500. Over time, infrastructure gets sized around that smaller number, traffic grows, uncached queries get more expensive, and other workloads use up the capacity the cache freed. When the cache disappears, the database is suddenly asked for something close to the original 10,000 reads a second, which it may no longer be able to handle.
The Amazon Builders' Library article Caching challenges and strategies calls this a service becoming addicted to its cache: the cache goes from a helpful addition to a necessary part of the service's ability to operate. That article is the main source for this post, and it leads to a better question than "does caching make this faster?" The question is: what happens to the rest of the system when the cache stops working?
How a cache changes the capacity model
The usual cache-aside pattern looks harmless. The application checks the cache, and on a miss reads from the database and fills the cache:
async function getProduct(productId: string) {
const cacheKey = `product:${productId}`;
const cached = await redis.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
const product = await productsRepository.findById(productId);
await redis.set(cacheKey, JSON.stringify(product), { EX: 300 });
return product;
}
It's attractive because Redis isn't the source of truth. If a key disappears, the application reads the database, refills the cache and carries on. The hidden assumption is that the database can absorb the misses, and that can stop being true long before anyone notices.
At 20,000 reads a second with a 98% hit rate, only about 400 reads reach the database. Remove the cache and the database gets 20,000, fifty times more, with no change in user traffic:
So "we can just fall back to the database" isn't a complete plan. The fallback path needs its own capacity model.
Test with the cache turned off
One of the most useful tests for a production cache is also the simplest: turn it off. The Builders' Library article describes testing services with caching disabled to check that safeguards like request caps and load shedding really do protect the service behind it.
A dashboard showing a 97% hit rate is useful day to day. The reliability question is different: at a 0% hit rate, how much production traffic can the database safely handle? If the answer is 25%, Redis is critical, whatever the architecture diagram calls it.
That isn't automatically bad design. At large enough scale, sizing the database to serve everything without a cache can be impractical. Meta's Scaling Memcache at Facebook and TAO describe systems built on exactly that kind of dependency. The mistake isn't relying on a cache. It's discovering during an outage that you were relying on it all along.
Cache stampedes
Misses aren't independent. When a popular key expires, it doesn't cause one database query; it can cause thousands at once. Say product:iphone is very hot and its cached value expires. Two thousand requests arrive at almost the same moment, each one sees a miss, and each one asks the database for the same row:
This is a cache stampede (or thundering herd). Both the Builders' Library and Redis's post on caches, promises and locks discuss coordinating the refresh so that one missing popular value doesn't turn into a burst of identical work.
Coalescing identical misses
What we want is for 2,000 misses on the same key to produce one database query, with the other 1,999 requests sharing its result. This is called request coalescing:
Within one Node.js process, a map of in-flight promises is enough:
const inflight = new Map<string, Promise<unknown>>();
async function cached<T>(key: string, loader: () => Promise<T>): Promise<T> {
const hit = await redis.get(key);
if (hit !== null) {
return JSON.parse(hit) as T;
}
const existing = inflight.get(key);
if (existing) {
return existing as Promise<T>;
}
const promise = loader()
.then(async (value) => {
await redis.set(key, JSON.stringify(value), { EX: 300 });
return value;
})
.finally(() => {
inflight.delete(key);
});
inflight.set(key, promise);
return promise;
}
Across a fleet it's harder, because each instance can decide to refresh independently. Options include distributed locks, probabilistic early refresh, dedicated refresh workers, or simply accepting a bounded amount of duplicate work (one refresh per instance is often fine). There's no single right answer. The key point is that how many misses happen at once matters as much as the miss percentage.
Adding jitter to expiry
Expiry itself can synchronise traffic. If 100,000 entries are warmed at about the same time with a 300-second TTL, a large part of the keyspace expires together five minutes later:
A little randomness spreads the refresh work out:
function ttlWithJitter(baseSeconds: number, jitterSeconds: number) {
return baseSeconds + Math.floor(Math.random() * jitterSeconds);
}
await redis.set(key, value, {
EX: ttlWithJitter(300, 60),
});
Entries now expire somewhere between 300 and 360 seconds instead of all at once. It's the same idea as jitter on retries: a large population of clients doing the same thing at the same moment turns sensible local behaviour into a system-wide spike.
TTLs and invalidation are consistency decisions
TTLs are often picked casually ("five minutes sounds fine"), but a TTL is a product promise. Five minutes means a user may see data several minutes behind the source of truth. For a country list, product descriptions or configuration metadata, that's usually fine. For permissions, inventory, payment state or risk decisions, it may not be. The real question is how stale this value can safely get, and the Builders' Library makes the same point: expiry should follow how often the data changes and how much staleness its consumers can tolerate.
Invalidation is also harder than it looks, because it's a race. Take the common "update the database, then delete the cache key" pattern:
await database.updateProduct(productId, update);
await redis.del(`product:${productId}`);
Now add a concurrent reader. Request A misses the cache and reads the old value from the database. Request B updates the database and deletes the key. Then request A writes its old value into the cache.
Each step was reasonable and the cache is still wrong. Meta's Cache made consistent explains why: in a dynamic cache, data changes on both the read path (cache fills) and the write path (invalidation), and that combination makes many races possible. The old joke about cache invalidation being hard is really about concurrency.
"Eventually consistent" also needs a product definition. A follower count lagging briefly is fine. A revoked admin permission staying active isn't. A stale stock count during a limited-stock checkout causes real business problems. The caching strategy should follow the cost of being wrong, not how easy it is to put a value in Redis.
Serving stale data on purpose
Stale data can also help reliability. Suppose Redis holds a product's price, the entry is due for a refresh, and the database is currently unhealthy. Should every request throw away the cached value and pile onto the failing database? Often it's safer to serve the last known good value a little longer.
The Builders' Library describes doing this with two TTLs. After the soft TTL, the client tries to refresh; if the refresh fails, it keeps serving the cached value until the hard TTL, after which it stops. That gives the dependency room to recover instead of making every request join the failure.
interface CacheEnvelope<T> {
value: T;
refreshedAt: number;
hardExpiresAt: number;
}
async function getConfig(): Promise<Config> {
const cached = await loadCache<Config>("config");
if (!cached) {
return refreshConfig();
}
const age = Date.now() - cached.refreshedAt;
if (age < SOFT_TTL_MS) {
return cached.value;
}
try {
return await refreshConfig();
} catch {
if (Date.now() < cached.hardExpiresAt) {
return cached.value;
}
throw new Error("Config unavailable and stale limit exceeded");
}
}
That's a trade between a slightly stale answer and no answer. For configuration and catalogue data, stale is usually much better than unavailable. For permissions and balances, the opposite can be true. Stale serving only works when you've decided the maximum acceptable staleness up front.
Bounding the fallback
Here's a fallback that looks resilient:
async function getProduct(id: string) {
try {
const cached = await redis.get(`product:${id}`);
if (cached) {
return JSON.parse(cached);
}
} catch {
// Cache unavailable. Continue.
}
return products.findById(id);
}
For one request, it is. Across every instance at once during a Redis outage, every request bypasses the cache and goes to the database, and now two things are down instead of one. A safer version caps how many fallback queries can run at the same time:
import pLimit from "p-limit";
const databaseFallback = pLimit(100);
async function loadWithoutCache(id: string) {
return databaseFallback(() => products.findById(id));
}
Depending on the workload, the protection could be a rate limiter, load shedding, stale serving or another form of admission control. The principle matters more than the tool: losing the cache must not mean unlimited access to the database. The Builders' Library recommends exactly this, capping or shedding requests to the downstream service during long cache failures.
The miss path needs protecting for things that don't exist too. If clients keep asking for /product/does-not-exist, every request misses the cache and queries the database, and a buggy or malicious client can generate endless random IDs to bypass the cache entirely. Negative caching stores the "not found" result briefly:
const NOT_FOUND = "__NOT_FOUND__";
async function getProduct(id: string) {
const key = `product:${id}`;
const cached = await redis.get(key);
if (cached === NOT_FOUND) {
return null;
}
if (cached) {
return JSON.parse(cached);
}
const product = await products.findById(id);
if (!product) {
await redis.set(key, NOT_FOUND, { EX: 30 });
return null;
}
await redis.set(key, JSON.stringify(product), { EX: 300 });
return product;
}
The negative TTL is shorter because "not found" may later become "exists". The Builders' Library mentions caching error responses the same way, with a different TTL from normal entries.
Redis has limits too
Redis is fast, not infinite. A cluster still has finite CPU, memory, network bandwidth, connections and capacity per shard, and how the load is spread matters. If one key such as homepage:trending gets 30% of all traffic, the shard holding it can saturate while cluster-wide CPU looks fine:
Recent Redis versions include the HOTKEYS command for finding the keys that use the most CPU time and network bandwidth. Aggregate capacity doesn't protect you from skew.
Memory pressure turns into database pressure, too. When Redis reaches its memory limit, the eviction policy decides what goes: least recently used, least frequently used, random, keys with a TTL, or no eviction (rejecting writes). If a traffic change pushes useful entries out, the hit rate slides, and at 20,000 requests a second each drop costs the database a lot more:
| Hit rate | Database reads/sec |
|---|---|
| 98% | 400 |
| 90% | 2,000 |
| 70% | 6,000 |
Watching Redis memory without connecting it to hit rate, evictions and database queries misses the consequence that actually matters.
Hit rate as a capacity signal
"Cache hit rate: 93%" doesn't tell me whether the system is safe. This does:
| Metric | Value |
|---|---|
| Request rate | 40,000/s |
| Cache hit rate | 93% |
| Database reads from misses | 2,800/s |
| Database safe capacity | 4,000/s |
Now the margin is visible. If the hit rate drops to 88%, database traffic rises to about 4,800 a second, past the safe limit. So the alert that matters may not be "Redis unavailable" but "hit rate below 90%", because that's where the database starts to be in danger. Hit rate isn't just a cache efficiency metric. It's an input to the capacity model of everything behind the cache.
Alongside the usual cache metrics (hit and miss rate, latency, errors, memory, evictions, connections, CPU, network), I'd want metrics that connect the cache to what it protects: database queries caused by misses, database latency during miss spikes, refresh and coalesced request counts, hot-key distribution, stale responses served and fallback requests rejected. The single most telling number is projected database load if the cache disappeared. It tells you whether the cache is just speeding up a healthy path or holding back a workload the database couldn't survive, and that should shape alerting, capacity planning and how seriously the cache itself is run.
Local caches and cache formats
One way to reduce dependence on a shared cache is an in-process cache in front of it:
If Redis becomes unavailable, a warm local cache can keep both latency and database protection for part of the workload; the Builders' Library suggests this as a fallback. The trade-off is that each process now holds its own copy. Different instances can return different values, invalidation gets harder, memory is duplicated and deployments leave each process with a different set of entries.
I find it helpful to think of a cache as another replica of your data. Then the usual distributed-systems questions appear naturally: how is it populated and invalidated, how stale can it get, what happens when updates arrive out of order, how does it recover, and which copy is the real one? Redis gives you fast key-value access, but the system around it is still a distributed-state system.
Treating a cache as a replica also explains why cache formats matter during deployments. If version 1 writes {"id": "123", "name": "Alice"} and version 2 expects displayName and a version field, both versions share the same Redis cluster during a rolling deploy and read each other's entries. If v2 assumes displayName always exists, old entries break new code. The Builders' Library recommends treating cache formats like persisted data: new code should read old values, old code should tolerate new fields, and flushing everything to fix a mismatch is risky because the refill can overwhelm the database.
Two practical options: put the schema version in the key (product:v1:123, product:v2:123), which briefly doubles storage but avoids ambiguity, or read both shapes:
function parseCachedProduct(raw: string): Product {
const value = JSON.parse(raw);
if (value.version === 2) {
return fromV2(value);
}
return fromLegacy(value);
}
A cache can be disposable in theory and still be too big or too important to throw away instantly in production. The expand-and-contract approach used for database schemas works well here too.
Deciding what to cache
Caching can hide slow code for a long time. A query that takes 1.5 seconds behind a 99.9% hit rate is almost never seen, so it can stay slow for years until a cache failure exposes every request to it. Measuring uncached latency now and then is a reliability exercise, not just database tuning.
Caching also depends on traffic shape. If 80% of requests hit 20% of objects, a cache works very well. If the product changes and traffic spreads more evenly, the same cache size produces many more misses. The Builders' Library recommends checking cache size and expiry against real traffic distributions for this reason.
Before caching something, I ask a few questions:
- Is there real reuse? If almost every request asks for a unique value once, the cache adds a network hop, serialisation, memory and operational work without enough hits to justify them.
- Can the data be stale? If not, caching is much harder.
- Is the miss expensive? A cache earns more when regeneration is costly.
- Can miss traffic be bounded? If losing the cache could take down the source of truth, the fallback needs explicit protection.
Testing how caching degrades
Benchmarking GET at 0.7 ms tells you Redis is fast. It says little about whether the caching design is resilient. These scenarios tell you much more:
| Failure scenario | What I want to know |
|---|---|
| One hot key expires | Does one database query happen, or a stampede? |
| Many keys expire together | Does downstream traffic spike sharply? |
| Redis latency rises | Does application latency degrade gracefully? |
| Redis becomes unavailable | Is the database fallback bounded? |
| Cache starts empty | Can it warm up without overloading dependencies? |
| Hit rate declines gradually | At what point does database load become unsafe? |
| One key becomes extremely hot | Does one shard saturate? |
| Redis memory fills | How do evictions affect the database? |
| Database becomes unavailable | Can stale data keep the service useful? |
| Cache format changes | Can mixed versions coexist? |
| Nonexistent IDs become popular | Are negative results cached? |
Include partial failures. A slow Redis cluster can be worse than a dead one if every request waits for the cache timeout before falling through to the database. And a 90% hit rate can be more interesting than 0% if 90% is exactly where the database crosses its safe limit.
Putting it together
A more defensive cache-aside path looks something like this:
The interesting part of the diagram isn't Redis; it's everything around it. Who's allowed to refresh a hot key? How many fallback queries can run at once? Can the app serve stale data, and how stale? What happens when there's no database capacity left, or when Redis is slow rather than down? Those are reliability decisions; the cache client API is an implementation detail.
There's a simple way to tell which kind of cache you have: imagine turning it off. If latency goes up but the service stays stable, it's a performance optimisation. If you get database overload, timeouts, retry storms and an outage, it's part of your reliability architecture. That's fine, and often unavoidable at scale. What causes trouble is an accidental dependency. Once the system needs the cache to survive, it deserves the same attention as a database or a queue: knowing what happens when it fails, starts empty, sees a new traffic pattern, runs out of memory or gets one very hot key, and whether the database can survive the recovery.
Key takeaways
- Work out what the database would face at a 0% hit rate. If it couldn't survive, the cache is a reliability dependency and should be run like one.
- Test with the cache turned off, and with it slow or partly failing, not just when it's warm.
- Prevent stampedes with request coalescing and TTL jitter, and cache "not found" results briefly.
- Cap fallback traffic to the database, and serve stale data within a defined limit where the product allows it.
- Treat TTLs and invalidation as consistency decisions, and cache formats as contracts across deployments.
- Alert on the hit rate where database load becomes unsafe, not just on Redis being down.
References
- Amazon Builders' Library — Caching challenges and strategies — the main source here: cache addiction, testing with caching disabled, soft and hard TTLs, negative caching, local caches and format changes.
- Meta Engineering — Cache made consistent — why cache fills and invalidation together create races, and how Meta measured and improved consistency.
- Meta Engineering — Scaling Memcache at Facebook — large-scale caching as protection for the database tier.
- Meta Engineering — TAO: The power of the graph — a multi-tier cache in front of persistent storage, and its consistency trade-offs.
- Redis — Caches, promises and locks — cache stampedes and coordinating refreshes with promises and locks.
- Redis — Key eviction —
maxmemoryand the available eviction policies. - Redis — HOTKEYS — finding the keys that use the most CPU time and network bandwidth.
