Bird
Raised Fist0
NestJSframework~20 mins

Why caching reduces response latency in NestJS - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Caching Mastery in NestJS
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
How does caching improve response time in NestJS?

In a NestJS application, why does using caching typically reduce the response latency for repeated requests?

ABecause caching compresses the response data, making it smaller to send over the network.
BBecause caching stores the result of expensive operations, so the server can quickly return the stored data without recalculating.
CBecause caching sends the request to multiple servers simultaneously to get the fastest response.
DBecause caching increases the server's CPU speed, making all operations faster.
Attempts:
2 left
💡 Hint

Think about what happens when the server has already done the work once and saves the result.

❓ component_behavior
intermediate
2:00remaining
What happens when a cached value is available in NestJS?

Consider a NestJS controller method that uses caching. What is the behavior when a cached value exists for a request?

AThe method skips executing its logic and returns the cached value immediately.
BThe method executes fully but ignores the cached value.
CThe method clears the cache and then executes its logic.
DThe method returns an error because cached values are not allowed.
Attempts:
2 left
💡 Hint

Think about why caching is used: to avoid repeating work.

📝 Syntax
advanced
2:00remaining
Identify the correct NestJS cache interceptor usage

Which option correctly applies the built-in cache interceptor to a NestJS controller method to enable caching?

NestJS
import { Controller, Get, UseInterceptors, CacheInterceptor } from '@nestjs/common';

@Controller('items')
export class ItemsController {
  @Get()
  @UseInterceptors(/* ??? */)
  findAll() {
    // expensive operation
    return ['item1', 'item2'];
  }
}
ACacheInterceptor
BCacheManager
CCacheService
DCacheModule
Attempts:
2 left
💡 Hint

Look for the interceptor class that handles caching.

❓ state_output
advanced
2:00remaining
What is the response time difference with and without caching?

Given a NestJS endpoint that takes 2 seconds to compute a response, what will be the approximate response time for the second request if caching is enabled?

AAbout 4 seconds because caching doubles the processing time.
BAbout 2 seconds because caching does not affect response time.
CAbout 0.01 seconds because the cached result is returned instantly.
DAbout 1 second because caching halves the processing time.
Attempts:
2 left
💡 Hint

Think about how caching avoids repeating the expensive operation.

🔧 Debug
expert
3:00remaining
Why does caching not reduce latency in this NestJS example?

Consider this NestJS controller method using caching, but response times remain slow on repeated requests. What is the likely cause?

NestJS
import { Controller, Get, UseInterceptors, CacheInterceptor } from '@nestjs/common';

@Controller('data')
export class DataController {
  @Get()
  @UseInterceptors(CacheInterceptor)
  async fetchData() {
    const result = await this.expensiveOperation();
    return result;
  }

  async expensiveOperation() {
    // Simulate delay
    await new Promise(res => setTimeout(res, 2000));
    return { data: 'value' };
  }
}
AThe controller method must return a string, not an object, for caching to work.
BThe expensiveOperation method is async, so caching cannot store async results.
CThe CacheInterceptor only caches POST requests, not GET requests.
DThe cache is not enabled globally or the CacheModule is not imported, so caching does not work.
Attempts:
2 left
💡 Hint

Check if the caching system is properly set up in the app module.

Practice

(1/5)
1. Why does caching reduce response latency in a NestJS application?
easy
A. Because it stores frequently requested data temporarily to avoid repeated slow operations
B. Because it increases the size of the database
C. Because it disables network requests completely
D. Because it compresses the response data before sending

Solution

  1. Step 1: Understand what caching does

    Caching temporarily stores data that is requested often, so the system doesn't have to fetch it repeatedly from slow sources like databases or APIs.
  2. Step 2: Connect caching to response time

    By avoiding repeated slow operations, caching reduces the time the app waits before sending a response, thus lowering latency.
  3. Final Answer:

    Because it stores frequently requested data temporarily to avoid repeated slow operations -> Option A
  4. Quick Check:

    Caching stores data to speed up responses = A [OK]
Hint: Caching saves repeated data fetch time to speed responses [OK]
Common Mistakes:
  • Thinking caching increases database size
  • Believing caching disables network requests
  • Confusing caching with data compression
2. Which of the following is the correct way to import caching in a NestJS module?
easy
A. import { CacheModule } from '@nestjs/common';
B. import { CacheInterceptor } from '@nestjs/core';
C. import { CacheModule } from '@nestjs/cache';
D. import { CacheService } from '@nestjs/common';

Solution

  1. Step 1: Identify the correct NestJS package for CacheModule

    CacheModule is part of the '@nestjs/common' package, so it should be imported from there.
  2. Step 2: Verify other options

    CacheInterceptor is from '@nestjs/common', not '@nestjs/core'; '@nestjs/cache' and CacheService do not exist as valid imports.
  3. Final Answer:

    import { CacheModule } from '@nestjs/common'; -> Option A
  4. Quick Check:

    CacheModule import is from '@nestjs/common' = D [OK]
Hint: CacheModule always imports from '@nestjs/common' [OK]
Common Mistakes:
  • Importing CacheModule from wrong package
  • Confusing CacheInterceptor import location
  • Using non-existent CacheService import
3. Given this NestJS controller snippet using caching:
  @UseInterceptors(CacheInterceptor)
  @Get('data')
  async getData() {
    console.log('Fetching data...');
    return { value: 42 };
  }

What will happen on the second request to /data?
medium
A. The console logs 'Fetching data...' again and returns { value: 42 }
B. The request fails with a cache error
C. The console does not log anything and returns cached { value: 42 }
D. The console logs twice and returns { value: 42 } twice

Solution

  1. Step 1: Understand CacheInterceptor behavior

    CacheInterceptor caches the response of the first request and returns it directly on subsequent requests without calling the method again.
  2. Step 2: Predict console output on second request

    Since the method is not called again, 'Fetching data...' is not logged on the second request, but the cached response is returned.
  3. Final Answer:

    The console does not log anything and returns cached { value: 42 } -> Option C
  4. Quick Check:

    CacheInterceptor returns cached data without method call = C [OK]
Hint: CacheInterceptor skips method call on cached requests [OK]
Common Mistakes:
  • Assuming method runs every time
  • Expecting cache errors on normal use
  • Thinking console logs twice per request
4. This NestJS code tries to enable caching but has an error:
  @Module({
    imports: [CacheModule.register()],
    controllers: [AppController],
    providers: [AppService, CacheInterceptor],
  })
  export class AppModule {}

What is the main problem here?
medium
A. CacheModule.register() requires a cache store option
B. CacheInterceptor should be provided using APP_INTERCEPTOR token, not directly
C. CacheInterceptor cannot be used with AppService
D. CacheModule must be imported from '@nestjs/core'

Solution

  1. Step 1: Check how to provide CacheInterceptor globally

    CacheInterceptor must be provided using the special token APP_INTERCEPTOR to work as a global interceptor.
  2. Step 2: Identify the error in providers array

    Providing CacheInterceptor directly in providers does not activate it globally; it needs to be wrapped with APP_INTERCEPTOR.
  3. Final Answer:

    CacheInterceptor should be provided using APP_INTERCEPTOR token, not directly -> Option B
  4. Quick Check:

    Use APP_INTERCEPTOR token to provide CacheInterceptor = B [OK]
Hint: Use APP_INTERCEPTOR token to enable CacheInterceptor globally [OK]
Common Mistakes:
  • Providing CacheInterceptor directly in providers
  • Thinking CacheModule always needs cache store option
  • Importing CacheModule from wrong package
5. You want to cache user profile data in NestJS but only for users with a premium subscription. Which approach best reduces response latency without caching non-premium users?
hard
A. Use CacheModule with a global TTL that applies to all users equally
B. Cache all user profiles regardless of subscription to simplify caching
C. Disable caching and fetch all profiles fresh every time
D. Use CacheInterceptor with a custom cache key that includes user type and skip caching for non-premium users

Solution

  1. Step 1: Understand selective caching needs

    To cache only premium users, caching logic must distinguish user types and avoid caching non-premium data.
  2. Step 2: Apply custom cache key and conditional caching

    Using CacheInterceptor with a custom cache key including user type allows caching premium users separately and skipping others.
  3. Step 3: Evaluate other options

    Caching all users wastes resources; disabling caching loses latency benefits; global TTL applies to all users, not selective.
  4. Final Answer:

    Use CacheInterceptor with a custom cache key that includes user type and skip caching for non-premium users -> Option D
  5. Quick Check:

    Selective caching with custom keys reduces latency best = A [OK]
Hint: Customize cache keys to cache only needed data [OK]
Common Mistakes:
  • Caching all data without filtering
  • Disabling caching completely
  • Using global TTL without user distinction
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