Caching in NestJS can be achieved through two distinct approaches: the built-in CacheModule with CacheInterceptor, or manual integration with Redis via ioredis.
Built-in approach (CacheModule)
NestJS provides a store-agnostic caching layer via @nestjs/common:
- Import CacheModule.register() with a Redis store adapter (
cache-manager-redis-store). - Use
@UseInterceptors(CacheInterceptor)for automatic HTTP response caching on@Get()routes. - Customize per-endpoint with
@CacheKey()and@CacheTTL(). - Inject
CACHE_MANAGERfor manualget()/set()/del()/reset()operations.
Sources: How to add Redis cache to a NestJS app
Manual ioredis approach
For full control over Redis, build a custom service:
- Create a FactoryProvider Pattern to instantiate a singleton ioredis client.
- Layer a Redis Repository Pattern with Redis Prefix Key Naming for clean separation.
- Implement the Cache-aside Pattern in domain services: check cache → query DB on miss → populate cache.
- Use
OnModuleInit/OnModuleDestroylifecycle hooks for connection management. - Set appropriate TTL values per data type (10 min for tokens, 30 min for products, 1 day for reference data).
Sources: Using Redis Client in NestJS
Choosing an approach
| Factor | CacheModule | Manual ioredis |
|---|---|---|
| Boilerplate | Low | Medium-high |
| Redis feature access | Limited | Full |
| Decorator support | Yes | No |
| Backend portability | Yes | No |
| Testing | Built-in mocking | Manual mocking |
| Production readiness | Good for simple caching | Good for any Redis use case |