Redis caching in NestJS without serving stale data
Caching is the fastest way to make a slow screen fast, and the fastest way to show a manager last week’s numbers. Both come from the same few lines of code. This is how I add Redis caching to NestJS apps so it helps without causing confusing bugs.
One rule first: fix the query, then cache it. A cache in front of a slow query only hides the problem until the cache expires. If you haven’t yet, check the query with explain() and the right index.
The pattern: cache-aside
Cache-aside is the simplest pattern and the one I use almost everywhere:
- Look for the result in Redis.
- If it’s there, return it.
- If not, compute it from the database, store it in Redis with an expiry time, and return it.
- When the underlying data changes, delete the cached copy.
A small cache service
NestJS has a built-in cache module, but I prefer a thin service over ioredis directly. It is easy to read, and it gives you full control over keys and expiry.
// cache.service.ts
import { Injectable, OnModuleDestroy } from '@nestjs/common';
import Redis from 'ioredis';
@Injectable()
export class CacheService implements OnModuleDestroy {
private redis = new Redis(process.env.REDIS_URL ?? 'redis://redis:6379');
/** Return the cached value, or compute it, cache it for ttlSeconds and return it. */
async wrap<T>(key: string, ttlSeconds: number, compute: () => Promise<T>): Promise<T> {
const hit = await this.redis.get(key);
if (hit !== null) return JSON.parse(hit) as T;
const value = await compute();
await this.redis.set(key, JSON.stringify(value), 'EX', ttlSeconds);
return value;
}
async del(...keys: string[]) {
if (keys.length) await this.redis.del(...keys);
}
onModuleDestroy() {
this.redis.disconnect();
}
}
Using it in a service:
// reports.service.ts
async monthlySales(companyId: string, month: string) {
return this.cache.wrap(`report:sales:${companyId}:${month}`, 600, () =>
this.orders.aggregate([
{ $match: { companyId, month } },
{ $group: { _id: '$productId', qty: { $sum: '$qty' }, total: { $sum: '$total' } } },
]),
);
}
Name keys so you can find them again
A good key says what the data is and whose it is: report:sales:<companyId>:<month>, product:<id>, user:<id>:permissions. Always include the tenant or company ID in multi-company systems. Forgetting it is how one client sees another client’s numbers, which is the worst caching bug there is.
Choosing expiry times
Every cached value should expire, even if you also delete it on changes. Expiry is your safety net when a code path forgets to clear the cache.
| Data | Expiry I start with |
|---|---|
| Settings, product catalogue, permissions | 10 to 60 minutes, cleared on change |
| Dashboards and reports for past periods | Hours (past months rarely change) |
| Today’s dashboard | 1 to 5 minutes |
| Anything involving stock levels or money balances | Usually don’t cache, or seconds at most |
Ask the people who use the screen how fresh it needs to be. “Updated every five minutes” is perfectly fine for most dashboards, as long as everyone knows. Showing the time the data was calculated on screen avoids a lot of confusion.
Clear the cache when data changes
When an order is created or edited, delete the reports it affects:
// orders.service.ts
async create(dto: CreateOrderDto) {
const order = await this.orders.create(dto);
await this.cache.del(`report:sales:${order.companyId}:${order.month}`);
return order;
}
Delete rather than update the cached value. The next read rebuilds it from the database, which is always correct, while trying to patch a cached report in place is a reliable source of subtle bugs.
If one change affects many keys, put them in a Redis set as you create them, or use a version number in the key (report:v7:...) and increase the version to invalidate everything at once. Avoid KEYS report:* in production: it blocks Redis while it scans. Use SCAN if you really must search.
Stop the stampede
When a popular key expires, every request that arrives in the next second finds the cache empty and runs the expensive query at the same time. On a busy dashboard that can be dozens of identical heavy queries hitting the database at once.
Inside one Node process, the simplest fix is to share the in-flight promise, so concurrent requests wait for the same computation:
private inflight = new Map<string, Promise<unknown>>();
async wrap<T>(key: string, ttlSeconds: number, compute: () => Promise<T>): Promise<T> {
const hit = await this.redis.get(key);
if (hit !== null) return JSON.parse(hit) as T;
let pending = this.inflight.get(key) as Promise<T> | undefined;
if (!pending) {
pending = compute()
.then(async (value) => {
await this.redis.set(key, JSON.stringify(value), 'EX', ttlSeconds);
return value;
})
.finally(() => this.inflight.delete(key));
this.inflight.set(key, pending);
}
return pending;
}
With several app instances, add a short Redis lock (SET lock:<key> 1 NX EX 10) so only one instance rebuilds the value while the others briefly wait or serve the old copy. For most single-server business apps, the in-process version is enough.
Things to watch
- Dates come back as strings.
JSON.parsedoesn’t restoreDateobjects. Convert them where you use them, or store timestamps as numbers. - Set a memory limit. In
redis.conf(or the container command), setmaxmemoryandmaxmemory-policy allkeys-lruif Redis is only a cache, so it evicts old keys instead of running out of memory. If you also use Redis for queues or sessions, usevolatile-lruso only keys with an expiry are evicted. - The app must survive Redis being down. Wrap cache reads in a try/catch and fall back to the database. A cache outage should make the app slower, not broken.
Summary
- Fix the query first, then cache
- Cache-aside: read, compute on miss, store with expiry, delete on change
- Include the company or tenant ID in every key
- Always set an expiry, and pick it with the people who use the screen
- Share in-flight work to prevent stampedes
- Treat Redis as optional: the app should work without it