DebuggingFeaturedNode.jsPerformance

Node.js Memory Leaks: How to Detect and Diagnose Them

6 Mins read
Node.js Memory Leaks: How to Detect and Diagnose Them

Find the Retained Objects: A Practical Guide to Node.js Memory Leaks

A Node.js service that starts fast but gradually consumes more memory can be difficult to diagnose. A rising memory graph may point to a leak, but it can also reflect normal garbage collection, a traffic spike, or memory allocated outside the JavaScript heap. To find the cause, compare memory over time, reproduce the growth, and use heap snapshots to identify objects that remain reachable when they should not.

This guide walks through a practical Node.js memory leak investigation: what to measure, how to capture and compare snapshots, and how to avoid common diagnostic traps.

What a Node.js Memory Leak Looks Like

JavaScript’s garbage collector reclaims objects that are no longer reachable from active code. A leak occurs when an application unintentionally keeps references to objects it no longer needs. Because those references remain, garbage collection cannot free the objects.

A common warning sign is a steadily rising heapUsed value under similar traffic, especially when it does not settle after garbage collection. But memory growth alone is not proof of a leak. A cache may be warming up, traffic may have increased, or a dependency may be allocating native memory.

Know which memory number you are looking at

Node’s process.memoryUsage() reports several useful values:

  • heapUsed: JavaScript heap memory currently occupied by objects.
  • heapTotal: memory currently allocated for the JavaScript heap. It may be larger than heapUsed.
  • external: memory associated with native objects bound to JavaScript, such as some buffers.
  • arrayBuffers: memory used by ArrayBuffer and related objects, including many Node.js buffers. This is included in external.
  • rss: resident memory used by the whole process, including the heap, native allocations, code, and other areas.

The pattern matters. If heapUsed climbs between comparable workloads, investigate retained JavaScript objects. If rss grows while heapUsed stays fairly steady, check buffers, native dependencies, fragmentation, and other non-heap usage. These readings are clues, not diagnoses.

Start with Low-Risk Monitoring

Before taking snapshots, establish when and where memory grows. Add lightweight measurements to a test environment or use your monitoring platform to track memory alongside request rate, latency, and errors.

const formatMB = (bytes) => (bytes / 1024 / 1024).toFixed(1);

setInterval(() => {
  const memory = process.memoryUsage();

  console.log({
    rssMB: formatMB(memory.rss),
    heapUsedMB: formatMB(memory.heapUsed),
    heapTotalMB: formatMB(memory.heapTotal),
    externalMB: formatMB(memory.external),
    arrayBuffersMB: formatMB(memory.arrayBuffers)
  });
}, 30_000).unref();

Use this kind of logging as a starting point, not as a complete observability system. Avoid logging every second in a busy production service, and make sure your logging pipeline can handle the output. A dashboard that shows trends is usually more useful than isolated numbers.

Compare like with like

  1. Record a baseline after startup and warm-up.
  2. Run a repeatable workload, such as a fixed number of requests or jobs.
  3. Allow the service to become idle, then record memory again.
  4. Repeat the same workload and compare the post-workload readings.

Look for a rising post-workload baseline over repeated cycles. Heap usage naturally fluctuates, and the garbage collector does not necessarily run immediately when an object becomes unreachable. A single reading cannot distinguish that normal behavior from a leak.

Capture and Compare Heap Snapshots in Node

Heap snapshots show objects on the JavaScript heap and the references keeping them reachable. They are especially useful when heapUsed rises consistently and you need to find which object types or retaining paths account for the growth.

Use the inspector in a controlled environment

For local diagnosis, start the application with the inspector enabled:

node --inspect app.js

Connect to the process from Chrome DevTools using chrome://inspect, open the Memory panel, and choose Heap snapshot. Capture one snapshot after warm-up, run the repeatable workload, let the application settle, and capture another. In the comparison view, inspect object types with increasing counts or retained size. Select an object and follow its retaining path to see what is keeping it alive.

You can also use Node’s built-in V8 module to write a snapshot to a file:

const v8 = require('node:v8');

const file = v8.writeHeapSnapshot();
console.log(`Heap snapshot written to ${file}`);

Heap snapshots can pause the process and require significant memory to create. Take them in a test or staging environment when possible. A snapshot can temporarily push a memory-constrained process over its limit, and snapshots may contain sensitive strings or application data. Store them securely and remove them when the investigation is complete.

What to look for in a snapshot

  • Large or growing arrays, maps, sets, or plain-object collections.
  • Repeated instances of a class that should have a limited lifetime.
  • Closures, listeners, or timers retaining request-specific data.
  • Unexpected paths from a long-lived root, such as a global variable or module-level cache.

Focus on retained objects and their paths, not just their shallow size. A small object can keep a much larger object graph alive. A high object count can also be harmless if the objects are short-lived and collectible. Compare snapshots after equivalent workloads and confirm that the suspected objects continue to accumulate.

Common Leak Patterns and Fixes

Unbounded caches and collections

A module-level map can keep every result ever seen for the lifetime of the process. If the data set can grow without limit, use a maximum size, a time-to-live policy, or an external cache with an eviction strategy.

// Risky: entries stay reachable until explicitly removed.
const cache = new Map();

function remember(key, value) {
  cache.set(key, value);
}

Weak collections can help when entries should not keep their object keys alive, but they are not a universal replacement for a bounded cache. Weak collections cannot be iterated, and they do not solve growth caused by other strong references.

Listeners that outlive their owners

Registering an event listener for every request, connection, or component can retain its callback and any variables captured by that callback. Remove listeners when they are no longer needed, or attach cleanup to the same lifecycle that created them.

function watch(emitter, handler) {
  emitter.on('data', handler);

  return () => {
    emitter.off('data', handler);
  };
}

Do not use removeAllListeners() as a blanket cleanup if other parts of the application rely on those listeners. Remove the specific listener you own.

Timers and unfinished asynchronous work

Intervals, retry loops, pending promises, and queued jobs can retain state indefinitely if they are never stopped or settled. Clear timers during shutdown or when their associated task ends. Also check that error paths do not leave work queued or listeners attached.

Buffers and native allocations

If external, arrayBuffers, or rss grows while heap usage remains stable, investigate buffer lifetimes and native add-ons rather than assuming a JavaScript object leak. A small Buffer view can share a larger backing allocation, so keeping the view alive may retain more memory than expected. Confirm the allocation pattern with profiling and a minimal reproduction before changing code.

Garbage Collection: Useful Signal, Not a Cure

Garbage collection is automatic, but its timing depends on runtime conditions. Forcing a collection may make a diagnostic comparison easier, but it does not fix references that keep unwanted objects alive. Avoid adding forced garbage collection to normal application logic as a supposed leak remedy.

For a controlled test, Node can expose the garbage collector with --expose-gc:

node --expose-gc app.js

Then a test harness can call global.gc() before a measurement. Use this only to support diagnosis, and compare measurements consistently. It is not a substitute for profiling, and it may affect performance. For deeper investigation, Node’s diagnostic reports, CPU and heap profiling tools, and runtime tracing can provide additional evidence; choose tools that match the suspected memory area.

Production Safety and Common Pitfalls

  • Do not expose the inspector publicly. It can provide powerful control over the process. Bind it to a trusted interface and restrict access.
  • Do not treat a larger heap limit as a fix. Raising the limit can delay a crash, but it may also increase memory pressure and hide an unbounded retention problem.
  • Do not compare different workloads. Request volume, payload size, cache state, and concurrency can all change memory usage.
  • Do not rely on one metric. Interpret heapUsed, external, arrayBuffers, and rss together.
  • Do not overlook tool overhead. Profiling and snapshot creation consume resources and can alter timing.

For repeatable debugging, use a consistent Node.js version and development setup. FromDev’s guides to setting the Node.js version in VS Code and choosing from 15+ Node.js IDEs can help standardize your workflow. If your service uses native code, investigate those boundaries separately; the principles behind thread-safe memory copying in C and C++ are relevant when reviewing native memory handling, but do not by themselves diagnose a Node.js leak.

Conclusion

To diagnose a Node.js memory leak, first identify which part of process memory is growing. Measure under repeatable conditions, compare post-workload baselines, and use heap snapshots to trace retained JavaScript objects back to their owners. If heap usage is stable while external memory or RSS rises, broaden the investigation to buffers, native code, and the runtime environment.

The key is to verify a suspected leak before changing limits or forcing garbage collection. Find the reference or allocation pattern that explains the growth, fix its lifecycle or add an appropriate bound, then repeat the same workload to confirm that memory stabilizes.

Leave a Reply

Your email address will not be published. Required fields are marked *