0
0
NestJSframework~10 mins

Cache decorators in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Cache decorators
Method call
Check cache for key
Return cached
Return value
Response sent
When a method with a cache decorator is called, it first checks if the result is cached. If yes, it returns cached data. Otherwise, it runs the method, caches the result, then returns it.
Execution Sample
NestJS
@Cacheable()
getData() {
  return fetchFromDb();
}
A method decorated to cache its result after fetching data once.
Execution Table
StepActionCache Key Exists?Method Executed?Cache Updated?Returned Value
1Call getData()NoYesYesData from DB
2Call getData() againYesNoNoData from DB
3Call getData() third timeYesNoNoData from DB
💡 After first call caches data, subsequent calls return cached data without executing method.
Variable Tracker
VariableStartAfter 1After 2After 3
cache{}{"getData": "Data from DB"}{"getData": "Data from DB"}{"getData": "Data from DB"}
methodResultundefined"Data from DB""Data from DB""Data from DB"
Key Moments - 2 Insights
Why does the method not run on the second call?
Because the cache already has the key from the first call, so the decorator returns cached data directly (see execution_table step 2).
What happens if the cache is empty?
The method runs normally, its result is stored in cache, then returned (see execution_table step 1).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is returned on the third call?
AData fetched fresh from DB
BUndefined
CCached Data
DError
💡 Hint
Check the 'Returned Value' column at step 3 in the execution_table.
At which step does the cache get updated?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Cache Updated?' column in the execution_table.
If the cache was cleared before the third call, what would happen?
AThrows an error
BMethod executes and cache updates again
CReturns cached data anyway
DReturns undefined
💡 Hint
Refer to the behavior in step 1 where cache is empty and method runs.
Concept Snapshot
Cache decorators in NestJS:
- Use @Cacheable() on methods
- On call, check cache for key
- If cached, return cached result
- Else, run method, cache result, return it
- Speeds up repeated calls by avoiding work
Full Transcript
Cache decorators in NestJS help store method results so repeated calls return cached data instead of running the method again. When a decorated method is called, it first checks if the cache has the result. If yes, it returns cached data immediately. If not, it runs the method, stores the result in cache, then returns it. This saves time and resources for repeated calls. The execution table shows the first call runs the method and caches the result. Later calls return cached data without running the method again. Variables track the cache content and method results over calls.