Lesson 22 / 34

Caching

Speed up responses with in-memory or Redis caching using CacheModule, CacheInterceptor and TTLs.

Cache decorator

Apply CacheInterceptor to cache GET responses, and tune it with @CacheKey() and @CacheTTL().

import { CacheInterceptor, CacheTTL } from '@nestjs/cache-manager';
import { UseInterceptors } from '@nestjs/common';

@UseInterceptors(CacheInterceptor)
@CacheTTL(300_000) // 5 minutes, in milliseconds (cache-manager v5+)
@Get()
findAll() {
  return this.usersService.findAll();
}

Redis cache

Register the cache module globally, then switch the store to Redis with a store package such as @keyv/redis.

import { CacheModule } from '@nestjs/cache-manager';
import { createKeyv } from '@keyv/redis';

CacheModule.registerAsync({
  isGlobal: true,
  useFactory: async () => ({
    stores: [createKeyv('redis://localhost:6379')],
    ttl: 60_000,
  }),
})

Quick check

Quick check: What happens to a `@UseInterceptors(CacheInterceptor)` GET route on the second identical request within the TTL?

  • The handler runs again and overwrites the cache
  • The cached response is returned without running the handler
  • A 304 is always returned
Answer

The cached response is returned without running the handler — Cache hits short-circuit the handler. Only GET responses are auto-cached.