Lorixen.
EN

Finding a memory leak in a Node.js app

Short answer: If your Node.js app's memory climbs steadily until the server restarts it or it crashes with an out-of-memory error, something is holding on to data it no longer needs. Confirm the pattern with memory metrics, reproduce it under load outside production, take two or three heap snapshots some minutes apart, and compare them in Chrome DevTools to see which objects keep growing and what is keeping them alive. The usual culprits are caches with no limit, listeners that are never removed and timers or closures that keep old requests around.

Is it really a leak?

Memory use in Node.js goes up and down naturally. The V8 engine allocates memory as your app works and reclaims it in garbage collection cycles, so a sawtooth pattern is normal. A leak looks different: the low points of the sawtooth keep rising over hours or days, and memory never returns to its earlier baseline even when traffic drops.

Before hunting, record memory over time. The Node.js documentation on understanding and tuning memory describes process.memoryUsage(), which reports figures including heapTotal, the memory allocated for the heap, and heapUsed, the memory actually in use within it, as well as external memory used by bindings to C++ libraries and arrayBuffers for buffer-like objects. Logging heapUsed every minute, or sending it to your monitoring tool, shows whether you have a steady climb.

Also rule out the obvious: a recent traffic increase, a deliberate in-memory cache or a memory limit set too low for the workload. The same documentation covers flags such as --max-old-space-size for adjusting the heap limit, but raising the limit only delays a true leak.

Common causes in business apps

  • Unbounded caches. An object or Map used to cache product data, user sessions or API responses that only ever grows.
  • Event listeners added per request. Attaching a listener to a long-lived object, such as a database client or event emitter, inside a request handler and never removing it.
  • Timers and intervals. A setInterval started for each connection or job and never cleared.
  • Closures holding large objects. A callback stored somewhere long-lived that captures a big request body or result set.
  • Global arrays used as queues or logs. Pushing items for later processing without ever removing them.
  • Third-party libraries. Occasionally the leak is in a dependency; snapshots will show objects from its code.

Taking heap snapshots

A heap snapshot is a full picture of the objects in memory and the references between them. The Node.js guide on using heap snapshots lists several ways to capture one:

  • With the inspector: run Node with the --inspect flag, connect Chrome DevTools, open the Memory tab and take a snapshot.
  • With a signal: start Node with --heapsnapshot-signal=SIGUSR2, then send that signal to the process to write a snapshot file. The guide notes this works in Node 12 or later.
  • From code: call writeHeapSnapshot() from the v8 module, for example from an admin-only endpoint.

The same guide carries an important warning. While a snapshot is being created, all other work on the main thread stops, and it can take more than a minute depending on the heap. The snapshot is built in memory and can double the heap size, potentially filling memory and crashing the app. If you take one in production, do it on an instance that can fail without affecting customers, such as one taken out of the load balancer.

Finding the leak by comparison

One snapshot shows what is in memory; two show what is growing. The Node.js guide describes the method: load the snapshots into DevTools, select the newer one and switch the view from Summary to Comparison, then look for large positive deltas and explore the references that caused them in the bottom panel.

A practical routine:

  1. Start the app and let it warm up.
  2. Take snapshot A.
  3. Run a repeatable load, for example a few thousand requests to the endpoint you suspect.
  4. Take snapshot B, run the same load again, then take snapshot C.
  5. Compare B with A and C with B. Objects whose count rises by roughly the same amount each round are your leak candidates.
  6. Follow the retainer chain for one of those objects. It shows what is holding it, often a cache, a listener array or a module-level variable you recognise.

Fixing and preventing

  • Give caches limits. Use a cache with a maximum size or expiry, such as a least-recently-used cache, or move caching to Redis.
  • Remove listeners. Pair every on() with off(), or use once() for one-time listeners. Node's warning about possible EventEmitter memory leaks is a useful hint.
  • Clear timers when the connection or job they belong to ends.
  • Keep request data in request scope. Avoid storing per-request objects in module-level variables.
  • Monitor after deploys. Watch heapUsed for a day after each release so a new leak is caught early.

A worked example

Consider a hypothetical Austin event-ticketing API whose servers were restarted by the hosting platform every few hours for exceeding memory. Memory charts showed heapUsed rising by a similar amount with every busy period and never falling back.

Using a staging copy, a developer took three heap snapshots around repeated load tests. The comparison showed a growing number of seat-map objects retained by a module-level Map, used as a cache keyed by session ID and never cleared. Replacing it with a size-limited cache with a ten-minute expiry flattened the memory curve, and the forced restarts stopped.

FAQ

Is restarting the app regularly a fix?

It hides the symptom. It can be a stopgap while you investigate, but the leak will still cause slowdowns as memory fills.

Can monitoring tools find leaks for me?

Many show memory trends and some capture heap data, but the comparison and reasoning about retainers is still manual work.

Does this apply to serverless Node.js functions?

Less often, because instances are short-lived, but warm instances can still accumulate memory between invocations.

If your Node.js app keeps running out of memory and restarting, describe what the memory graph looks like.

Sources

WhatsAppBook a call