What if your cache could remember exactly who asked for what, every single time?
Why Custom cache keys in NestJS? - Purpose & Use Cases
Imagine you have a web app that fetches user data from a database. Every time a user requests their profile, the app runs the same database query again and again.
To speed things up, you decide to store the results in a cache. But if you use a simple cache key like 'user', the app will mix up data from different users.
Using generic cache keys causes wrong data to show up, confusing users.
Manually creating unique keys for each request is tricky and easy to mess up, especially when requests have many parameters.
This leads to bugs, stale data, and wasted time fixing cache mistakes.
Custom cache keys let you define exactly how to name each cached item based on request details.
This means each user's data is stored separately and retrieved correctly without confusion.
It makes caching reliable, fast, and easy to maintain.
cache.set('user', userData); // overwrites data for all users
cache.set(`user_${userId}`, userData); // unique key per userCustom cache keys unlock precise, efficient caching that keeps data accurate and speeds up your app.
Think of a library where every book has a unique code. Without unique codes, books get mixed up on shelves. Custom cache keys are like those unique codes for your cached data.
Manual cache keys cause data mix-ups and bugs.
Custom cache keys create unique names for each cached item.
This improves app speed, accuracy, and reliability.
Practice
@CacheKey() in a NestJS service?Solution
Step 1: Understand the role of
This decorator is used to specify a custom key name for the cached data instead of using a default or generated key.@CacheKey()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().Final Answer:
To define a custom name for the cached data key -> Option CQuick Check:
Custom cache key =@CacheKey()[OK]
- Confusing @CacheKey() with @CacheTTL()
- Thinking @CacheKey() clears cache
- Assuming @CacheKey() disables caching
Solution
Step 1: Identify correct decorator syntax
In NestJS, decorators are applied with@DecoratorName(parameters)syntax above the method.Step 2: Check each option
@CacheKey('myKey')\nasync getData() { return data; } uses@CacheKey('myKey')correctly. @CacheTTL(300)\nasync getData() { return data; } uses@CacheTTLwhich 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.Final Answer:
@CacheKey('myKey')\nasync getData() { return data; } -> Option DQuick Check:
Decorator syntax = @CacheKey('key') [OK]
- Using assignment instead of decorator syntax
- Mixing @CacheKey with @CacheTTL
- Calling cacheKey as a function instead of decorator
@CacheKey('userList')
@CacheTTL(60)
async getUsers() {
return ['Alice', 'Bob'];
}What will be the cache key and TTL for the cached data?
Solution
Step 1: Identify the cache key from @CacheKey()
The decorator@CacheKey('userList')sets the cache key explicitly to 'userList'.Step 2: Identify the TTL from @CacheTTL()
The decorator@CacheTTL(60)sets the cache time to 60 seconds.Final Answer:
Key: 'userList', TTL: 60 seconds -> Option BQuick Check:
Custom key + TTL = 'userList' & 60s [OK]
- Assuming method name is cache key when @CacheKey is used
- Ignoring @CacheTTL and thinking no TTL is set
- Confusing TTL units (seconds vs milliseconds)
@CacheKey('dataKey')
@CacheTTL('300')
async fetchData() {
return 'info';
}Why does the cache TTL not work as expected?
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 AQuick Check:
TTL must be number, not string [OK]
- Passing TTL as string instead of number
- Thinking decorator order matters here
- Assuming async disables caching
getUserById(id: string)?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 withid. 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 butidis 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 AQuick Check:
Dynamic key = function in @CacheKey() [OK]
- Trying to use method parameters directly in decorator string
- Assuming @CacheKey() accepts method arguments
- Generating key inside method but not linking to cache
Ready to prove it?
Pass the test and this pattern moves unknown
