0
0
NestJSframework~10 mins

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

Choose your learning style9 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.