Performance: Custom cache keys
This affects how efficiently cached data is retrieved and reused, impacting response time and server load.
const key = `userData:${userId}`; cacheManager.set(key, data);
cacheManager.set('userData', data); // same key for all users
| Pattern | Cache Hits | Cache Misses | Server Load | Verdict |
|---|---|---|---|---|
| Static key for all requests | Low | High | High | [X] Bad |
| Unique key per request parameters | High | Low | Low | [OK] Good |
@CacheKey() in a NestJS service?@CacheKey()@CacheTTL() sets cache duration, clearing cache is manual or by other methods, and disabling cache is not done by @CacheKey().@CacheKey() [OK]@DecoratorName(parameters) syntax above the method.@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.@CacheKey('userList')
@CacheTTL(60)
async getUsers() {
return ['Alice', 'Bob'];
}@CacheKey('userList') sets the cache key explicitly to 'userList'.@CacheTTL(60) sets the cache time to 60 seconds.@CacheKey('dataKey')
@CacheTTL('300')
async fetchData() {
return 'info';
}getUserById(id: string)?@CacheKey() that returns the key string using method parameters.@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.@CacheKey(() => `user_${id}`) above the method -> Option APass the test and this pattern moves unknown