Bird
Raised Fist0
Node.jsframework~20 mins

In-memory caching patterns in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
In-memory Cache Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Node.js in-memory cache example?

Consider this simple cache implemented with a Map. What will be logged to the console?

Node.js
const cache = new Map();

function getData(key) {
  if (cache.has(key)) {
    return cache.get(key);
  }
  const value = key * 2;
  cache.set(key, value);
  return value;
}

console.log(getData(3));
console.log(getData(3));
A6\n6
B6\nundefined
C3\n3
Dundefined\n6
Attempts:
2 left
💡 Hint

Think about what happens when the key is already in the cache.

📝 Syntax
intermediate
2:00remaining
Which option correctly implements a TTL (time-to-live) cache entry in Node.js?

We want to store a value in a cache that expires after 1 second. Which code snippet correctly sets and removes the cache entry?

Acache.set(key, value, 1000); // Map does not support TTL natively
Bcache.set(key, value); setInterval(() => cache.delete(key), 1000);
CsetTimeout(() => cache.set(key, value), 1000);
Dcache.set(key, value); setTimeout(() => cache.delete(key), 1000);
Attempts:
2 left
💡 Hint

Map does not support TTL natively. You must remove the key manually after delay.

🔧 Debug
advanced
2:00remaining
Why does this cache implementation cause a memory leak?

Look at this cache code snippet. What causes the memory leak?

Node.js
const cache = {};

function addToCache(key, value) {
  cache[key] = value;
}

// Keys are never removed from cache

addToCache('a', 'data1');
addToCache('b', 'data2');
// ... many keys added over time
AKeys are never removed, so cache grows indefinitely, causing memory leak.
BValues are overwritten causing data loss, not memory leak.
CUsing an object for cache causes syntax errors.
DCache keys are deleted too early causing errors.
Attempts:
2 left
💡 Hint

Think about what happens if you never remove keys from the cache.

❓ state_output
advanced
2:00remaining
What is the final cache content after running this code?

Given this cache with a max size of 2, what keys remain after the operations?

Node.js
class LRUCache {
  constructor(maxSize) {
    this.maxSize = maxSize;
    this.cache = new Map();
  }

  get(key) {
    if (!this.cache.has(key)) return null;
    const value = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, value);
    return value;
  }

  set(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else if (this.cache.size === this.maxSize) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    this.cache.set(key, value);
  }
}

const cache = new LRUCache(2);
cache.set('a', 1);
cache.set('b', 2);
cache.get('a');
cache.set('c', 3);

console.log([...cache.cache.keys()]);
A['a', 'b']
B['b', 'c']
C['a', 'c']
D['c']
Attempts:
2 left
💡 Hint

Remember that accessing a key moves it to the most recently used position.

🧠 Conceptual
expert
2:00remaining
Which option best explains why WeakMap is useful for in-memory caching?

Why would you choose a WeakMap over a Map for caching objects in Node.js?

AWeakMap stores keys as strings only, making it faster than Map.
BWeakMap allows cached objects to be garbage collected if no other references exist, preventing memory leaks.
CWeakMap automatically persists cache data to disk for durability.
DWeakMap supports TTL natively, removing expired entries automatically.
Attempts:
2 left
💡 Hint

Think about how garbage collection works with weak references.

Practice

(1/5)
1. What is the main purpose of using in-memory caching in a Node.js application?
easy
A. To send data over the network
B. To permanently save data to disk
C. To encrypt data for security
D. To store data temporarily for faster access during runtime

Solution

  1. Step 1: Understand caching purpose

    In-memory caching stores data temporarily inside the app to avoid repeated slow operations.
  2. Step 2: Differentiate from other storage types

    Permanent storage is done on disk, not in-memory cache. Network and encryption are unrelated here.
  3. Final Answer:

    To store data temporarily for faster access during runtime -> Option D
  4. Quick Check:

    In-memory cache = temporary fast storage [OK]
Hint: Cache means fast temporary storage in app memory [OK]
Common Mistakes:
  • Confusing cache with permanent disk storage
  • Thinking cache sends data over network
  • Assuming cache encrypts data
2. Which of the following is the correct way to create a simple in-memory cache using JavaScript's Map in Node.js?
easy
A. const cache = Map();
B. const cache = {};
C. const cache = new Map();
D. const cache = new map();

Solution

  1. Step 1: Recall Map object creation syntax

    JavaScript's Map is created with new Map(), capital M and parentheses.
  2. Step 2: Check options for syntax correctness

    const cache = new Map(); uses correct syntax. const cache = Map(); misses new keyword. const cache = {}; uses object literal, not Map. const cache = new map(); uses lowercase 'map' which is invalid.
  3. Final Answer:

    const cache = new Map(); -> Option C
  4. Quick Check:

    Map creation = new Map() [OK]
Hint: Use 'new Map()' with capital M and parentheses [OK]
Common Mistakes:
  • Omitting 'new' keyword
  • Using lowercase 'map' instead of 'Map'
  • Confusing Map with plain object {}
3. Consider this Node.js code using a Map as cache:
const cache = new Map();
cache.set('user1', {name: 'Alice'});
cache.set('user2', {name: 'Bob'});
console.log(cache.get('user1').name);

What will be printed to the console?
medium
A. Alice
B. undefined
C. user1
D. Error: Cannot read property 'name' of undefined

Solution

  1. Step 1: Understand cache.set and cache.get usage

    cache.set('user1', {name: 'Alice'}) stores an object with name 'Alice' under key 'user1'.
  2. Step 2: Retrieve and access property

    cache.get('user1') returns the object {name: 'Alice'}, so accessing .name gives 'Alice'.
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    cache.get('user1').name = Alice [OK]
Hint: cache.get(key) returns stored value; access properties normally [OK]
Common Mistakes:
  • Assuming cache.get returns key instead of value
  • Forgetting to use .name on the returned object
  • Thinking cache.get returns undefined if key exists
4. This code snippet tries to implement a cache but has a bug:
const cache = new Map();
function getData(key) {
  if (cache.has(key)) {
    return cache.get;
  }
  const data = fetchFromDb(key);
  cache.set(key, data);
  return data;
}

What is the bug causing incorrect cache retrieval?
medium
A. fetchFromDb should be awaited with async
B. cache.get is a function reference, should call cache.get(key)
C. cache.set(key, data) should be cache.add(key, data)
D. cache.has(key) should be cache.exists(key)

Solution

  1. Step 1: Analyze cache retrieval line

    cache.get is a function, but code returns cache.get without calling it with key.
  2. Step 2: Correct method usage

    It should be cache.get(key) to retrieve the cached value properly.
  3. Final Answer:

    cache.get is a function reference, should call cache.get(key) -> Option B
  4. Quick Check:

    Use cache.get(key) to get value [OK]
Hint: Call cache.get with key: cache.get(key) [OK]
Common Mistakes:
  • Returning cache.get without parentheses
  • Using non-existent cache.exists method
  • Confusing cache.set with cache.add
5. You want to implement an in-memory cache in Node.js that automatically removes entries after 5 seconds to save memory. Which approach correctly adds expiration logic?
hard
A. Use Map and setTimeout to delete the key after 5 seconds when setting cache
B. Use Map and clear the entire cache every 5 seconds with setInterval
C. Use a plain object and rely on garbage collection to remove old keys
D. Use Map and never delete keys to keep cache forever

Solution

  1. Step 1: Understand expiration requirement

    We want each cache entry to be removed individually after 5 seconds.
  2. Step 2: Evaluate options for expiration logic

    Use Map and setTimeout to delete the key after 5 seconds when setting cache uses setTimeout per key to delete it after 5 seconds, which fits requirement. Use Map and clear the entire cache every 5 seconds with setInterval clears entire cache, not per key. Use a plain object and rely on garbage collection to remove old keys relies on garbage collection which does not remove keys automatically. Use Map and never delete keys to keep cache forever never deletes keys, so no expiration.
  3. Final Answer:

    Use Map and setTimeout to delete the key after 5 seconds when setting cache -> Option A
  4. Quick Check:

    Use setTimeout per key for expiration [OK]
Hint: Use setTimeout to delete each key after delay [OK]
Common Mistakes:
  • Clearing whole cache instead of individual keys
  • Expecting garbage collection to remove keys automatically
  • Not deleting keys causes memory bloat
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