Memory leak in Node.js: how to find and fix it
What a memory leak is
A memory leak happens when your application allocates memory and never frees it. Over time, RAM usage grows continuously until the process crashes or is killed by the system for running out of memory. In Node.js this is common when objects that should be discarded stay "stuck" through references that are never removed.
Symptoms
- RAM usage rises steadily and never goes back down.
- The application gets slower as the hours pass.
- Periodic crashes followed by restarts.
- Messages like
JavaScript heap out of memory.
Most common causes
- Event listeners not removed: registering
on(...)repeatedly withoutremoveListener. - Closures and global variables: data piling up in variables that live for the whole execution.
- Infinite cache: storing items in an object or Map without ever clearing it.
- Timers:
setIntervalthat never gets aclearInterval.
How to identify it
1. Monitor memory usage. Track RAM usage over time. A graph that only goes up is the main sign.
2. Take a heap snapshot. Run the application with the inspection flag node --inspect your-app.js, open chrome://inspect in the browser, capture two snapshots a few minutes apart, and compare what grew.
3. Use process.memoryUsage(). Periodically log process.memoryUsage().heapUsed to see the trend.
How to fix it
- Always remove listeners that will no longer be used.
- Set a limit for caches (e.g., an LRU cache) and expire old items.
- Clear timers with
clearIntervalandclearTimeout. - Avoid piling up data in global-scope variables.
Monitoring memory on Square Cloud
On Square Cloud you track your application's RAM usage in real time from the Dashboard. If usage goes over your plan's limit, the platform warns you — so it's easy to spot a leak before it brings the application down. Combine monitoring with the best practices above to keep your bot or API stable 24/7.
Updated on: 06/13/2026
Thank you!
