---
title: "Redis Caching Patterns: Cache-Aside, TTLs and Cache Stampedes"
description: "Caching with Redis in Node.js apps: cache-aside, write-through, TTLs with jitter, invalidation, preventing cache stampedes, and what you shouldn't cache at all."
url: https://sanderyaz.com/en/blog/redis-caching-patterns/
author: Sander Yazıcıoğlu
date: 2026-12-02
updated: 2026-12-02
lang: en
tags: ["Redis","Node.js","Backend","Performance"]
---

# Redis Caching Patterns: Cache-Aside, TTLs and Cache Stampedes

At Loadium and Testinium we hit the same problem on high-traffic reporting screens: the same heavy query ran dozens of times a second and the database choked. Putting Redis in front fixes that, but a badly built cache means stale data, memory blowups and sudden load spikes. Here are the patterns that work.

## 1. Cache-aside (lazy loading)

The most common and safest pattern: check the cache first; on a miss, read the source and write the cache.

```ts
async function getRunSummary(id: string) {
  const key = `run:summary:v2:${id}`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const summary = await db.runSummary(id);
  await redis.set(key, JSON.stringify(summary), 'EX', 300);
  return summary;
}
```

The `v2` in the key is the easiest way to invalidate the whole old cache when the data shape changes.

## 2. Write-through and invalidation

When data is written, the cache must be updated (write-through) or deleted (invalidated). Deleting is usually safer: the next read fetches fresh data and there's less risk of a race between two writes.

```ts
await db.updateRun(id, patch);
await redis.del(`run:summary:v2:${id}`);
```

## 3. Add jitter to TTLs

Write a thousand keys at once with a 300-second TTL and they all expire together, sending a thousand queries to the database in the same second. Add a random offset:

```ts
const ttl = 300 + Math.floor(Math.random() * 60);
```

## 4. Prevent cache stampedes

When a popular key expires, hundreds of requests hit the database at once. Options:

- **Single flight:** within one process, attach waiting requests to one Promise.
- **Distributed lock:** let only one process recompute with `SET lock:key 1 NX EX 10`; others wait briefly and read again.
- **Early refresh:** refresh in the background in the last seconds before the TTL ends, so users always read from cache.

```ts
const inflight = new Map<string, Promise<unknown>>();
function once<T>(key: string, fn: () => Promise<T>): Promise<T> {
  if (!inflight.has(key)) inflight.set(key, fn().finally(() => inflight.delete(key)));
  return inflight.get(key) as Promise<T>;
}
```

## 5. Memory limit and eviction policy

Set `maxmemory` and choose `allkeys-lru` or `allkeys-lfu` for a cache-only Redis. An unbounded Redis will one day fill up and start rejecting writes. Don't keep data that mustn't be lost, such as queues or sessions, on the same instance.

## 6. What not to cache

- User-specific, permission-dependent data without the user ID in the key.
- Data that must be accurate to the second (balances, stock) with long TTLs.
- Queries that are already fast; a cache is always extra complexity.

## 7. Measure

Track hit rate, average latency and memory use. If the hit rate is below 50%, either the key design is wrong or that data isn't a good fit for caching. To see how it behaves under load, run the scenarios from the [load testing guide](/en/blog/load-testing-guide/) with and without the cache.

## Conclusion

Start with cache-aside, version your keys, add jitter to TTLs, use single flight against stampedes and set a memory limit. Built right, a cache cuts database load dramatically; built wrong, it becomes a layer that hides bugs. For packaging the app itself, see [Node.js Docker multi-stage builds](/en/blog/nodejs-docker-multi-stage-build/).

---

About the author: [Sander Yazıcıoğlu](https://sanderyaz.com/en/about/). Sander Yazıcıoğlu is a Senior Full-Stack Developer in Istanbul. At LiveTesting he builds the backend, frontend, realtime systems and Appium automation of a real-device testing platform; before that he built enterprise Angular apps at Testinium and Loadium.
