Bird
Raised Fist0
Node.jsframework~20 mins

Common memory leak patterns in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Memory Leak Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Identifying memory leaks from event listeners
In Node.js, which of the following patterns is most likely to cause a memory leak related to event listeners?
AAdding event listeners inside a function without removing them when no longer needed
BUsing async/await to handle asynchronous code
CDeclaring variables with const instead of let
DUsing setTimeout with a delay of zero milliseconds
Attempts:
2 left
💡 Hint
Think about what happens if event listeners keep accumulating over time.
component_behavior
intermediate
2:00remaining
Effect of global variables on memory usage
What happens to memory usage in a Node.js application if large objects are stored in global variables and never cleared?
AMemory usage fluctuates randomly without any pattern
BMemory usage stays constant because global variables are optimized by the engine
CMemory usage increases over time because the objects remain referenced globally
DMemory usage decreases automatically as Node.js garbage collects global variables
Attempts:
2 left
💡 Hint
Consider how garbage collection works with references.
🔧 Debug
advanced
3:00remaining
Diagnosing memory leak from closures
Examine the following code snippet. What is the main cause of the memory leak?
Node.js
function createHandler() {
  const largeData = new Array(1000000).fill('data');
  return function handler() {
    console.log(largeData[0]);
  };
}

const handlers = [];
for (let i = 0; i < 1000; i++) {
  handlers.push(createHandler());
}
AThe closure keeps a reference to largeData, preventing it from being garbage collected
BThe array largeData is too large to be stored in memory
CThe console.log statement causes memory to leak
DThe for loop runs too many times causing a stack overflow
Attempts:
2 left
💡 Hint
Think about what the returned function remembers from its creation context.
📝 Syntax
advanced
2:00remaining
Identifying incorrect use of timers causing leaks
Which option shows a timer usage pattern that will cause a memory leak in Node.js?
AsetTimeout(() => { /* some code */ }, 1000); // runs once
BsetInterval(() => { /* some code */ }, 1000); // never cleared
CclearInterval(timerId); // clears interval properly
DsetImmediate(() => { /* some code */ }); // runs once immediately
Attempts:
2 left
💡 Hint
Consider what happens if intervals are never stopped.
state_output
expert
3:00remaining
Memory usage after removing references
Given the following code, what will be the approximate memory usage behavior after running it?
Node.js
let cache = {};

function addToCache(key) {
  cache[key] = new Array(1000000).fill('x');
}

for (let i = 0; i < 10; i++) {
  addToCache(i);
}

// Now clear cache
cache = null;

// What happens next?
AMemory usage will cause a crash immediately
BMemory usage will stay high because the arrays are still referenced elsewhere
CMemory usage will increase because setting cache to null creates new objects
DMemory usage will drop because cache is set to null and objects become unreachable
Attempts:
2 left
💡 Hint
Think about what happens when references are removed.

Practice

(1/5)
1. Which of the following is a common cause of memory leaks in Node.js applications?
easy
A. Keeping references to objects that are no longer needed
B. Using asynchronous functions
C. Writing synchronous code
D. Using the latest Node.js version

Solution

  1. Step 1: Understand what causes memory leaks

    Memory leaks happen when your program holds onto data it no longer needs, preventing the system from freeing memory.
  2. Step 2: Identify the correct cause among options

    Keeping references to unused objects prevents garbage collection, causing leaks. Other options do not inherently cause leaks.
  3. Final Answer:

    Keeping references to objects that are no longer needed -> Option A
  4. Quick Check:

    Memory leaks = unused references [OK]
Hint: Memory leaks happen when unused data is still referenced [OK]
Common Mistakes:
  • Thinking async code always causes leaks
  • Confusing synchronous code with leaks
  • Assuming Node.js version causes leaks
2. Which syntax correctly removes an event listener in Node.js to help prevent memory leaks?
easy
A. emitter.deleteListener('event', callback);
B. emitter.off('event');
C. emitter.remove('event', callback);
D. emitter.removeListener('event', callback);

Solution

  1. Step 1: Recall Node.js event listener removal syntax

    The correct method to remove a specific listener is removeListener(event, callback).
  2. Step 2: Check each option's validity

    emitter.removeListener('event', callback); uses the correct method. emitter.off('event'); removes all listeners but omits the specific callback. Options A and C are not valid methods.
  3. Final Answer:

    emitter.removeListener('event', callback); -> Option D
  4. Quick Check:

    Correct method = removeListener(event, callback) [OK]
Hint: Use removeListener with event and callback to remove listeners [OK]
Common Mistakes:
  • Using emitter.off without callback
  • Using non-existent methods like remove or deleteListener
  • Omitting the callback function
3. Consider this code snippet:
const cache = {};
function addToCache(key, value) {
  cache[key] = value;
}
addToCache('user1', {name: 'Alice'});
addToCache('user2', {name: 'Bob'});
console.log(Object.keys(cache).length);

What will be the output and what memory issue might this cause if keys are never removed?
medium
A. 0; No memory leak because cache is empty
B. 2; Memory leak due to unbounded cache growth
C. Error; Syntax error in code
D. Undefined; cache is not defined

Solution

  1. Step 1: Analyze the code output

    The cache object stores two keys: 'user1' and 'user2'. Object.keys(cache).length returns 2.
  2. Step 2: Identify memory issue

    Since keys are never removed, cache grows indefinitely, causing a memory leak.
  3. Final Answer:

    2; Memory leak due to unbounded cache growth -> Option B
  4. Quick Check:

    Cache size = 2, leak if keys never removed [OK]
Hint: Uncleared caches cause leaks; count keys to check size [OK]
Common Mistakes:
  • Thinking cache is empty initially
  • Assuming syntax error without checking code
  • Confusing undefined with empty object
4. You have this code causing a memory leak:
const listeners = [];
function addListener(emitter, callback) {
  emitter.on('data', callback);
  listeners.push({emitter, callback});
}
// Later you forget to remove listeners

What is the best fix to prevent the leak?
medium
A. Remove listeners with emitter.removeListener and clear the listeners array
B. Do nothing; Node.js cleans up automatically
C. Replace emitter.on with emitter.once
D. Use global variables instead of arrays

Solution

  1. Step 1: Identify cause of leak

    Listeners are added and stored in an array but never removed, causing memory to stay used.
  2. Step 2: Apply fix to remove listeners and clear references

    Use emitter.removeListener with stored callbacks and clear the listeners array to free memory.
  3. Final Answer:

    Remove listeners with emitter.removeListener and clear the listeners array -> Option A
  4. Quick Check:

    Remove listeners + clear refs = fix leak [OK]
Hint: Always remove event listeners and clear stored references [OK]
Common Mistakes:
  • Assuming Node.js auto-cleans listeners
  • Using emitter.once without removing listeners
  • Using global variables increases leaks
5. You have a Node.js app caching user sessions in a global object. Over time, memory usage grows unexpectedly. Which combined approach best prevents this memory leak?
hard
A. Use global variables for caching without cleanup
B. Store all sessions indefinitely to avoid losing data
C. Implement session expiration and remove expired sessions from cache regularly
D. Avoid using any caching to prevent leaks

Solution

  1. Step 1: Understand the problem with indefinite caching

    Storing sessions forever causes the cache to grow without limit, leading to memory leaks.
  2. Step 2: Apply session expiration and cleanup

    Removing expired sessions regularly frees memory and prevents leaks while keeping useful data.
  3. Final Answer:

    Implement session expiration and remove expired sessions from cache regularly -> Option C
  4. Quick Check:

    Expire and clean cache to prevent leaks [OK]
Hint: Expire and clear cached data regularly to avoid leaks [OK]
Common Mistakes:
  • Keeping all data forever causes leaks
  • Avoiding caching is not practical
  • Using globals without cleanup worsens leaks