No. 41Backend9 min read2,296 words
Redis caching patterns: a practical guide for web apps
A practical guide to Redis caching for Node and TypeScript apps: cache-aside, TTLs, invalidation, stampede protection and the production settings to get right.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways ยท 05
The short version
- 01Cache-aside (check Redis, load from the database on a miss, write the result back with a TTL) is the right default pattern for most web apps.
- 02Every cache key needs a TTL; start with time-based expiry you can tolerate and add explicit invalidation only where staleness actually hurts users.
- 03Invalidate by deleting keys after the database write commits, and keep TTLs as a backstop, because a concurrent reader can still write back a stale value.
- 04Protect hot keys from cache stampedes with a short lock using SET NX and a unique token, or refresh them early in the background before they expire.
- 05For a pure cache, set maxmemory with an allkeys eviction policy, treat Redis errors as cache misses, and fix slow queries with indexes before caching them.
On this page ยท 10
Redis caching works best with one default pattern: cache-aside, where your code checks Redis first, loads from the database on a miss, and writes the result back with a time-to-live (TTL). Add explicit invalidation only for data where staleness hurts, protect your hottest keys from stampedes, configure an eviction policy, and always let a Redis failure fall back to the database. Treat the cache as a fast, forgetful copy of the truth, never the truth itself.
Caching is the part of backend work where the wins are obvious and the bugs are sneaky. A cache can turn an expensive query into a memory lookup, right up until it serves a stale price to a customer or overloads your database the moment a hot key expires. This is a practical walkthrough of Redis caching in a Node and TypeScript app, with the patterns that hold up in production and the traps that catch most teams.
When you actually need a Redis cache
Redis is an in-memory data store. It is fast because it keeps data in RAM and speaks a small, predictable protocol. For caching, that is mostly all you need: set a key, read a key, give it an expiry. (Valkey, the open-source fork created after Redis changed its licence in 2024, speaks the same protocol, so everything here applies to it too.)
Before you reach for it, be honest about whether you need it. If a Postgres query is slow because it is missing an index, fix the index. A cache layered on a bad query hides the problem and adds a second source of truth you now have to keep in sync. Redis earns its place when data is expensive to compute or fetch, read far more often than it is written, and can tolerate being slightly out of date.
| Good cache candidates | Poor cache candidates |
|---|---|
| Product and content listings | Account balances at the moment of payment |
| A user's resolved permission set | Stock levels during checkout |
| Aggregations that scan many rows | Data written as often as it is read |
| Responses from slow third-party APIs | Anything that must be transactionally correct on every read |
| Expensive rendered fragments | Data that is already fast with a proper index |
Also check what your framework already does. In a Next.js app, rendered pages and fetch results can be cached by the framework itself, which we explain in Next.js caching, finally explained. Redis is the right tool for data your own code needs to share across requests, instances and background workers.
Caching patterns compared
| Pattern | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Cache-aside (lazy loading) | App reads cache; on miss, loads from DB and populates | Simple; only caches what is read; survives cache loss | First request after expiry is slow; stale reads possible |
| Write-through | App writes to DB and cache together | Reads are always warm | Caches data nobody reads; two writes per update |
| Write-behind | App writes to cache; cache flushes to DB later | Very fast writes | Risk of data loss; complex; rarely right for web apps |
| Refresh-ahead | Hot keys rebuilt in the background before expiry | No misses on hot keys | More machinery; only worth it for a few keys |
Cache-aside is the right default. The rest of this guide builds on it.
The cache-aside pattern in TypeScript
Check the cache first. On a miss, load from the database, write the result back with a TTL, and return it. Here is a typed helper using ioredis. The generic getOrSet is the workhorse you will reuse everywhere.
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL!, {
maxRetriesPerRequest: 1,
commandTimeout: 200, // ms: a slow cache should not stall the request
});
async function getOrSet<T>(
key: string,
ttlSeconds: number,
loader: () => Promise<T>,
): Promise<T> {
const cached = await safeGet(key);
if (cached !== null) {
return JSON.parse(cached) as T;
}
const fresh = await loader();
// Add up to 10% jitter so keys written together do not all expire together.
const ttl = Math.round(ttlSeconds * (1 + Math.random() * 0.1));
await redis.set(key, JSON.stringify(fresh), "EX", ttl).catch(() => {});
return fresh;
}
async function safeGet(key: string): Promise<string | null> {
try {
return await redis.get(key);
} catch {
return null; // Treat any cache error as a miss.
}
}
// Usage: cache a product for 5 minutes.
async function getProduct(id: string) {
return getOrSet(`product:v1:${id}`, 300, () =>
db.product.findUniqueOrThrow({ where: { id } }),
);
}A few things in that block are doing real work:
- Always set a TTL. The
SETcommand takesEXin the same call, so there is no window where a key exists without an expiry. A cache without expiry is a memory leak with extra steps. - Check for
nullexplicitly, not truthiness, because an empty string or zero is a valid cached value. - Add TTL jitter. Keys cached together during a deploy or a traffic spike otherwise expire together, and you get a burst of misses.
- Fail soft. A short command timeout plus catching errors means a slow or down Redis degrades to direct database reads instead of 500s.
- Version the key. The
v1segment lets you change the cached shape on deploy without old and new code reading each other's data.
Key naming matters more than it looks
Use a consistent, colon-separated scheme: product:v1:123, user:42:permissions, tenant:7:dashboard:stats. The prefix tells you what the key is, makes debugging with redis-cli --scan --pattern 'product:*' sane, and gives you a clean unit for invalidation. In a multi-tenant app, put the tenant ID in every key so one customer's data can never be served to another. Decide the convention early and write it down, because renaming keys across a running system is no fun.
What to store
Store the smallest useful shape, not whole ORM objects with every relation attached. Large values cost memory, network time and serialisation time on every read. For objects you update field by field, a Redis hash can be more efficient than one JSON string, but JSON keeps reads and writes symmetric and is the simpler default.
Cache invalidation, the genuinely hard part
The joke about the two hard problems in computing (cache invalidation and naming things) lands because it is true. The moment the underlying data changes, the cache is wrong, and you have to decide how wrong you can stand to be.
Two strategies cover most cases.
TTL-based expiry is the simplest: pick a TTL you can tolerate and let the cache go stale within that window. If product descriptions can be five minutes out of date, a 300 second TTL means zero invalidation code. Reach for this first.
Explicit invalidation is for data that must update promptly after a write. Delete the key in the same code path that changes the source of truth, after the database write has committed:
async function updateProduct(id: string, data: Partial<Product>) {
const updated = await db.product.update({ where: { id }, data });
// Delete after the write commits, never before.
await redis.del(`product:v1:${id}`, `product:v1:${id}:related`);
return updated;
}Delete, do not update. Writing the new value into the cache from the write path invites races where two concurrent updates leave the older value cached. Deleting and letting the next read repopulate is simpler and safer.
There is still a small race worth knowing about: a reader loads the old row just before your update, your update commits and deletes the key, then the slow reader writes its stale value back. It is rare, which is why you keep a TTL on every key as a backstop even when you invalidate explicitly. For data where even that window is unacceptable, do not cache it.
Derived data is where invalidation breaks
A single product update might invalidate the product key, a category listing, a search result and a homepage block. If you cannot enumerate every dependent key, you have honest options:
- Tag related keys. Keep a Redis set of keys per entity and delete the whole set on change.
- Use a version counter. Store
catalog:versionand include it in every derived key. Incrementing it withINCRmakes every old key unreachable at once, and TTLs clean them up. - Lean on short TTLs so staleness heals itself.
Do not pretend you tracked every dependency when you did not.
Preventing a cache stampede
Here is the bug that takes down databases. A popular key expires. In the next few milliseconds, many concurrent requests all miss the cache, all run the expensive loader at once, and all hit Postgres together. The cache was protecting your database, and the instant it blinked, the database fell over. This stampede, or thundering herd, bites hardest exactly when traffic spikes.
The fix is a short-lived lock so only one request rebuilds the value while the rest wait briefly and read the fresh result. The lock needs a unique token, so a request whose lock expired does not delete a lock someone else now holds. Redis's own distributed locks guide describes this compare-and-delete pattern.
import { randomUUID } from "node:crypto";
const RELEASE = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
`;
async function getOrSetLocked<T>(
key: string,
ttlSeconds: number,
loader: () => Promise<T>,
): Promise<T> {
const cached = await safeGet(key);
if (cached !== null) return JSON.parse(cached) as T;
const lockKey = `lock:${key}`;
const token = randomUUID();
const gotLock = await redis.set(lockKey, token, "PX", 10_000, "NX");
if (!gotLock) {
// Someone else is rebuilding. Poll briefly for their result.
for (let i = 0; i < 10; i++) {
await new Promise((r) => setTimeout(r, 50));
const retry = await safeGet(key);
if (retry !== null) return JSON.parse(retry) as T;
}
return loader(); // Fallback: rebuild rather than hang.
}
try {
const fresh = await loader();
await redis.set(key, JSON.stringify(fresh), "EX", ttlSeconds);
return fresh;
} finally {
await redis.eval(RELEASE, 1, lockKey, token);
}
}This lock is a performance optimisation, not a correctness guarantee: if two requests occasionally both rebuild, nothing breaks. Never use a cache lock like this to protect money movement or anything that must happen exactly once; that belongs in database transactions and constraints.
Two complementary techniques:
- Request coalescing in process. Keep a map of in-flight promises per key, so concurrent misses on the same instance share one loader call. It costs nothing and removes most duplicate work before Redis is even involved.
- Refresh ahead for the hottest keys. Store a logical expiry inside the value and rebuild it in the background shortly before the real TTL hits, so readers never see a miss. Save this machinery for the handful of keys that warrant it, and do the refresh in a background job if it is expensive.
Caching the absence of data
A subtle source of load is the negative lookup. If getProduct("does-not-exist") always misses the cache and always hits the database, an attacker or a buggy client can bypass your cache by requesting nonsense IDs. Cache the miss too, with a short TTL and a sentinel value, so repeated lookups for missing data stay cheap. Pair it with rate limiting on endpoints that accept arbitrary IDs.
Redis caching in production: settings people skip
Set maxmemory and an eviction policy. For an instance used purely as a cache, an allkeys policy such as allkeys-lru or allkeys-lfu lets Redis drop the least valuable keys when memory fills instead of refusing writes. The eviction documentation explains each policy. Do not share that instance with a job queue or session store, which need noeviction so data is never silently dropped.
Treat Redis as unreliable in your code. It is a separate process that can be down, slow or restarting. The safeGet wrapper and command timeout above mean a Redis failure degrades to direct database calls. The cache is an optimisation, not a dependency you bet the request on.
Never use KEYS in production. It blocks the server while it walks every key. Use SCAN for debugging and tagged sets or version counters for invalidation.
Run it close to your app. A cache in another region can be slower than the database query it replaces.
Watch the numbers. INFO stats exposes keyspace_hits and keyspace_misses. A low or falling hit rate usually means TTLs are too short, keys are too granular, or you are caching things nobody reads twice. Track memory use and evictions too: steady evictions on a cache you thought was big enough mean it is not.
| Setting | Pure cache | Queue, sessions or rate limits |
|---|---|---|
maxmemory | Set it | Set it, with headroom |
| Eviction policy | allkeys-lru or allkeys-lfu | noeviction |
| Persistence | Optional | Required for queues and sessions; optional for rate limit counters |
| TTL on every key | Yes | Where the data model allows |
A Redis caching checklist
- Fix slow queries with indexes before caching them.
- Use cache-aside with a TTL on every key, plus jitter.
- Version and namespace keys, including the tenant ID where relevant.
- Invalidate by deleting after commit; keep TTLs as a backstop.
- Protect hot keys with coalescing, a tokened lock, or refresh-ahead.
- Cache misses with a short TTL.
- Configure
maxmemoryand an eviction policy that matches the instance's job. - Fail soft on Redis errors and monitor hit rate, memory and evictions.
A cache you can trust
Start with cache-aside and a TTL you can live with. Add explicit invalidation only where staleness actually hurts, guard your hottest keys against stampedes, cache misses as well as hits, and always let a Redis outage fall back to the database. Caching with Redis is not complicated once you treat it as what it is: a fast, forgetful copy of the truth, sitting in front of a database that does the real work, ideally Postgres.
Caching layers are a regular part of our performance engineering work. If your app is slow under load, or you want a second pair of eyes on a caching layer before it ships, get in touch.
FAQ ยท 05 questions
Frequently asked questions
What is Redis caching?
Redis caching means storing the results of expensive operations, such as database queries, API calls or rendered fragments, in Redis, an in-memory key-value store. Later requests read the stored copy from memory instead of repeating the work. Each entry usually has an expiry time so stale data eventually refreshes.
What is the difference between cache-aside and write-through caching?
With cache-aside, the application reads from the cache and, on a miss, loads from the database and populates the cache. With write-through, every write goes to the cache and the database together, so the cache is always populated. Cache-aside is simpler and only caches data that is actually read, which is why it is the common default.
What TTL should I use for Redis cache keys?
Use the longest expiry your users can tolerate seeing stale data for that specific item. Reference data like product descriptions can often live for minutes or hours, while prices, stock and permissions need shorter TTLs or explicit invalidation. Adding a little random jitter to TTLs stops many keys expiring at the same moment.
What is a cache stampede?
A cache stampede, or thundering herd, happens when a popular cache key expires and many concurrent requests miss at once, all running the same expensive database query simultaneously. It can overload the database at exactly the moment traffic is highest. Locks, request coalescing and early background refresh prevent it.
Should I use Redis or Next.js caching?
They solve different problems and work well together. Next.js caching stores rendered pages and fetch results inside the framework and its hosting layer. Redis is a shared data cache your application code controls directly, useful for query results, sessions, rate limits and data shared across services or background workers.