Consider a NestJS cache configured with a TTL (time-to-live) of 5 seconds. What happens when you try to retrieve a cached value after 6 seconds?
import { CacheModule, Injectable, Inject, CACHE_MANAGER } from '@nestjs/common'; @Injectable() export class SampleService { constructor(@Inject(CACHE_MANAGER) private readonly cacheManager) {} async getCachedValue() { return await this.cacheManager.get('key'); } } // CacheModule registered with TTL: 5 seconds
Think about what TTL means for cached data lifetime.
TTL defines how long a cached item stays valid. After 5 seconds, the cached value expires and is removed, so retrieval returns null or undefined.
Choose the correct way to configure the CacheModule with a TTL of 10 seconds.
import { CacheModule } from '@nestjs/common'; CacheModule.register({ // TTL configuration here });
TTL is specified in seconds as a number.
The TTL option expects a number representing seconds. So ttl: 10 means 10 seconds.
Given this NestJS cache configuration, the cached values never expire. What is the likely cause?
CacheModule.register({
ttl: 5,
max: 100
});
// Usage:
await cacheManager.set('key', 'value');
// After 10 seconds
const val = await cacheManager.get('key'); // val is still 'value'Consider the cache store implementation and its TTL support.
Some cache stores or custom stores may not support TTL expiration. Setting TTL has no effect if the store ignores it.
Consider this code snippet using NestJS cache manager:
await cacheManager.set('short', 'A', { ttl: 2 }); await cacheManager.set('long', 'B', { ttl: 5 }); // After 3 seconds const shortVal = await cacheManager.get('short'); const longVal = await cacheManager.get('long'); console.log(shortVal, longVal);
Think about which keys expire after 3 seconds.
The key 'short' expires after 2 seconds, so after 3 seconds it is gone (undefined). The key 'long' expires after 5 seconds, so it still returns 'B'.
In a NestJS app using Redis as a distributed cache, what is the effect of setting TTL in CacheModule configuration?
Think about Redis capabilities and how TTL works in distributed caches.
Redis supports key expiration natively. When TTL is set in NestJS CacheModule using Redis store, Redis enforces expiration automatically.