Bird
Raised Fist0
NestJSframework~10 mins

Cache interceptor in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Cache interceptor
Request received
↓
Check cache for response
↓
Return cached
↓
Send cached
↓
Send response
The cache interceptor checks if a response is cached for a request. If yes, it returns cached data. If no, it calls the handler, caches the result, then returns it.
Execution Sample
NestJS
import { CacheInterceptor, Controller, Get, UseInterceptors } from '@nestjs/common';

@Controller('items')
@UseInterceptors(CacheInterceptor)
export class ItemsController {
  @Get()
  findAll() { return ['item1', 'item2']; }
}
This code uses CacheInterceptor to cache the response of the findAll method in ItemsController.
Execution Table
StepActionCache Check ResultHandler CalledCache UpdatedResponse Sent
1Request to GET /itemsNo cache foundYesCache stores ['item1', 'item2']['item1', 'item2'] sent
2Request to GET /items againCache hitNoNo changeCached ['item1', 'item2'] sent
3Request to GET /items after cache expiryNo cache foundYesCache stores ['item1', 'item2']['item1', 'item2'] sent
💡 Execution stops after sending response to client.
Variable Tracker
VariableStartAfter 1After 2After 3
cacheempty['item1', 'item2']['item1', 'item2']['item1', 'item2'] (refreshed)
handlerCalledfalsetruefalsetrue
responseSentnone['item1', 'item2']['item1', 'item2']['item1', 'item2']
Key Moments - 2 Insights
Why does the handler not run on the second request?
Because the cache check found a stored response (see execution_table step 2), so the interceptor returns cached data without calling the handler.
What happens when the cache expires?
The cache is empty again (step 3), so the handler runs to get fresh data, which is then stored in cache for future requests.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'handlerCalled' at step 2?
Atrue
Bundefined
Cfalse
Dnull
💡 Hint
Check the 'handlerCalled' row in variable_tracker at 'After 2' column.
At which step does the cache get updated with new data?
AStep 1
BStep 2
CStep 3
DNo step updates cache
💡 Hint
Look at the 'Cache Updated' column in execution_table.
If the cache never expires, which step would the handler never be called?
AStep 1
BStep 3
CStep 2
DHandler always called
💡 Hint
Refer to 'handlerCalled' in variable_tracker and cache expiry explanation in key_moments.
Concept Snapshot
Cache Interceptor in NestJS:
- Checks cache before calling handler
- Returns cached response if available
- Calls handler and caches result if not
- Improves performance by avoiding repeated work
- Use @UseInterceptors(CacheInterceptor) on controllers or routes
Full Transcript
The Cache Interceptor in NestJS works by intercepting incoming requests. When a request arrives, it first checks if a cached response exists. If yes, it returns that cached response immediately without calling the handler method. If no cached response is found, it calls the handler to get fresh data, stores this data in the cache, and then sends it back to the client. This process repeats for each request. When the cache expires, the interceptor calls the handler again to refresh the cache. This mechanism helps improve performance by reducing repeated processing for the same requests.

Practice

(1/5)
1. What is the main purpose of the CacheInterceptor in NestJS?
easy
A. To handle authentication and authorization
B. To store responses and speed up repeated requests
C. To log all incoming requests
D. To format response data before sending

Solution

  1. Step 1: Understand the role of CacheInterceptor

    The CacheInterceptor caches HTTP responses to avoid recomputing them on repeated requests.
  2. Step 2: Compare with other options

    Logging, authentication, and formatting are handled by other interceptors or middleware, not CacheInterceptor.
  3. Final Answer:

    To store responses and speed up repeated requests -> Option B
  4. Quick Check:

    CacheInterceptor caches responses = C [OK]
Hint: CacheInterceptor caches responses to speed up requests [OK]
Common Mistakes:
  • Confusing CacheInterceptor with logging interceptors
  • Thinking it handles security tasks
  • Assuming it formats data
2. Which of the following is the correct way to apply the CacheInterceptor to a controller method in NestJS?
easy
A. Add CacheInterceptor in the constructor of the controller
B. @Cacheable() decorator on the method
C. @UseInterceptors(CacheInterceptor) above the method
D. Use @CacheInterceptor() as a method parameter

Solution

  1. Step 1: Recall how to apply interceptors in NestJS

    Interceptors are applied using the @UseInterceptors() decorator above methods or controllers.
  2. Step 2: Check each option

    Only @UseInterceptors(CacheInterceptor) above the method uses the correct decorator syntax. Options B, C, and D are invalid or do not exist in NestJS.
  3. Final Answer:

    @UseInterceptors(CacheInterceptor) above the method -> Option C
  4. Quick Check:

    UseInterceptors decorator = A [OK]
Hint: Use @UseInterceptors(CacheInterceptor) to apply caching [OK]
Common Mistakes:
  • Using non-existent @Cacheable decorator
  • Trying to inject interceptor in constructor
  • Passing interceptor as method parameter
3. Given this code snippet, what will be the output on the second request to /hello?
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';

@Controller()
export class HelloController {
  private count = 0;

  @UseInterceptors(CacheInterceptor)
  @Get('hello')
  getHello() {
    this.count++;
    return `Hello count: ${this.count}`;
  }
}
medium
A. "Hello count: 1" first request, "Hello count: 2" second request
B. Error because count is private
C. "Hello count: 0" on both requests
D. "Hello count: 1" on first and second request

Solution

  1. Step 1: Understand CacheInterceptor behavior

    CacheInterceptor caches the response of the first request and returns it for subsequent requests without calling the method again.
  2. Step 2: Analyze the count variable increment

    On the first request, count increments to 1 and returns "Hello count: 1". On the second request, the cached response is returned, so count does not increment again.
  3. Final Answer:

    "Hello count: 1" on first and second request -> Option D
  4. Quick Check:

    Cache returns cached response = B [OK]
Hint: CacheInterceptor returns cached response, method not re-executed [OK]
Common Mistakes:
  • Assuming count increments on every request
  • Thinking private variables cause errors here
  • Ignoring caching effect on method execution
4. Identify the error in this NestJS CacheInterceptor usage:
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';

@Controller()
export class TestController {
  @UseInterceptors(CacheInterceptor())
  @Get('test')
  test() {
    return 'Test response';
  }
}
medium
A. CacheInterceptor should not be called as a function
B. Missing CacheModule import in the controller
C. Method test must be async to use CacheInterceptor
D. CacheInterceptor must be applied globally, not per method

Solution

  1. Step 1: Check how CacheInterceptor is applied

    CacheInterceptor is a class, not a function, so it should be passed without parentheses to @UseInterceptors().
  2. Step 2: Verify other options

    CacheModule import is required but not shown here (not an error in this snippet). Method does not need to be async. CacheInterceptor can be applied per method.
  3. Final Answer:

    CacheInterceptor should not be called as a function -> Option A
  4. Quick Check:

    Use class name without () = A [OK]
Hint: Pass CacheInterceptor class, not call it as function [OK]
Common Mistakes:
  • Calling CacheInterceptor with parentheses
  • Assuming method must be async
  • Thinking CacheModule import error here
5. You want to customize the cache key for a route in NestJS using CacheInterceptor. Which approach correctly achieves this?
hard
A. Extend CacheInterceptor and override the trackBy method to return a custom key
B. Pass a custom key string directly to @UseInterceptors(CacheInterceptor)
C. Set a custom key in the controller constructor
D. Use @CacheKey('customKey') decorator on the method

Solution

  1. Step 1: Understand how to customize cache keys

    CacheInterceptor allows customization by extending it and overriding the trackBy method to define how keys are generated.
  2. Step 2: Evaluate other options

    Passing a string to @UseInterceptors() is invalid. Setting keys in constructor or using @CacheKey decorator does not exist in NestJS.
  3. Final Answer:

    Extend CacheInterceptor and override the trackBy method to return a custom key -> Option A
  4. Quick Check:

    Override trackBy method = D [OK]
Hint: Override trackBy method in extended CacheInterceptor [OK]
Common Mistakes:
  • Trying to pass key directly to decorator
  • Using non-existent @CacheKey decorator
  • Setting keys in constructor instead of method
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard