> ## Knowledge Base Index
> Fetch the complete knowledge base index at: https://help.squarecloud.app/sitemap.xml
> Use this file to discover available pages before exploring further.
> Pure-Markdown content can be obtained by appending a '.md' suffix to the content URLs listed in the sitemap (without the trailing slash).

# 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 without `removeListener`.
* **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**: `setInterval` that never gets a `clearInterval`.

## 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 `clearInterval` and `clearTimeout`.
* 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.
