Custom cache keys help you control how data is stored and retrieved in the cache. This makes your app faster by reusing saved results exactly when you want.
When you want to cache data for specific users separately.
When caching results of a function that depends on multiple inputs.
When you want to avoid cache conflicts by naming keys clearly.
When you want to customize cache expiration per key.
When you want to debug or monitor cache usage with meaningful keys.
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
Step 1: Check the @CacheTTL parameter type
The TTL decorator expects a number (seconds), but '300' is a string, which causes it to fail.
Step 2: Verify other decorator rules
Decorator order does not affect TTL, async methods support caching, and 'dataKey' is a valid string key.
Final Answer:
Because TTL value should be a number, not a string -> Option A
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
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.
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.
Final Answer:
Use @CacheKey(() => `user_${id}`) above the method -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.