Spring Fresh Sale! - Up To 67% OFF BDIX Hosting + Free Domain
Node.js

How to Profile and Fix Memory Leaks in a Node.js Application

A memory leak is when your Node.js app holds onto memory it no longer needs, so usage climbs over time until the process slows or crashes. The pattern is telling: memory that keeps rising and never comes back down. Here is how to find and fix the cause.

Step 1: Confirm it is really a leak

Watch memory over time under normal load. Healthy apps rise and fall as the garbage collector works. A leak shows a steady upward trend that never recovers, eventually ending in a heap out-of-memory crash. Monitoring helps — see monitoring a Node.js app.

Step 2: Capture heap snapshots

The reliable way to find a leak is to compare heap snapshots taken minutes apart under load. Objects that keep growing between snapshots are your leak. Capture and compare them with Chrome DevTools — see analyzing heap snapshots and debugging with the inspector.

The usual culprits

  • Growing global variables or module-level arrays/maps that are never cleared.
  • Event listeners added but never removed, accumulating over time (watch for the "possible EventEmitter memory leak" warning).
  • Caches with no eviction — they grow forever; use a bounded cache with a size limit or TTL.
  • Closures holding references to large objects longer than needed.
  • Timers that are never cleared.

Step 3: Fix and verify

Once you have identified the growing objects, trace where they are retained, break the reference (remove listeners, bound the cache, clear timers), and re-run your snapshot comparison to confirm memory now stabilises.

Frequently asked questions

My memory rises then falls — is that a leak?

No, that is normal. The garbage collector reclaims memory in cycles, so a saw-tooth pattern is healthy. A leak is a steady climb that never returns to baseline.

What's the fastest way to find the leaking object?

Two heap snapshots taken under load, minutes apart, compared in DevTools. Sort by which object counts grew, and that points you straight at the leak's type and often its source.

Can raising --max-old-space-size fix a leak?

No — it only delays the crash by giving the leak more room. Always find and fix the underlying leak; raising the limit is a stopgap, not a solution.

Was this article helpful?