Redis Caching in NestJS

By Abdelilah Ommane ยท Backend Developer

Short answer

Install @nestjs/cache-manager and ioredis, register CacheModule with a Redis store in AppModule, then inject Cache and use cache.get() / cache.set() around expensive reads. This cuts database load and response latency.

1. Install

npm i @nestjs/cache-manager cache-manager ioredis

2. Register the Redis store

import { CacheModule } from '@nestjs/cache-manager';
import { redisStore } from 'cache-manager/ioredis';

CacheModule.registerAsync({
  isGlobal: true,
  useFactory: async () => ({
    store: await redisStore({ host: 'localhost', port: 6379 }),
    ttl: 60,
  }),
})

3. Use it in a service

@Injectable()
export class ProductsService {
  constructor(@Inject(CACHE_MANAGER) private cache: Cache) {}

  async get(id: string) {
    const hit = await this.cache.get(`product:${id}`);
    if (hit) return hit;
    const product = await this.repo.findById(id);
    await this.cache.set(`product:${id}`, product, 60);
    return product;
  }
}

FAQ

When should I invalidate the cache?

On writes that change the cached data โ€” delete or overwrite the key in the same transaction path that updates the database, so reads never serve stale values.

Redis vs in-memory cache?

In-memory is per-instance and lost on restart; Redis is shared across instances and survives restarts, which is why it's the right choice for multi-instance or clustered deployments.

← All guides