Bird
Raised Fist0
NestJSframework~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using @CacheKey() in a NestJS service?
easy
A. To set the time duration for cache expiration
B. To clear all cached data automatically
C. To define a custom name for the cached data key
D. To disable caching for a method

Solution

  1. Step 1: Understand the role of @CacheKey()

    This decorator is used to specify a custom key name for the cached data instead of using a default or generated key.
  2. Step 2: Differentiate from other cache decorators

    @CacheTTL() sets cache duration, clearing cache is manual or by other methods, and disabling cache is not done by @CacheKey().
  3. Final Answer:

    To define a custom name for the cached data key -> Option C
  4. Quick Check:

    Custom cache key = @CacheKey() [OK]
Hint: Remember: CacheKey sets the cache name, TTL sets time [OK]
Common Mistakes:
  • Confusing @CacheKey() with @CacheTTL()
  • Thinking @CacheKey() clears cache
  • Assuming @CacheKey() disables caching
2. Which of the following is the correct way to apply a custom cache key to a method in NestJS?
easy
A. @CacheKey = 'myKey'\nasync getData() { return data; }
B. @CacheTTL(300)\nasync getData() { return data; }
C. cacheKey('myKey')\nasync getData() { return data; }
D. @CacheKey('myKey')\nasync getData() { return data; }

Solution

  1. Step 1: Identify correct decorator syntax

    In NestJS, decorators are applied with @DecoratorName(parameters) syntax above the method.
  2. Step 2: Check each option

    @CacheKey('myKey')\nasync getData() { return data; } uses @CacheKey('myKey') correctly. @CacheTTL(300)\nasync getData() { return data; } uses @CacheTTL which sets time, not key. @CacheKey = 'myKey'\nasync getData() { return data; } uses invalid assignment syntax. cacheKey('myKey')\nasync getData() { return data; } uses a non-existent function.
  3. Final Answer:

    @CacheKey('myKey')\nasync getData() { return data; } -> Option D
  4. Quick Check:

    Decorator syntax = @CacheKey('key') [OK]
Hint: Decorators start with @ and parentheses for parameters [OK]
Common Mistakes:
  • Using assignment instead of decorator syntax
  • Mixing @CacheKey with @CacheTTL
  • Calling cacheKey as a function instead of decorator
3. Given this NestJS method with caching:
@CacheKey('userList')
@CacheTTL(60)
async getUsers() {
  return ['Alice', 'Bob'];
}

What will be the cache key and TTL for the cached data?
medium
A. Key: 'getUsers', TTL: default (no TTL set)
B. Key: 'userList', TTL: 60 seconds
C. Key: 'userList', TTL: default (no TTL set)
D. Key: 'getUsers', TTL: 60 seconds

Solution

  1. Step 1: Identify the cache key from @CacheKey()

    The decorator @CacheKey('userList') sets the cache key explicitly to 'userList'.
  2. Step 2: Identify the TTL from @CacheTTL()

    The decorator @CacheTTL(60) sets the cache time to 60 seconds.
  3. Final Answer:

    Key: 'userList', TTL: 60 seconds -> Option B
  4. Quick Check:

    Custom key + TTL = 'userList' & 60s [OK]
Hint: @CacheKey sets key, @CacheTTL sets time in seconds [OK]
Common Mistakes:
  • Assuming method name is cache key when @CacheKey is used
  • Ignoring @CacheTTL and thinking no TTL is set
  • Confusing TTL units (seconds vs milliseconds)
4. You wrote this code:
@CacheKey('dataKey')
@CacheTTL('300')
async fetchData() {
  return 'info';
}

Why does the cache TTL not work as expected?
medium
A. Because TTL value should be a number, not a string
B. Because @CacheKey must come after @CacheTTL
C. Because async methods cannot use caching decorators
D. Because the cache key 'dataKey' is invalid

Solution

  1. Step 1: Check the @CacheTTL parameter type

    The TTL decorator expects a number (seconds), but '300' is a string, which causes it to fail.
  2. Step 2: Verify other decorator rules

    Decorator order does not affect TTL, async methods support caching, and 'dataKey' is a valid string key.
  3. Final Answer:

    Because TTL value should be a number, not a string -> Option A
  4. Quick Check:

    TTL must be number, not string [OK]
Hint: TTL needs number type, not quoted string [OK]
Common Mistakes:
  • Passing TTL as string instead of number
  • Thinking decorator order matters here
  • Assuming async disables caching
5. You want to cache user data with a dynamic key based on user ID. Which approach correctly creates a custom cache key in NestJS for method getUserById(id: string)?
hard
A. Use @CacheKey(() => `user_${id}`) above the method
B. Manually generate the key inside the method and use @CacheKey() without parameters
C. Use @CacheKey('user_' + id) directly above the method
D. Use @CacheKey() and pass the key as a method argument

Solution

  1. Step 1: Understand dynamic cache keys in NestJS

    To create a dynamic cache key, you can pass a function to @CacheKey() that returns the key string using method parameters.
  2. Step 2: Evaluate each option

    Use @CacheKey(() => `user_${id}`) above the method correctly uses a function returning a template string with id. Manually generate the key inside the method and use @CacheKey() without parameters is invalid because @CacheKey() needs the key at decoration time. Use @CacheKey('user_' + id) directly above the method tries to concatenate directly but id is not available at decoration time. Use @CacheKey() and pass the key as a method argument is invalid as @CacheKey() does not accept method arguments.
  3. Final Answer:

    Use @CacheKey(() => `user_${id}`) above the method -> Option A
  4. Quick Check:

    Dynamic key = function in @CacheKey() [OK]
Hint: Use function in @CacheKey() for dynamic keys [OK]
Common Mistakes:
  • Trying to use method parameters directly in decorator string
  • Assuming @CacheKey() accepts method arguments
  • Generating key inside method but not linking to cache
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