Untitled Lesson
Skill Matrix
UNLOCK NODES BY LEARNING NEW TAGS.
In JavaScript
š» Code Challenge | +75 XP
Write the Node.js/Backend code snippet to implement a Node Memory Management and Garbage Collection pipeline. Include the setup and basic execution steps.
You are reviewing a Node Memory Management and Garbage Collection pipeline and the output is incorrect. Reorder the following pipeline stages in the correct logical order to fix the bug: Input Data, Process, Output.
Task: Reorder the blocks in logical sequence to solve the problem.
A.D.A. Interface
Adaptive Didactic Assistant

Pascual Vila
Frontend Instructor // Code Syllabus
The Error //
Building an in-process cache with a plain object or array that never evicts entries
// Wrong: unbounded, never garbage collected
const cache = {};
app.get('/user/:id', (req, res) => {
cache[req.params.id] = req.body; // grows forever
});
// Correct: bounded cache with eviction
const LRU = require('lru-cache');
const cache = new LRU({ max: 500, ttl: 1000 * 60 * 5 });The Solution //
Anything stored in a module-level object or array stays reachable from the global root for the lifetime of the process, so the Mark-and-Sweep GC can never collect it ā the heap grows until you hit the ~1.4GB default limit and crash. Use a bounded structure (LRU cache with a max size) or move the cache to Redis with a TTL instead of raw JS objects.
The Error //
Registering event listeners inside a function that gets called repeatedly, instead of once
// Wrong: adds a new listener on every request
app.get('/data', (req, res) => {
emitter.on('update', () => res.json({ ok: true }));
});
// Correct: register once outside the handler, or use .once()/removeListener
emitter.on('update', handleUpdate); // registered once at module loadThe Solution //
Every call to emitter.on() attaches a new closure that V8 keeps reachable through the emitter's internal listener array ā if that registration happens inside a per-request handler instead of at startup, thousands of duplicate listeners pile up and each one keeps its captured scope alive, leaking memory and eventually triggering Node's MaxListenersExceededWarning.