Bird
Raised Fist0
NestJSframework~20 mins

Cache stores (memory, Redis) in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cache Mastery in NestJS
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when using NestJS CacheModule with memory store?
Consider a NestJS service that caches a value in memory using CacheModule. What will be the output of the following code snippet when retrieving the cached value?
NestJS
import { Injectable, Inject, Module } from '@nestjs/common';
import { CacheModule, CACHE_MANAGER } from '@nestjs/cache-manager';
import type { Cache } from 'cache-manager';

@Injectable()
export class SampleService {
  constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}

  async cacheAndGet() {
    await this.cacheManager.set('key', 'hello');
    return await this.cacheManager.get('key');
  }
}

@Module({
  imports: [CacheModule.register()],
  providers: [SampleService],
})
export class AppModule {}
A"hello"
Bundefined
Cnull
DThrows a runtime error
Attempts:
2 left
💡 Hint
Think about what CacheModule.register() uses by default for storage.
📝 Syntax
intermediate
2:00remaining
Which option correctly configures Redis cache store in NestJS?
You want to configure NestJS CacheModule to use Redis as the cache store. Which of the following code snippets correctly sets up Redis as the cache store?
ACacheModule.register({ store: require('cache-manager-redis-store'), host: 'localhost', port: 6379 })
BCacheModule.register({ store: 'redis', host: 'localhost', port: 6379 })
CCacheModule.register({ redis: { host: 'localhost', port: 6379 } })
DCacheModule.register({ store: require('redis'), host: 'localhost', port: 6379 })
Attempts:
2 left
💡 Hint
The Redis store requires a specific package to be passed as the store option.
❓ state_output
advanced
2:00remaining
What happens to cached data when using memory store in a clustered NestJS app?
In a NestJS app running multiple instances (clustered), you use CacheModule with the default memory store. What will happen when you cache data in one instance and try to access it from another?
ACached data is shared across all instances and accessible everywhere
BCacheModule automatically syncs memory cache between instances
CEach instance has its own cache; data is not shared between instances
DAccessing cached data from another instance throws an error
Attempts:
2 left
💡 Hint
Think about how memory works in separate processes.
🔧 Debug
advanced
2:00remaining
Why does the Redis cache throw a connection error in this NestJS setup?
You configured CacheModule with Redis store but get a connection error at runtime. Which of the following is the most likely cause?
NestJS
CacheModule.register({ store: require('cache-manager-redis-store'), host: '127.0.0.1', port: 6380 })
AHost IP '127.0.0.1' is invalid for Redis connections
BThe store option should be a string 'redis' not a require call
CCacheModule does not support Redis caching
DRedis server is not running on port 6380
Attempts:
2 left
💡 Hint
Check if Redis server is listening on the specified port.
🧠 Conceptual
expert
3:00remaining
Why choose Redis over memory store for caching in NestJS in production?
Which of the following reasons best explains why Redis is preferred over the default memory store for caching in a production NestJS app?
AMemory store is faster and more scalable than Redis
BRedis supports distributed caching and persists data beyond app restarts
CRedis cache is built into NestJS by default, no extra setup needed
DMemory store automatically syncs cache between multiple app instances
Attempts:
2 left
💡 Hint
Think about app restarts and multiple server instances.

Practice

(1/5)
1. What is the main advantage of using Redis as a cache store in a NestJS application compared to in-memory cache?
easy
A. Redis does not support expiration of cached data.
B. Redis cache is stored only in the local app memory.
C. Redis allows sharing cached data across multiple app instances.
D. Redis cache clears automatically every second.

Solution

  1. Step 1: Understand in-memory cache scope

    In-memory cache stores data only inside the app instance's memory, so it is not shared.
  2. Step 2: Understand Redis cache scope

    Redis is a separate server that multiple app instances can connect to, sharing cached data.
  3. Final Answer:

    Redis allows sharing cached data across multiple app instances. -> Option C
  4. Quick Check:

    Redis cache is shared [OK]
Hint: Redis shares cache across servers; memory cache is local only [OK]
Common Mistakes:
  • Thinking in-memory cache shares data between servers
  • Believing Redis cache is local to one app instance
  • Assuming Redis cache clears every second automatically
2. Which of the following is the correct way to import and register the Redis cache store in a NestJS module?
easy
A. CacheModule.forRoot({ type: 'redis', url: 'redis://localhost:6379' })
B. CacheModule.register({ store: 'redis', host: 'localhost', port: 6379 })
C. CacheModule.useRedis({ host: 'localhost', port: 6379 })
D. CacheModule.registerRedis({ url: 'redis://localhost:6379' })

Solution

  1. Step 1: Recall NestJS CacheModule syntax

    CacheModule.register() is used to configure cache with options including store type and connection details.
  2. Step 2: Identify correct Redis store option

    Using store: 'redis' with host and port is the correct way to set Redis cache in NestJS.
  3. Final Answer:

    CacheModule.register({ store: 'redis', host: 'localhost', port: 6379 }) -> Option B
  4. Quick Check:

    Use CacheModule.register with store: 'redis' [OK]
Hint: Use CacheModule.register with store: 'redis' for Redis cache [OK]
Common Mistakes:
  • Using non-existent methods like useRedis or registerRedis
  • Confusing forRoot with register for cache setup
  • Incorrect option keys like type instead of store
3. Given this NestJS code snippet using in-memory cache:
await cacheManager.set('key1', 'value1', { ttl: 5 });
const val1 = await cacheManager.get('key1');
await new Promise(r => setTimeout(r, 6000));
const val2 = await cacheManager.get('key1');
What will be the values of val1 and val2 respectively?
medium
A. 'value1' and undefined
B. 'value1' and 'value1'
C. undefined and 'value1'
D. undefined and undefined

Solution

  1. Step 1: Understand TTL effect on cache

    The key 'key1' is set with a TTL (time to live) of 5 seconds, so it expires after 5 seconds.
  2. Step 2: Analyze timing of gets

    val1 is read immediately after setting, so it returns 'value1'. val2 is read after 6 seconds, after TTL expires, so it returns undefined.
  3. Final Answer:

    'value1' and undefined -> Option A
  4. Quick Check:

    TTL expires after 5s, val2 is undefined [OK]
Hint: TTL expires cache after set time; later gets return undefined [OK]
Common Mistakes:
  • Expecting cached value to persist beyond TTL
  • Ignoring async delay before second get
  • Confusing immediate and delayed cache reads
4. You wrote this NestJS Redis cache setup:
CacheModule.register({
  store: 'redis',
  host: 'localhost',
  port: '6379'
})
But your app throws a connection error. What is the likely cause?
medium
A. The port should be a number, not a string.
B. Redis store does not support host option.
C. CacheModule.register cannot be used for Redis.
D. Missing password option causes connection failure.

Solution

  1. Step 1: Check data types in config

    Port should be a number (6379), not a string ('6379'), or connection fails.
  2. Step 2: Validate other options

    Host is valid, CacheModule.register supports Redis, password is optional if Redis has no auth.
  3. Final Answer:

    The port should be a number, not a string. -> Option A
  4. Quick Check:

    Port must be number type [OK]
Hint: Use number type for port, not string, in Redis config [OK]
Common Mistakes:
  • Passing port as string instead of number
  • Assuming host option is invalid
  • Thinking password is always required
5. You want to cache user profile data in Redis with a TTL of 10 minutes in NestJS. Which code snippet correctly sets this cache and retrieves it safely?
hard
A. await cacheManager.set('user_123', profile, 600); const data = cacheManager.get('user_123');
B. await cacheManager.set('user_123', profile, { expire: 600 }); const data = await cacheManager.get('user_123');
C. cacheManager.set('user_123', profile, { ttl: 600 }); const data = await cacheManager.get('user_123');
D. await cacheManager.set('user_123', profile, { ttl: 600 }); const data = await cacheManager.get('user_123');

Solution

  1. Step 1: Use correct TTL option in set()

    TTL must be passed as an object property { ttl: 600 } for 10 minutes (600 seconds).
  2. Step 2: Await both set and get calls

    Both set and get are async, so await is needed to ensure completion and data retrieval.
  3. Final Answer:

    await cacheManager.set('user_123', profile, { ttl: 600 }); const data = await cacheManager.get('user_123'); -> Option D
  4. Quick Check:

    TTL as { ttl: 600 } and await both calls [OK]
Hint: Pass TTL as { ttl: seconds } and await async cache calls [OK]
Common Mistakes:
  • Passing TTL as a number directly instead of in object
  • Not awaiting async cache get call
  • Using wrong option name like expire instead of ttl
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard