0
0
NestJSframework~10 mins

Custom cache keys in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom cache keys
Request received
Check cache with key
Return
Store result with custom key
Return
When a request comes, NestJS checks the cache using a custom key. If found, it returns cached data. Otherwise, it runs the handler, caches the result with the custom key, then returns it.
Execution Sample
NestJS
import { CacheInterceptor, CacheKey, CacheTTL, Controller, Get, UseInterceptors } from '@nestjs/common';

@Controller('items')
@UseInterceptors(CacheInterceptor)
export class ItemsController {
  @Get()
  @CacheKey('custom-items-key')
  @CacheTTL(60)
  findAll() {
    return ['item1', 'item2'];
  }
}
This code caches the response of findAll() using a custom cache key 'custom-items-key' for 60 seconds.
Execution Table
StepActionCache Key UsedCache Hit?Result Returned
1Request to GET /itemscustom-items-keyNoExecute findAll()
2Run findAll()custom-items-keyNo['item1', 'item2']
3Store result in cachecustom-items-keyN/ACache updated
4Return responsecustom-items-keyN/A['item1', 'item2']
5Next request to GET /itemscustom-items-keyYes['item1', 'item2']
💡 Cache hit on step 5 returns cached data, skipping handler execution.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5
cacheemptyempty{ 'custom-items-key': ['item1', 'item2'] }{ 'custom-items-key': ['item1', 'item2'] }
responsenone['item1', 'item2']['item1', 'item2']['item1', 'item2']
Key Moments - 2 Insights
Why does the cache key need to be unique and custom?
Because the cache uses the key to find stored data. If keys are not unique, different requests might return wrong cached data. See execution_table step 1 and 5 where 'custom-items-key' is used.
What happens if the cache key is missing or default?
NestJS uses a default key based on method and parameters, which might cause unexpected cache hits or misses. Custom keys give control, as shown in execution_table step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the cache key used at step 2?
Aitems-findAll
Bdefault-key
Ccustom-items-key
Dno key
💡 Hint
Check the 'Cache Key Used' column at step 2 in the execution_table.
At which step does the cache get updated with the new data?
AStep 1
BStep 3
CStep 4
DStep 5
💡 Hint
Look for the action 'Store result in cache' in the execution_table.
If the cache key was not custom but default, what might change in the execution?
ACache hit might occur for wrong requests
BCache would never be used
CCache key would be 'custom-items-key' anyway
DCache TTL would be ignored
💡 Hint
Refer to key_moments about why unique keys matter.
Concept Snapshot
NestJS custom cache keys:
- Use @CacheKey('your-key') to set a unique cache key
- Cache stores and retrieves data by this key
- Ensures correct cached data per request
- Combine with @CacheTTL(seconds) to set cache duration
- Helps avoid cache collisions and stale data
Full Transcript
When a request comes to a NestJS controller method with caching, the framework checks if the response is already stored in cache using a key. By default, NestJS generates a key based on method and parameters, but you can set a custom key using @CacheKey decorator. This custom key is used to check the cache. If the cache has data for that key, it returns it immediately. Otherwise, it runs the method, stores the result in cache with the custom key, and returns the data. This process ensures that cached data is correctly matched to requests, avoiding wrong data returns. The cache duration can be set with @CacheTTL. The execution table shows the steps: first request misses cache, runs method, stores result; next request hits cache and returns stored data. Variables like cache content and response change accordingly. Beginners often wonder why custom keys matter: they prevent cache collisions and ensure correct data is served. If keys are not unique, different requests might get wrong cached results. This visual trace helps understand how custom cache keys control caching behavior in NestJS.