0
0
NestJSframework~3 mins

Why Custom cache keys in NestJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your cache could remember exactly who asked for what, every single time?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
cache.set('user', userData); // overwrites data for all users
After
cache.set(`user_${userId}`, userData); // unique key per user
What It Enables

Custom cache keys unlock precise, efficient caching that keeps data accurate and speeds up your app.

Real Life Example

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.

Key Takeaways

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.