Bird
Raised Fist0
NestJSframework~10 mins

Cache stores (memory, Redis) in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Cache stores (memory, Redis)
Request comes in
↓
Check cache store
↓
Send response
When a request arrives, the system first checks the cache (memory or Redis). If data is found (hit), it returns it immediately. If not (miss), it fetches from the source, stores it in cache, then returns it.
Execution Sample
NestJS
import { Inject, Injectable, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';

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

  async getData(key: string) {
    const cached = await this.cacheManager.get(key);
    if (cached) return cached;
    const data = await this.fetchFromDb();
    await this.cacheManager.set(key, data, { ttl: 100 });
    return data;
  }

  async fetchFromDb() {
    return 'fresh data';
  }
}
This code tries to get data from cache first. If missing, it fetches fresh data, stores it in cache, then returns it.
Execution Table
StepActionCache StateData RetrievedResult
1Call getData('item1'){}undefinedCache miss, fetch from DB
2cacheManager.get('item1'){}undefinedNo cached data found
3fetchFromDb(){}'fresh data'Fetched fresh data
4cacheManager.set('item1', 'fresh data', { ttl: 100 }){'item1': 'fresh data'}N/AData cached
5Return 'fresh data'{'item1': 'fresh data'}'fresh data'Response sent
6Call getData('item1') again{'item1': 'fresh data'}'fresh data'Cache hit, return cached
7cacheManager.get('item1'){'item1': 'fresh data'}'fresh data'Cached data found
8Return 'fresh data'{'item1': 'fresh data'}'fresh data'Response sent from cache
💡 Execution stops after returning cached data on second call.
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 6Final
cache{}{}{'item1': 'fresh data'}{'item1': 'fresh data'}{'item1': 'fresh data'}
cachedundefinedundefinedundefined'fresh data''fresh data'
dataundefined'fresh data''fresh data''fresh data''fresh data'
Key Moments - 3 Insights
Why does the first call to getData fetch from the database instead of cache?
Because the cache is empty at the start (see Step 2 in execution_table), so cacheManager.get returns undefined, causing a cache miss.
How does the cache store data after fetching from the database?
After fetching fresh data (Step 3), cacheManager.set stores it in cache with a TTL (Step 4), updating the cache state.
Why does the second call to getData return data immediately?
Because the data is now in cache (Step 6 and 7), so cacheManager.get returns the cached value, avoiding database fetch.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the cache state after Step 4?
A{'item1': undefined}
B{}
C{'item1': 'fresh data'}
DNone
💡 Hint
Check the 'Cache State' column at Step 4 in the execution_table.
At which step does the cache hit occur?
AStep 2
BStep 7
CStep 5
DStep 3
💡 Hint
Look for when cacheManager.get returns cached data in the execution_table.
If the TTL was set to 0, what would happen on the second call?
ACache would still return 'fresh data'
BCache would throw an error
CCache would be empty, causing a miss
DCache would store data indefinitely
💡 Hint
TTL 0 means no expiration in cache-manager, so data remains cached.
Concept Snapshot
Cache stores keep data temporarily to speed up responses.
Memory cache stores data in app memory; Redis stores data externally.
On request, check cache first (hit) to return fast.
If miss, fetch fresh data, store in cache, then return.
TTL controls how long data stays cached.
NestJS uses cache-manager to handle cache stores easily.
Full Transcript
This visual execution shows how cache stores work in NestJS using memory or Redis. When a request calls getData with a key, the system first checks the cache. If the data is not found (cache miss), it fetches fresh data from the database, stores it in the cache with a time-to-live (TTL), and returns it. On subsequent calls with the same key, the data is found in cache (cache hit), so it returns immediately without fetching from the database. The execution table traces each step, showing cache state changes and data retrieval. The variable tracker follows key variables like cache content and retrieved data. Key moments clarify why the first call fetches fresh data and how caching speeds up later calls. The quiz tests understanding of cache state and behavior. This pattern helps apps respond faster and reduce load by reusing stored data.

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