Bird
Raised Fist0
NestJSframework~20 mins

Cache decorators in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cache Decorators Master
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 @Cacheable with a method returning a random number?

Consider a NestJS service method decorated with @Cacheable() that returns a random number. What will happen when you call this method twice in a row?

NestJS
import { Cacheable } from '@nestjs/cache-manager';

class RandomService {
  @Cacheable()
  getRandom() {
    return Math.random();
  }
}

const service = new RandomService();
const first = service.getRandom();
const second = service.getRandom();
console.log(first === second);
Atrue - The second call returns the cached value from the first call
Bfalse - Each call generates a new random number
CThrows a runtime error because caching is not configured
Dundefined - The method does not return anything
Attempts:
2 left
💡 Hint

Think about what caching does to method results.

❓ lifecycle
intermediate
2:00remaining
When is the cache cleared if you use @CacheEvict on a method?

In NestJS, if a method is decorated with @CacheEvict(), when does the cache get cleared?

NestJS
import { CacheEvict } from '@nestjs/cache-manager';

class UserService {
  @CacheEvict()
  updateUser(id: string, data: any) {
    // update user logic
    return true;
  }
}
AAfter the method successfully completes
BOnly if the method throws an error
CCache is never cleared automatically
DBefore the method runs
Attempts:
2 left
💡 Hint

Think about when you want to remove stale data after an update.

📝 Syntax
advanced
2:00remaining
Which option correctly uses @CacheKey and @CacheTTL decorators together?

Choose the correct way to set a custom cache key and TTL (time to live) for a method in NestJS.

NestJS
import { CacheKey, CacheTTL, Cacheable } from '@nestjs/cache-manager';

class ProductService {
  @Cacheable()
  @CacheKey('custom_key')
  @CacheTTL(120)
  getProduct(id: string) {
    return { id, name: 'Product' };
  }
}
A
@CacheTTL(120)
@CacheKey('custom_key')
@Cacheable()
getProduct(id: string) { return { id, name: 'Product' }; }
B
@CacheKey('custom_key')
@CacheTTL(120)
@Cacheable()
getProduct(id: string) { return { id, name: 'Product' }; }
C
@CacheTTL(120)
@Cacheable()
@CacheKey('custom_key')
getProduct(id: string) { return { id, name: 'Product' }; }
D
@Cacheable()
@CacheKey('custom_key')
@CacheTTL(120)
getProduct(id: string) { return { id, name: 'Product' }; }
Attempts:
2 left
💡 Hint

Remember the order decorators are applied matters in NestJS.

🔧 Debug
advanced
2:00remaining
What error occurs if you use @Cacheable on a method returning a Promise but forget to await it?

Given a method decorated with @Cacheable() that returns a Promise, what happens if you call it without await and try to cache the result?

NestJS
import { Cacheable } from '@nestjs/cache-manager';

class AsyncService {
  @Cacheable()
  async fetchData() {
    return 'data';
  }
}

const service = new AsyncService();
const result = service.fetchData();
console.log(typeof result);
A'string' - The cache automatically unwraps the Promise
BThrows a TypeError because caching expects a string
C'object' - The cached value is a Promise object, not the resolved data
Dundefined - The method returns nothing
Attempts:
2 left
💡 Hint

Think about what happens when you don't await an async function.

🧠 Conceptual
expert
2:00remaining
Which statement about NestJS cache decorators is TRUE?

Choose the true statement about how NestJS cache decorators work.

A@Cacheable caches method results and automatically invalidates cache on data changes
B@CacheEvict can be used to clear cache entries manually after specific method calls
C@CacheKey sets the cache expiration time in seconds for the method
D@CacheTTL defines a custom cache key string for the cached method
Attempts:
2 left
💡 Hint

Recall the purpose of each decorator.

Practice

(1/5)
1. What is the main purpose of using cache decorators like @Cacheable in a NestJS service method?
easy
A. To store the method's result and reuse it for faster responses
B. To log every method call for debugging
C. To automatically retry failed method calls
D. To encrypt the method's output before sending

Solution

  1. Step 1: Understand cache decorator role

    Cache decorators like @Cacheable save the output of a method so it can be reused without recalculating.
  2. Step 2: Identify the benefit

    This reuse speeds up responses by avoiding repeated work.
  3. Final Answer:

    To store the method's result and reuse it for faster responses -> Option A
  4. Quick Check:

    Cache decorators improve speed by storing results [OK]
Hint: Cache decorators save method results to speed up calls [OK]
Common Mistakes:
  • Thinking cache decorators log method calls
  • Confusing cache with retry logic
  • Assuming cache encrypts data
2. Which of the following is the correct way to apply a cache decorator with a 10-second TTL on a NestJS method?
easy
A. @Cacheable({ ttl: 10 })
B. @CacheEvict({ ttl: 10 })
C. @Cacheable(ttl = 10)
D. @Cacheable(ttl: 10)

Solution

  1. Step 1: Recall correct decorator syntax

    The @Cacheable decorator accepts an options object with ttl as a key.
  2. Step 2: Identify correct object syntax

    Correct syntax uses curly braces and colon: { ttl: 10 }.
  3. Final Answer:

    @Cacheable({ ttl: 10 }) -> Option A
  4. Quick Check:

    Use object with ttl key inside @Cacheable [OK]
Hint: Use @Cacheable({ ttl: number }) with curly braces [OK]
Common Mistakes:
  • Using parentheses with assignment inside decorator
  • Using @CacheEvict to set TTL
  • Using colon without braces
3. Given this NestJS service method with caching:
@Cacheable({ ttl: 5 })
async getData() {
  console.log('Fetching data');
  return 'data';
}

What will be printed if getData() is called three times within 5 seconds?
medium
A. Fetching data (printed 3 times)
B. Fetching data (printed once)
C. No output printed
D. Fetching data (printed twice)

Solution

  1. Step 1: Understand caching effect on method calls

    The first call runs the method and caches the result for 5 seconds.
  2. Step 2: Analyze subsequent calls within TTL

    Calls within 5 seconds return cached result without running method, so no console log.
  3. Final Answer:

    Fetching data (printed once) -> Option B
  4. Quick Check:

    Cache prevents repeated method execution within TTL [OK]
Hint: Method logs once, cached calls skip execution [OK]
Common Mistakes:
  • Assuming method runs every call ignoring cache
  • Thinking cache disables method completely
  • Confusing TTL with infinite caching
4. Consider this code snippet:
@Cacheable({ ttl: 10 })
async fetchData() {
  return await this.httpService.get('url');
}

@CacheEvict()
clearCache() {
  // clears cache
}

What is the main issue with the @CacheEvict usage here?
medium
A. The method must be async to use @CacheEvict
B. It should be @Cacheable instead of @CacheEvict
C. It lacks a key or target to specify which cache to clear
D. TTL must be set on @CacheEvict as well

Solution

  1. Step 1: Understand @CacheEvict purpose

    @CacheEvict clears cached data, but needs to know which cache entry or key to clear.
  2. Step 2: Identify missing key or target

    The code does not specify a key or target, so it cannot clear the intended cache.
  3. Final Answer:

    It lacks a key or target to specify which cache to clear -> Option C
  4. Quick Check:

    @CacheEvict needs key/target to clear cache [OK]
Hint: CacheEvict must specify what cache to clear [OK]
Common Mistakes:
  • Using CacheEvict without specifying key
  • Confusing CacheEvict with Cacheable
  • Assuming async required for CacheEvict
5. You want to cache a method result but clear the cache automatically when a related update method runs. Which combination of decorators correctly achieves this in NestJS?
hard
A. Use @CacheEvict on fetch method and @Cacheable on update method
B. Use @CacheEvict on both methods to clear cache
C. Use @Cacheable on both methods to cache results
D. Use @Cacheable on the fetch method and @CacheEvict on the update method with matching cache keys

Solution

  1. Step 1: Understand caching and eviction roles

    @Cacheable caches method results; @CacheEvict clears cache entries.
  2. Step 2: Apply decorators to correct methods

    Cache the fetch method result, and clear that cache when update method runs using @CacheEvict with matching keys.
  3. Final Answer:

    Use @Cacheable on the fetch method and @CacheEvict on the update method with matching cache keys -> Option D
  4. Quick Check:

    Cache fetch, evict on update with matching keys [OK]
Hint: Cache fetch, evict on update with matching keys [OK]
Common Mistakes:
  • Evicting cache on fetch method instead of update
  • Caching update method results unnecessarily
  • Not matching cache keys between decorators
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