What if you could speed up your app with just one simple tag above your functions?
Why Cache decorators in NestJS? - Purpose & Use Cases
Imagine you have a web app that fetches user data from a database every time someone visits their profile page.
Each visit triggers the same slow database query again and again.
Manually adding caching means writing extra code everywhere to check if data is already saved.
This makes your code messy, hard to maintain, and easy to forget.
Also, you risk serving outdated data or missing cache updates.
Cache decorators let you add caching with a simple tag above your functions.
This keeps your code clean and automatically stores and retrieves data from cache.
You don't have to write repetitive cache logic yourself.
async getUser(id) {
const cached = await cache.get(id);
if (cached) return cached;
const user = await db.findUser(id);
await cache.set(id, user);
return user;
}@Cacheable()
async getUser(id) {
return await db.findUser(id);
}You can easily speed up your app by caching results without cluttering your code.
When many users view the same product page, cache decorators serve the stored product info instantly instead of querying the database each time.
Manual caching adds repetitive, error-prone code.
Cache decorators simplify caching by adding it declaratively.
This keeps code clean and improves app speed automatically.
Practice
@Cacheable in a NestJS service method?Solution
Step 1: Understand cache decorator role
Cache decorators like@Cacheablesave the output of a method so it can be reused without recalculating.Step 2: Identify the benefit
This reuse speeds up responses by avoiding repeated work.Final Answer:
To store the method's result and reuse it for faster responses -> Option AQuick Check:
Cache decorators improve speed by storing results [OK]
- Thinking cache decorators log method calls
- Confusing cache with retry logic
- Assuming cache encrypts data
Solution
Step 1: Recall correct decorator syntax
The@Cacheabledecorator accepts an options object withttlas a key.Step 2: Identify correct object syntax
Correct syntax uses curly braces and colon:{ ttl: 10 }.Final Answer:
@Cacheable({ ttl: 10 }) -> Option AQuick Check:
Use object with ttl key inside @Cacheable [OK]
- Using parentheses with assignment inside decorator
- Using @CacheEvict to set TTL
- Using colon without braces
@Cacheable({ ttl: 5 })
async getData() {
console.log('Fetching data');
return 'data';
}What will be printed if
getData() is called three times within 5 seconds?Solution
Step 1: Understand caching effect on method calls
The first call runs the method and caches the result for 5 seconds.Step 2: Analyze subsequent calls within TTL
Calls within 5 seconds return cached result without running method, so no console log.Final Answer:
Fetching data (printed once) -> Option BQuick Check:
Cache prevents repeated method execution within TTL [OK]
- Assuming method runs every call ignoring cache
- Thinking cache disables method completely
- Confusing TTL with infinite caching
@Cacheable({ ttl: 10 })
async fetchData() {
return await this.httpService.get('url');
}
@CacheEvict()
clearCache() {
// clears cache
}What is the main issue with the
@CacheEvict usage here?Solution
Step 1: Understand
@CacheEvictpurpose@CacheEvictclears cached data, but needs to know which cache entry or key to clear.Step 2: Identify missing key or target
The code does not specify a key or target, so it cannot clear the intended cache.Final Answer:
It lacks a key or target to specify which cache to clear -> Option CQuick Check:
@CacheEvictneeds key/target to clear cache [OK]
- Using CacheEvict without specifying key
- Confusing CacheEvict with Cacheable
- Assuming async required for CacheEvict
Solution
Step 1: Understand caching and eviction roles
@Cacheablecaches method results;@CacheEvictclears cache entries.Step 2: Apply decorators to correct methods
Cache the fetch method result, and clear that cache when update method runs using@CacheEvictwith matching keys.Final Answer:
Use @Cacheable on the fetch method and @CacheEvict on the update method with matching cache keys -> Option DQuick Check:
Cache fetch, evict on update with matching keys [OK]
- Evicting cache on fetch method instead of update
- Caching update method results unnecessarily
- Not matching cache keys between decorators
Ready to prove it?
Pass the test and this pattern moves unknown
