Diagnosing and Fixing Memory Leaks in Node.js
Track Node.js memory growth with process.memoryUsage, heap snapshots, retaining paths, and bounded caches instead of guessing from RSS alone.
TechSilo
AI-assisted and human-curated
A Node.js process that grows from 150 MB to 1.5 GB over several hours may have a leak, an unbounded cache, or simply a workload that legitimately retains more data. The first task is to distinguish those cases.
Do not diagnose a leak from one memory reading. Measure memory over time, reproduce the same workload, and use a heap snapshot to find what is being retained.
Understand the memory numbers
Start with Node's built-in memory report:
setInterval(() => {
const memory = process.memoryUsage();
console.log({
rssMb: Math.round(memory.rss / 1024 / 1024),
heapUsedMb: Math.round(memory.heapUsed / 1024 / 1024),
heapTotalMb: Math.round(memory.heapTotal / 1024 / 1024),
externalMb: Math.round(memory.external / 1024 / 1024),
arrayBuffersMb: Math.round(memory.arrayBuffers / 1024 / 1024),
});
}, 10_000).unref();- RSS is the resident memory held by the process, including JavaScript and native allocations.
- heapUsed is the V8 heap currently occupied by JavaScript objects.
- heapTotal is the V8 heap space currently allocated.
- external covers memory associated with native objects bound to JavaScript.
- arrayBuffers reports memory used by ArrayBuffers and related buffers.
A stable heapUsed with rising RSS can point toward native allocations, buffers, fragmentation, or other process-level memory. It does not automatically mean the JavaScript heap is leaking.
Create a heap snapshot
Node provides a built-in V8 API for writing heap snapshots. You can also attach Chrome DevTools to a process started with the inspector.
const { writeHeapSnapshot } = require('node:v8');
process.on('SIGUSR2', () => {
const filename = writeHeapSnapshot();
console.log(`Heap snapshot written to ${filename}`);
});Start the application, reproduce the memory growth, then send SIGUSR2 to the process on supported Unix-like systems. The snapshot can be opened in Chrome DevTools under Memory → Load.
Alternatively, start a local development process with:
node --inspect=127.0.0.1:9229 server.jsKeep the inspector bound to localhost or behind a secure tunnel. Do not expose the debugging port to the public internet. Heap snapshots can contain credentials and user data, so store and share them as sensitive files. Capturing one is synchronous, blocks the event loop, and can require memory roughly twice the current heap size. It can cause an out-of-memory termination, so do it in a controlled environment with enough headroom.
Find the reference that keeps growing
Take a baseline snapshot, run a repeatable workload, and take another snapshot. Compare them and inspect objects whose count or retained size keeps increasing.
Look for:
- Maps, arrays, or caches that only grow.
- Event listeners that remain registered after a request or connection ends.
- Timers that keep closures alive.
- Request handlers retaining large payloads.
- Buffers or native resources that are not released.
- Long-lived promises or queues that never drain.
The retaining path matters more than the object's name. It shows which reference is keeping the object reachable.
A common leak: an unbounded cache
This cache grows for every distinct key and never removes entries:
const results = new Map();
function rememberResult(id, result) {
results.set(id, result);
}If the application sees millions of unique IDs, the map can retain millions of values. A simple size limit is one possible policy:
const results = new Map();
const MAX_ENTRIES = 1_000;
function rememberResult(id, result) {
// Refresh the insertion order for this key.
results.delete(id);
results.set(id, result);
if (results.size > MAX_ENTRIES) {
const oldestKey = results.keys().next().value;
if (oldestKey !== undefined) results.delete(oldestKey);
}
}This is a small FIFO-style example, not a complete cache implementation. Real systems may need TTL expiry, concurrency control, persistence, or an LRU policy. Choose the eviction rule based on the data and access pattern.
Avoid misleading fixes
Deleting a property from an object does not clear a local variable, and forcing garbage collection does not fix a reference that is still reachable. The optional --expose-gc flag can help with controlled experiments, but it is not a production leak remedy.
Likewise, adding a memory-monitoring package does not solve the underlying ownership problem. Use monitoring to find the trend, heap snapshots to locate retained objects, and a targeted cleanup or eviction policy to fix the cause.
For reference, see the official [Node.js V8 API](https://nodejs.org/api/v8.html#v8writeheapsnapshotfilename) and [Node.js debugging guide](https://nodejs.org/en/learn/getting-started/debugging).
Want to put this into practice?
Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.
Related blog posts
Console.log Alternatives for Efficient JavaScript Debugging
Use browser breakpoints, console.table, console.trace, timing APIs, and structured logs to debug without flooding production consoles.
Read postEnvironment Variable Management: Secure Secrets and Deployment Practices
Keep environment configuration safe across local development, CI, and production without leaking API keys into browser bundles or logs.
Read postnpm Scripts Cheat Sheet: Commands, Arguments, and Automation
A developer reference for package.json scripts, npm run, pre/post hooks, environment variables, and safe task automation.
Read postPractical CORS Configuration Security Guide for APIs
Secure cross-origin browser requests with explicit origin allowlists, correct preflight handling, and credential rules.
Read postTroubleshooting CORS Errors in Production: Step-by-Step Guide
Diagnose missing CORS headers, blocked OPTIONS preflights, proxy errors, and credential mismatches without weakening API security.
Read post