Bird
Raised Fist0
NestJSframework~20 mins

Custom cache keys in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cache Key Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does a custom cache key affect caching in NestJS?

Consider a NestJS controller method using a custom cache key function. What will be the effect on caching behavior?

NestJS
import { Controller, Get } from '@nestjs/common';
import { CacheKey, CacheTTL } from '@nestjs/cache-manager';

@Controller('items')
export class ItemsController {
  @Get()
  @CacheKey('custom_key')
  @CacheTTL(30)
  findAll() {
    return ['item1', 'item2'];
  }
}
AThe cache will always use 'custom_key' as the key for storing the response, ignoring request parameters.
BThe cache key will be generated dynamically based on request parameters automatically.
CThe cache will not store any response because custom keys disable caching.
DThe cache key will be a combination of method name and parameters, ignoring the custom key.
Attempts:
2 left
💡 Hint

Think about what the @CacheKey decorator does in NestJS.

📝 Syntax
intermediate
2:00remaining
Identify the correct syntax to set a custom cache key in NestJS

Which of the following code snippets correctly sets a custom cache key for a controller method in NestJS?

A
@CacheKey('myKey')
@Get()
getData() { return 'data'; }
B
@CacheKey(myKey)
@Get()
getData() { return 'data'; }
C
@CacheKey({ key: 'myKey' })
@Get()
getData() { return 'data'; }
D
@CacheKey()
@Get()
getData() { return 'data'; }
Attempts:
2 left
💡 Hint

Remember how decorators accept string literals for keys.

🔧 Debug
advanced
3:00remaining
Why does the custom cache key not work as expected?

Given this code, why does the cache not store separate responses for different user IDs?

NestJS
import { Controller, Get, Param } from '@nestjs/common';
import { CacheKey } from '@nestjs/cache-manager';

@Controller('users')
export class UsersController {
  @Get(':id')
  @CacheKey('user_data')
  getUser(@Param('id') id: string) {
    return { id, name: 'User ' + id };
  }
}
ABecause @CacheKey does not work with route parameters.
BBecause the method lacks @CacheTTL decorator to enable caching.
CBecause the cache key is fixed to 'user_data', responses for all user IDs overwrite each other.
DBecause the cache key should be a function returning a key string.
Attempts:
2 left
💡 Hint

Think about how cache keys identify cached data.

🧠 Conceptual
advanced
3:00remaining
How to create dynamic custom cache keys in NestJS?

Which approach correctly creates dynamic cache keys based on method parameters in NestJS?

ANestJS automatically generates dynamic cache keys without extra code.
BUse @CacheKey decorator with a template string including parameters directly.
CUse @CacheKey decorator multiple times with different keys for each parameter value.
DUse a custom interceptor that generates cache keys including method arguments dynamically.
Attempts:
2 left
💡 Hint

Think about how to customize cache keys beyond static strings.

❓ state_output
expert
4:00remaining
What is the cache key used and output after calling the method twice with different params?

Given the following NestJS controller and custom interceptor, what cache keys are used and what is the output after two calls with different parameters?

NestJS
import { CacheInterceptor, ExecutionContext, Injectable, Controller, Get, Param, UseInterceptors } from '@nestjs/common';

@Injectable()
class CustomCacheInterceptor extends CacheInterceptor {
  trackBy(context: ExecutionContext): string | undefined {
    const request = context.switchToHttp().getRequest();
    const id = request.params.id;
    return `user_${id}`;
  }
}

@Controller('users')
@UseInterceptors(CustomCacheInterceptor)
export class UsersController {
  @Get(':id')
  getUser(@Param('id') id: string) {
    return { id, name: 'User ' + id };
  }
}

// Calls:
// 1) GET /users/1
// 2) GET /users/2
ACache keys used: 'users_getUser'; outputs: same cached response for both calls
BCache keys used: 'user_1' and 'user_2'; outputs: {id:'1', name:'User 1'} and {id:'2', name:'User 2'}
CCache keys used: 'user_data'; outputs: first call cached, second call overwrites
DNo cache keys used; outputs: fresh response each call
Attempts:
2 left
💡 Hint

Look at how the custom interceptor builds the cache key.

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