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.
Practice
Solution
Step 1: Understand in-memory cache scope
In-memory cache stores data only inside the app instance's memory, so it is not shared.Step 2: Understand Redis cache scope
Redis is a separate server that multiple app instances can connect to, sharing cached data.Final Answer:
Redis allows sharing cached data across multiple app instances. -> Option CQuick Check:
Redis cache is shared [OK]
- Thinking in-memory cache shares data between servers
- Believing Redis cache is local to one app instance
- Assuming Redis cache clears every second automatically
Solution
Step 1: Recall NestJS CacheModule syntax
CacheModule.register() is used to configure cache with options including store type and connection details.Step 2: Identify correct Redis store option
Using store: 'redis' with host and port is the correct way to set Redis cache in NestJS.Final Answer:
CacheModule.register({ store: 'redis', host: 'localhost', port: 6379 }) -> Option BQuick Check:
Use CacheModule.register with store: 'redis' [OK]
- Using non-existent methods like useRedis or registerRedis
- Confusing forRoot with register for cache setup
- Incorrect option keys like type instead of store
await cacheManager.set('key1', 'value1', { ttl: 5 });
const val1 = await cacheManager.get('key1');
await new Promise(r => setTimeout(r, 6000));
const val2 = await cacheManager.get('key1');
What will be the values of val1 and val2 respectively?Solution
Step 1: Understand TTL effect on cache
The key 'key1' is set with a TTL (time to live) of 5 seconds, so it expires after 5 seconds.Step 2: Analyze timing of gets
val1 is read immediately after setting, so it returns 'value1'. val2 is read after 6 seconds, after TTL expires, so it returns undefined.Final Answer:
'value1' and undefined -> Option AQuick Check:
TTL expires after 5s, val2 is undefined [OK]
- Expecting cached value to persist beyond TTL
- Ignoring async delay before second get
- Confusing immediate and delayed cache reads
CacheModule.register({
store: 'redis',
host: 'localhost',
port: '6379'
})
But your app throws a connection error. What is the likely cause?Solution
Step 1: Check data types in config
Port should be a number (6379), not a string ('6379'), or connection fails.Step 2: Validate other options
Host is valid, CacheModule.register supports Redis, password is optional if Redis has no auth.Final Answer:
The port should be a number, not a string. -> Option AQuick Check:
Port must be number type [OK]
- Passing port as string instead of number
- Assuming host option is invalid
- Thinking password is always required
Solution
Step 1: Use correct TTL option in set()
TTL must be passed as an object property { ttl: 600 } for 10 minutes (600 seconds).Step 2: Await both set and get calls
Both set and get are async, so await is needed to ensure completion and data retrieval.Final Answer:
await cacheManager.set('user_123', profile, { ttl: 600 }); const data = await cacheManager.get('user_123'); -> Option DQuick Check:
TTL as { ttl: 600 } and await both calls [OK]
- Passing TTL as a number directly instead of in object
- Not awaiting async cache get call
- Using wrong option name like expire instead of ttl
Ready to prove it?
Pass the test and this pattern moves unknown
