0
0
NestJSframework~30 mins

TTL configuration in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
TTL Configuration in NestJS Cache Module
📖 Scenario: You are building a NestJS application that caches user data to improve performance. You want to configure the cache so that cached data expires automatically after a certain time (TTL - Time To Live).
🎯 Goal: Configure the NestJS CacheModule with a TTL of 5 seconds and create a service that caches and retrieves user data.
📋 What You'll Learn
Import CacheModule with TTL configuration set to 5 seconds
Create a service called UserCacheService
Use cacheManager to set and get cached user data
Ensure cached data expires after 5 seconds automatically
💡 Why This Matters
🌍 Real World
Caching user data with TTL helps improve app performance by reducing repeated database calls and automatically cleaning up stale data.
💼 Career
Understanding TTL configuration and cache management is essential for backend developers working with NestJS to build scalable and efficient applications.
Progress0 / 4 steps
1
Import CacheModule with TTL configuration
In your AppModule, import CacheModule from @nestjs/cache-manager and configure it with ttl: 5 inside CacheModule.register().
NestJS
Need a hint?

Use CacheModule.register({ ttl: 5 }) inside the imports array of @Module.

2
Create UserCacheService with cacheManager injection
Create a service class called UserCacheService. Inject CACHE_MANAGER using @Inject and assign it to a private variable called cacheManager.
NestJS
Need a hint?

Use @Inject(CACHE_MANAGER) in the constructor to get the cache manager instance.

3
Add methods to set and get cached user data
Inside UserCacheService, add an async method cacheUserData that takes userId and data and uses this.cacheManager.set() to cache the data. Also add an async method getUserData that takes userId and returns cached data using this.cacheManager.get().
NestJS
Need a hint?

Use this.cacheManager.set(key, value) to store and this.cacheManager.get(key) to retrieve cached data.

4
Register UserCacheService in AppModule providers
Add UserCacheService to the providers array in AppModule so it can be injected and used in the application.
NestJS
Need a hint?

Add UserCacheService inside the providers array of @Module.