Caching stores data temporarily so your app can get it faster next time. This makes your app respond quicker and feel smoother.
Why caching reduces response latency in NestJS
import { CacheModule, Module } from '@nestjs/common'; @Module({ imports: [CacheModule.register({ ttl: 5 })], // ttl is time to live in seconds }) export class AppModule {}
ttl means how long the data stays in cache before it is refreshed.
CacheModule helps NestJS store and retrieve cached data easily.
findAll method so repeated calls return cached data quickly.import { CacheInterceptor, Controller, Get, UseInterceptors } from '@nestjs/common'; @Controller('items') @UseInterceptors(CacheInterceptor) export class ItemsController { @Get() findAll() { return ['item1', 'item2', 'item3']; } }
import { CacheModule, Module } from '@nestjs/common'; @Module({ imports: [CacheModule.register({ ttl: 10 })], }) export class AppModule {}
This NestJS app counts visitors but caches the greeting for 30 seconds. So, repeated requests within 30 seconds show the same visitor number, making responses faster.
import { CacheModule, CacheInterceptor, Controller, Get, Module, UseInterceptors } from '@nestjs/common'; @Controller('greet') @UseInterceptors(CacheInterceptor) export class GreetController { private count = 0; @Get() sayHello() { this.count++; return `Hello! You are visitor number ${this.count}`; } } @Module({ imports: [CacheModule.register({ ttl: 30 })], controllers: [GreetController], }) export class AppModule {}
Caching improves speed but cached data might be outdated until refreshed.
Choose cache duration (ttl) wisely based on how fresh your data needs to be.
Use caching for data that does not change every second to get the best benefit.
Caching stores data temporarily to speed up repeated requests.
It reduces the time your app waits for data from slow sources.
In NestJS, CacheModule and CacheInterceptor make caching easy to add.
Practice
Solution
Step 1: Understand what caching does
Caching temporarily stores data that is requested often, so the system doesn't have to fetch it repeatedly from slow sources like databases or APIs.Step 2: Connect caching to response time
By avoiding repeated slow operations, caching reduces the time the app waits before sending a response, thus lowering latency.Final Answer:
Because it stores frequently requested data temporarily to avoid repeated slow operations -> Option AQuick Check:
Caching stores data to speed up responses = A [OK]
- Thinking caching increases database size
- Believing caching disables network requests
- Confusing caching with data compression
Solution
Step 1: Identify the correct NestJS package for CacheModule
CacheModule is part of the '@nestjs/common' package, so it should be imported from there.Step 2: Verify other options
CacheInterceptor is from '@nestjs/common', not '@nestjs/core'; '@nestjs/cache' and CacheService do not exist as valid imports.Final Answer:
import { CacheModule } from '@nestjs/common'; -> Option AQuick Check:
CacheModule import is from '@nestjs/common' = D [OK]
- Importing CacheModule from wrong package
- Confusing CacheInterceptor import location
- Using non-existent CacheService import
@UseInterceptors(CacheInterceptor)
@Get('data')
async getData() {
console.log('Fetching data...');
return { value: 42 };
}What will happen on the second request to
/data?Solution
Step 1: Understand CacheInterceptor behavior
CacheInterceptor caches the response of the first request and returns it directly on subsequent requests without calling the method again.Step 2: Predict console output on second request
Since the method is not called again, 'Fetching data...' is not logged on the second request, but the cached response is returned.Final Answer:
The console does not log anything and returns cached { value: 42 } -> Option CQuick Check:
CacheInterceptor returns cached data without method call = C [OK]
- Assuming method runs every time
- Expecting cache errors on normal use
- Thinking console logs twice per request
@Module({
imports: [CacheModule.register()],
controllers: [AppController],
providers: [AppService, CacheInterceptor],
})
export class AppModule {}What is the main problem here?
Solution
Step 1: Check how to provide CacheInterceptor globally
CacheInterceptor must be provided using the special token APP_INTERCEPTOR to work as a global interceptor.Step 2: Identify the error in providers array
Providing CacheInterceptor directly in providers does not activate it globally; it needs to be wrapped with APP_INTERCEPTOR.Final Answer:
CacheInterceptor should be provided using APP_INTERCEPTOR token, not directly -> Option BQuick Check:
Use APP_INTERCEPTOR token to provide CacheInterceptor = B [OK]
- Providing CacheInterceptor directly in providers
- Thinking CacheModule always needs cache store option
- Importing CacheModule from wrong package
Solution
Step 1: Understand selective caching needs
To cache only premium users, caching logic must distinguish user types and avoid caching non-premium data.Step 2: Apply custom cache key and conditional caching
Using CacheInterceptor with a custom cache key including user type allows caching premium users separately and skipping others.Step 3: Evaluate other options
Caching all users wastes resources; disabling caching loses latency benefits; global TTL applies to all users, not selective.Final Answer:
Use CacheInterceptor with a custom cache key that includes user type and skip caching for non-premium users -> Option DQuick Check:
Selective caching with custom keys reduces latency best = A [OK]
- Caching all data without filtering
- Disabling caching completely
- Using global TTL without user distinction
Ready to prove it?
Pass the test and this pattern moves unknown
