Lesson 22 / 33

Caching

Improve performance with in-memory or Redis caching.

Cache decorator

Use @Cacheable() or @Cache() to automatically cache method results.

import { Cacheable } from '@nestjs/cache-manager';

@Cacheable({ ttl: 300 }) // cache for 5 minutes
findAll() {
  return this.usersService.findAll();
}

Redis cache

Switch from in-memory to Redis by configuring the cache store.

import { CacheModule } from '@nestjs/cache-manager';
import type { RedisClientOptions } from 'redis';

CacheModule.register<RedisClientOptions>({
  isGlobal: true,
  store: 'redis',
  host: 'localhost',
  port: 6379
})