Cache stores help your app remember data temporarily to make it faster. Memory cache keeps data inside the app, Redis cache stores data outside the app for sharing.
Cache stores (memory, Redis) in NestJS
import { CacheModule } from '@nestjs/common'; import * as redisStore from 'cache-manager-redis-store'; // For memory cache CacheModule.register({ ttl: 5, // seconds max: 100, // max items }); // For Redis cache CacheModule.register({ store: redisStore, host: 'localhost', port: 6379, ttl: 10, });
Memory cache stores data inside your app process, so it resets when app restarts.
Redis cache stores data outside your app, so it can be shared and persists across restarts.
import { CacheModule } from '@nestjs/common'; @Module({ imports: [CacheModule.register({ ttl: 10 })], }) export class AppModule {}
import { CacheModule } from '@nestjs/common'; import * as redisStore from 'cache-manager-redis-store'; @Module({ imports: [ CacheModule.register({ store: redisStore, host: 'localhost', port: 6379, ttl: 20, }), ], }) export class AppModule {}
This example creates a simple controller with a counter. The CacheInterceptor caches the response for 5 seconds using Redis. If you call the /count endpoint multiple times within 5 seconds, it returns the same count without increasing.
import { Controller, Get, CacheInterceptor, UseInterceptors } from '@nestjs/common'; import { CacheModule, Module } from '@nestjs/common'; import * as redisStore from 'cache-manager-redis-store'; @Controller() @UseInterceptors(CacheInterceptor) export class AppController { private counter = 0; @Get('count') getCount() { this.counter++; return { count: this.counter }; } } @Module({ imports: [ CacheModule.register({ store: redisStore, host: 'localhost', port: 6379, ttl: 5, }), ], controllers: [AppController], }) export class AppModule {}
Memory cache is easy to set up but only works for single app instances.
Redis cache requires Redis server running but supports multiple app instances sharing cache.
Always set a TTL (time-to-live) to avoid stale data.
Cache stores speed up apps by saving data temporarily.
Memory cache is simple but local to one app instance.
Redis cache is shared and persistent, good for multiple servers.