0
0
NestJSframework~8 mins

Custom cache keys in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Custom cache keys
MEDIUM IMPACT
This affects how efficiently cached data is retrieved and reused, impacting response time and server load.
Caching API responses with unique keys for different query parameters
NestJS
const key = `userData:${userId}`;
cacheManager.set(key, data);
Generates unique keys per user, ensuring correct cached data is served without collisions.
📈 Performance Gainreduces cache misses and server load, improving response speed
Caching API responses with unique keys for different query parameters
NestJS
cacheManager.set('userData', data); // same key for all users
Using a single static cache key causes cache collisions and stale data for different users.
📉 Performance Costcauses frequent cache misses and redundant data fetching, increasing server response time
Performance Comparison
PatternCache HitsCache MissesServer LoadVerdict
Static key for all requestsLowHighHigh[X] Bad
Unique key per request parametersHighLowLow[OK] Good
Rendering Pipeline
Custom cache keys optimize the server response phase by reducing redundant data fetching and processing.
Server Processing
Network Response
⚠️ BottleneckCache lookup efficiency and data retrieval
Core Web Vital Affected
INP
This affects how efficiently cached data is retrieved and reused, impacting response time and server load.
Optimization Tips
1Use unique cache keys that reflect request parameters to avoid collisions.
2Avoid static keys for dynamic data to prevent stale cache issues.
3Test cache effectiveness by measuring response times for repeated requests.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is using a static cache key for all requests bad for performance?
AIt causes cache collisions and stale data, increasing server load.
BIt reduces server load by sharing cached data.
CIt improves cache hit rate for all users.
DIt decreases network latency automatically.
DevTools: Network
How to check: Open DevTools Network panel, observe response times for repeated requests with different parameters.
What to look for: Faster responses and fewer full data fetches indicate effective caching with custom keys.