Bird
Raised Fist0
NestJSframework~20 mins

CacheModule setup in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
CacheModule Mastery
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 CacheModule with default settings?

Consider a NestJS service that caches a value using CacheModule with default settings. What will be the behavior when retrieving a cached value immediately after setting it?

NestJS
import { CacheModule, Injectable, Module, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';

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

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

@Module({
  imports: [CacheModule.register()],
  providers: [SampleService],
})
export class AppModule {}
AThe method returns 'value' as the cached data is immediately available.
BThe method throws a runtime error because CacheModule requires explicit store configuration.
CThe method returns undefined because caching is asynchronous and not ready yet.
DThe method returns null because the default cache store does not store data.
Attempts:
2 left
💡 Hint

Think about how the default in-memory cache store works in NestJS CacheModule.

📝 Syntax
intermediate
1:30remaining
Which CacheModule setup code is syntactically correct for setting a TTL of 5 seconds?

Choose the correct way to configure CacheModule with a time-to-live (TTL) of 5 seconds.

ACacheModule.register({ expire: 5 })
BCacheModule.register({ ttl: 5 })
CCacheModule.register({ timeToLive: 5 })
DCacheModule.register({ ttl: 5000 })
Attempts:
2 left
💡 Hint

Check the official CacheModule options for TTL property name and units.

🔧 Debug
advanced
2:30remaining
Why does this CacheModule setup cause a runtime error?

Examine the following CacheModule setup. Why will it cause a runtime error?

NestJS
import { CacheModule } from '@nestjs/common';

CacheModule.register({
  store: 'redis',
  host: 'localhost',
  port: 6379
});
ABecause CacheModule does not support Redis caching.
BBecause the 'host' and 'port' options are invalid for CacheModule.
CBecause 'store' must be a function or a valid store instance, not a string.
DBecause the CacheModule requires a 'ttl' option to be set.
Attempts:
2 left
💡 Hint

Think about how to properly configure a Redis cache store in NestJS CacheModule.

❓ state_output
advanced
2:30remaining
What is the value of 'cachedData' after this code runs?

Given this NestJS service using CacheModule, what will be the value of cachedData after fetchData() is called twice in a row?

NestJS
import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';

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

  async fetchData() {
    const cached = await this.cacheManager.get('data');
    if (cached) return cached;
    const data = 'fresh data';
    await this.cacheManager.set('data', data, { ttl: 1 });
    return data;
  }
}

// Assume fetchData() is called twice within 2 seconds.
A'fresh data' both times because TTL is 1 second and cache expires quickly.
B'fresh data' first call, 'fresh data' second call because cache is still valid.
Cundefined both times because cache is not set properly.
D'fresh data' first call, undefined second call because cache is cleared.
Attempts:
2 left
💡 Hint

Consider the TTL of 1 second and the timing of calls.

🧠 Conceptual
expert
3:00remaining
Which statement about CacheModule global setup is true?

When configuring CacheModule globally in a NestJS app, which statement is correct?

ASetting <code>isGlobal: true</code> automatically enables Redis caching.
BCacheModule cannot be set globally; it must be imported in every module separately.
CGlobal CacheModule disables the ability to override cache settings in feature modules.
DSetting <code>isGlobal: true</code> in <code>CacheModule.register()</code> makes the cache available in all modules without importing it.
Attempts:
2 left
💡 Hint

Think about the purpose of the isGlobal option in NestJS modules.

Practice

(1/5)
1. What is the main purpose of importing CacheModule in a NestJS application?
easy
A. To enable temporary storage of data to speed up responses
B. To connect to a database automatically
C. To handle user authentication
D. To manage application logging

Solution

  1. Step 1: Understand CacheModule's role

    CacheModule is used to store data temporarily to reduce repeated processing.
  2. Step 2: Compare with other options

    It does not handle database, authentication, or logging directly.
  3. Final Answer:

    To enable temporary storage of data to speed up responses -> Option A
  4. Quick Check:

    CacheModule = temporary data storage [OK]
Hint: CacheModule is about caching data, not databases or auth [OK]
Common Mistakes:
  • Confusing CacheModule with database modules
  • Thinking CacheModule manages authentication
  • Assuming CacheModule handles logging
2. Which of the following is the correct way to import and register CacheModule with a TTL of 5 seconds in a NestJS module?
easy
A. CacheModule.register({ ttl: 5 })
B. CacheModule.forRoot({ ttl: 5 })
C. CacheModule.setup({ ttl: 5 })
D. CacheModule.init({ ttl: 5 })

Solution

  1. Step 1: Recall CacheModule registration method

    CacheModule uses the static method register to configure options like ttl.
  2. Step 2: Verify method names

    Methods like forRoot, setup, or init are not used by CacheModule.
  3. Final Answer:

    CacheModule.register({ ttl: 5 }) -> Option A
  4. Quick Check:

    Use register() to configure CacheModule [OK]
Hint: CacheModule uses register(), not forRoot() or init() [OK]
Common Mistakes:
  • Using forRoot() instead of register()
  • Using setup() or init() which do not exist
  • Forgetting to pass options inside register()
3. Given this NestJS module setup:
import { CacheModule, Module } from '@nestjs/common';

@Module({
  imports: [CacheModule.register({ ttl: 10 })],
})
export class AppModule {}
What will be the effect of the ttl: 10 option?
medium
A. Cache entries expire after 10 minutes
B. Cache entries expire after 10 seconds
C. Cache entries never expire
D. Cache entries expire immediately

Solution

  1. Step 1: Understand ttl meaning in CacheModule

    The ttl option sets the time-to-live in seconds for cached data.
  2. Step 2: Interpret ttl: 10

    Since ttl is 10, cached data expires after 10 seconds.
  3. Final Answer:

    Cache entries expire after 10 seconds -> Option B
  4. Quick Check:

    ttl = seconds cache lives [OK]
Hint: ttl value is in seconds, not minutes [OK]
Common Mistakes:
  • Assuming ttl is in minutes
  • Thinking ttl disables expiration
  • Confusing ttl with cache size
4. Identify the error in this CacheModule setup:
import { CacheModule, Module } from '@nestjs/common';

@Module({
  imports: [CacheModule.register({ ttl: '20' })],
})
export class AppModule {}
medium
A. register() method does not accept options
B. CacheModule cannot be imported from '@nestjs/common'
C. ttl should be a number, not a string
D. Module decorator is missing parentheses

Solution

  1. Step 1: Check ttl option type

    ttl expects a number representing seconds, not a string.
  2. Step 2: Verify other parts

    CacheModule import and Module decorator usage are correct; register() accepts options.
  3. Final Answer:

    ttl should be a number, not a string -> Option C
  4. Quick Check:

    ttl must be numeric [OK]
Hint: ttl must be a number, not quoted text [OK]
Common Mistakes:
  • Passing ttl as a string instead of number
  • Thinking register() has no parameters
  • Misusing import paths
5. You want to cache HTTP GET responses in a NestJS controller using CacheModule with a global TTL of 15 seconds. Which setup correctly applies caching to all routes in the module?
hard
A. Import CacheModule with ttl 15 and manually store cache in each method
B. Import CacheModule with ttl 15 and add @Cacheable() decorator on each method
C. Import CacheModule with ttl 15 and add @Cache() decorator on the module
D. Import CacheModule with ttl 15 and add @UseInterceptors(CacheInterceptor) on the controller

Solution

  1. Step 1: Understand CacheModule and CacheInterceptor usage

    CacheModule provides caching, and CacheInterceptor applies caching behavior to routes.
  2. Step 2: Apply CacheInterceptor globally on controller

    Using @UseInterceptors(CacheInterceptor) on the controller enables caching for all its routes.
  3. Step 3: Evaluate other options

    No @Cacheable() or @Cache() decorators exist in NestJS core; manual caching is possible but not automatic.
  4. Final Answer:

    Import CacheModule with ttl 15 and add @UseInterceptors(CacheInterceptor) on the controller -> Option D
  5. Quick Check:

    Use CacheInterceptor with CacheModule for route caching [OK]
Hint: Use CacheInterceptor decorator to enable caching on controllers [OK]
Common Mistakes:
  • Using non-existent decorators like @Cacheable or @Cache
  • Not applying CacheInterceptor to controller or routes
  • Trying manual caching instead of interceptor
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