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
Common Memory Leak Patterns in Node.js
📖 Scenario: You are building a simple Node.js application that processes user requests and stores session data temporarily. You want to understand common memory leak patterns so you can avoid them in your code.
🎯 Goal: Learn to identify and fix common memory leak patterns in Node.js by creating a small app that simulates these leaks and then applies fixes.
📋 What You'll Learn
Create an object to store session data
Add a configuration variable to limit session storage size
Implement a function to add sessions and simulate a memory leak
Fix the memory leak by removing old sessions
💡 Why This Matters
🌍 Real World
Web servers and applications often store user sessions or cache data in memory. Without limits, this can cause memory leaks and crash the server.
💼 Career
Understanding and fixing memory leaks is crucial for backend developers to build stable and scalable Node.js applications.
Progress0 / 4 steps
1
Create session storage object
Create an object called sessionStore to hold user session data. Initialize it as an empty object.
Node.js
Hint
Use const sessionStore = {} to create an empty object.
2
Add session limit configuration
Add a constant called MAX_SESSIONS and set it to 100. This will limit how many sessions we keep in sessionStore.
Node.js
Hint
Use const MAX_SESSIONS = 100; to set the session limit.
3
Simulate memory leak by adding sessions
Write a function called addSession that takes sessionId and data. Add the data to sessionStore using sessionId as key. Do not remove old sessions yet, which causes a memory leak.
Node.js
Hint
Define function addSession(sessionId, data) and assign data to sessionStore[sessionId].
4
Fix memory leak by removing old sessions
Update addSession to check if sessionStore has more keys than MAX_SESSIONS. If yes, remove the oldest session key before adding the new one. Use Object.keys(sessionStore) to get keys and delete to remove a session.
Node.js
Hint
Check the number of keys with Object.keys(sessionStore).length. Remove the first key with delete sessionStore[oldestSession].
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
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.
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.
Final Answer:
Keeping references to objects that are no longer needed -> Option A
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?
The correct method to remove a specific listener is removeListener(event, callback).
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.
Final Answer:
emitter.removeListener('event', callback); -> Option D
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
Step 1: Analyze the code output
The cache object stores two keys: 'user1' and 'user2'. Object.keys(cache).length returns 2.
Step 2: Identify memory issue
Since keys are never removed, cache grows indefinitely, causing a memory leak.
Final Answer:
2; Memory leak due to unbounded cache growth -> Option B
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
Step 1: Identify cause of leak
Listeners are added and stored in an array but never removed, causing memory to stay used.
Step 2: Apply fix to remove listeners and clear references
Use emitter.removeListener with stored callbacks and clear the listeners array to free memory.
Final Answer:
Remove listeners with emitter.removeListener and clear the listeners array -> Option A
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
Step 1: Understand the problem with indefinite caching
Storing sessions forever causes the cache to grow without limit, leading to memory leaks.
Step 2: Apply session expiration and cleanup
Removing expired sessions regularly frees memory and prevents leaks while keeping useful data.
Final Answer:
Implement session expiration and remove expired sessions from cache regularly -> Option C
Quick Check:
Expire and clean cache to prevent leaks [OK]
Hint: Expire and clear cached data regularly to avoid leaks [OK]