How to Debug Memory Leaks in Node.js Production Applications with Heap Snapshots

Why Node.js memory leaks are so painful in production

A Node.js service rarely crashes politely. It runs fine for hours, resident memory creeps up a few megabytes per minute, and then the container gets OOM-killed at 3 a.m. or V8 throws the famous Ineffective mark-compacts near heap limit Allocation failed – JavaScript heap out of memory. Restarting the pod hides the problem for another day, and the cycle repeats.

This guide is a hands-on node.js memory leak debugging workflow built for live services, not toy examples. You will learn how to confirm you actually have a leak, how to capture heap snapshots safely from a running production process, how to compare two snapshots in Chrome DevTools to isolate the exact retained objects, and how to fix the three patterns that cause the vast majority of real-world leaks: event listener accumulation, unbounded caches and lingering timers.

Step 1: Confirm it is a leak, not just normal heap growth

V8 is lazy on purpose. It grows the old space until it gets close to the limit, then does a major GC. A sawtooth memory graph is healthy. A staircase that never comes back down is a leak.

Know your memory numbers

Metric What it means Leak signal
rss Total resident memory of the process, including native allocations and Buffers Grows forever and never drops after GC
heapTotal Memory V8 reserved for the JS heap Keeps expanding toward --max-old-space-size
heapUsed Live JS objects after the last GC Baseline after each major GC keeps rising
external Native memory bound to JS objects (Buffers, some addons) Rising here points to Buffers or native code, not the JS heap
arrayBuffers Memory for ArrayBuffer and Buffer instances Streams or file uploads retained too long

Expose the numbers so you can chart them. A five line interval is enough to get started:

setInterval(() => {
  const m = process.memoryUsage();
  console.log(JSON.stringify({
    t: Date.now(),
    rss: Math.round(m.rss / 1048576),
    heapUsed: Math.round(m.heapUsed / 1048576),
    heapTotal: Math.round(m.heapTotal / 1048576),
    external: Math.round(m.external / 1048576)
  }));
}, 30000).unref();

If you already run Prometheus, prom-client with collectDefaultMetrics() gives you nodejs_heap_size_used_bytes and process_resident_memory_bytes out of the box. Plot a 24 hour window and look at the post-GC baseline, which is the lowest point of each sawtooth. If that floor rises steadily, you have a leak.

A quick sanity test before you dig in

  1. Run your service with GC traces on a staging instance: node --trace-gc --max-old-space-size=512 server.js.
  2. Fire a repeatable load burst (for example autocannon -c 50 -d 60 http://localhost:3000/api/orders).
  3. Stop the load and wait 60 seconds.
  4. Force a GC round if you started with --expose-gc, then read heapUsed.
  5. Repeat the cycle three times. If heapUsed after idle is clearly higher after each cycle, the leak is reproducible and you can move to snapshots.

Important: a leak that only appears under production traffic is still a leak. Do not block on reproducing it locally. The snapshot workflow below works on live processes.

memory leak server

Step 2: Capture heap snapshots from a live Node.js process

A heap snapshot is a full graph of every object V8 is keeping alive, with the retention paths that explain why each object survives GC. It is the single most valuable artifact in node.js memory leak debugging. You have four practical ways to get one.

Option A: Write a snapshot from inside the process (safest for production)

The v8 module can dump a snapshot to disk on demand. Trigger it with a signal so you never need to expose a debugger port:

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

process.on('SIGUSR2', () => {
  const file = path.join('/tmp', `heap-${process.pid}-${Date.now()}.heapsnapshot`);
  const written = v8.writeHeapSnapshot(file);
  console.log('heap snapshot written to', written);
});

Then from the host or container:

kill -USR2 <pid>
# kubernetes
kubectl exec -it my-pod -- kill -USR2 1
kubectl cp my-pod:/tmp/heap-1-1761724800000.heapsnapshot ./snap-1.heapsnapshot

Warning: writing a snapshot pauses the event loop for the duration of the dump (hundreds of milliseconds to several seconds on a multi-gigabyte heap) and temporarily increases RSS. Always do it on a drained instance, a canary pod, or a replica removed from the load balancer.

Option B: Automatic snapshot right before the crash

If the process dies before you can react, let Node capture the evidence for you:

node --heapsnapshot-near-heap-limit=2 --max-old-space-size=2048 server.js

Node writes up to two snapshots when the heap approaches its limit. Make sure the working directory is a writable volume with enough free disk space, because snapshots can be as large as the heap itself.

Option C: Chrome DevTools inspector

Start or signal the process into inspect mode:

# start with the inspector bound to localhost only
node --inspect=127.0.0.1:9229 server.js

# or enable it on an already running process
kill -USR1 <pid>

# tunnel from your machine to the server, never expose 9229 publicly
ssh -L 9229:127.0.0.1:9229 user@prod-host

Open chrome://inspect in Chrome or Edge, click inspect on the remote target, then go to the Memory panel. You get three profile types:

  • Heap snapshot: the full object graph at a point in time. Your main tool for comparison.
  • Allocation instrumentation on timeline: live recording that shows which allocations survive. Great for catching a leak while replaying traffic.
  • Allocation sampling: low overhead statistical sampling by call stack. The only one you should consider running under real load.

Option D: clinic.js for a fast first diagnosis

Clinic.js gives you a verdict before you ever open DevTools. Run it against a staging instance with a representative load generator:

npm i -g clinic autocannon

# step 1: is it memory, event loop, I/O or CPU?
clinic doctor --on-port 'autocannon -c 50 -d 120 http://localhost:3000/' -- node server.js

# step 2: where is memory being allocated?
clinic heapprofiler --on-port 'autocannon -c 50 -d 120 http://localhost:3000/' -- node server.js

clinic doctor prints a plain language recommendation and charts memory alongside event loop delay. clinic heapprofiler renders a flame graph of allocation sites, so you immediately see which function is responsible for most of the bytes. Use clinic to find the suspect file, then use heap snapshot comparison to prove exactly which objects are retained and by whom.

Step 3: Compare two snapshots and find the retained objects

One snapshot tells you what is in memory. Two snapshots tell you what is growing. That difference is where the leak hides.

The three snapshot method

  1. Snapshot 1 (baseline): take it after startup and after a short warm-up so lazy caches and connection pools are already populated.
  2. Apply load: replay the exact traffic pattern you suspect, for example 10,000 requests to the endpoint that correlates with the memory growth.
  3. Snapshot 2: take it right after the load finishes and the heap has settled.
  4. Apply the same load again, then take Snapshot 3.
  5. Compare 2 against 1, then 3 against 2. Anything that grows by roughly the same amount in both deltas is your leak. Anything that grows once and then stabilizes is just a warm cache.

DevTools always forces a full GC before writing a snapshot, so everything you see in a snapshot is genuinely reachable. Nothing in there is garbage waiting to be collected.

Reading the comparison view

Load both .heapsnapshot files into the DevTools Memory panel (drag and drop works), select the second one, and switch the dropdown from Summary to Comparison, with the baseline set to the first snapshot. Sort by Delta or Size Delta.

Column How to use it
# New / # Deleted / Delta A constructor with thousands of new objects and near zero deleted is the prime suspect
Shallow Size Memory held by the object itself. Useful for strings, Buffers and typed arrays
Retained Size Memory freed if this object disappeared. This is the number that matters for leaks
Retainers panel The chain of references from a GC root down to the object. Read it bottom-up to find the owner
Distance Hops from the root. Short distance plus huge retained size usually means a global or module-level container

Useful filters while you hunt:

  • Type (closure) in the class filter to find functions holding scopes alive. Closures are the number one mechanism behind accidental retention.
  • Look for (array), Map, Set and Object entries with a retained size in the tens of megabytes.
  • Search for your own class names and request-scoped object names. Seeing 50,000 instances of RequestContext after the request already finished is a smoking gun.
  • Yellow-highlighted entries in DevTools are directly reachable from JS. Red entries are detached nodes held only by a yellow parent.

Follow the retainer chain, not the object count

Beginners stop at “there are 120,000 strings”. That is useless. Click one, open the Retainers tree, and keep expanding until you hit something you recognize: a module-level Map, an EventEmitter‘s _events object, a Timeout handle, or a closure defined in your own file. That path is your bug report.

memory leak server

Step 4: The three leak patterns that cause most production incidents

Pattern 1: Event listener accumulation

Symptom in the snapshot: a growing (closure) count, large _events or EventEmitter retained size, and often a warning in the logs:

MaxListenersExceededWarning: Possible EventEmitter memory leak detected.
11 data listeners added to [Socket]. Use emitter.setMaxListeners() to increase limit

The classic bug is attaching a listener to a long-lived emitter from inside a short-lived request handler:

// LEAK: every request adds a listener to a process-wide emitter
app.get('/orders/:id', async (req, res) => {
  bus.on('order:updated', (order) => {
    if (order.id === req.params.id) res.write(JSON.stringify(order));
  });
  // listener keeps req, res, and the whole closure scope alive forever
});

Fixes:

  • Always remove what you add: res.on('close', () => bus.off('order:updated', handler)).
  • Use emitter.once() when the event can only happen one time.
  • Pass an AbortSignal: bus.on('order:updated', handler, { signal: controller.signal }) and call controller.abort() when the request ends. One abort removes every listener registered with that signal.
  • Lower the ceiling to fail fast in staging: emitter.setMaxListeners(5), never raise it to silence the warning.
  • Audit at runtime: bus.eventNames().map(n => [n, bus.listenerCount(n)]) exposed on a debug route.

Pattern 2: Unbounded caches and module-level collections

Symptom in the snapshot: a single Map, Object or Array with an enormous retained size and a very short distance from the root. The retainer chain ends at a module scope.

// LEAK: grows with every unique key, forever
const cache = new Map();

function getUser(id) {
  if (!cache.has(id)) cache.set(id, fetchUserFromDb(id));
  return cache.get(id);
}

This also covers memoization helpers, de-duplication sets, in-memory rate limiters keyed by IP, request logs kept “for debugging”, and session objects stored in a plain object.

Fixes:

  • Use a bounded LRU with TTL instead of a raw Map. lru-cache with max, maxSize and ttl is the standard answer.
  • Move shared state to Redis. A cache that must survive restarts does not belong in process memory anyway.
  • When keys are objects and you only want them alive while something else holds them, use WeakMap or WeakSet.
  • For value-keyed caches of objects, consider WeakRef plus FinalizationRegistry, but only if you genuinely need it. These are sharp tools.
  • Never cache the full response body of large payloads. Cache an identifier and re-stream.
  • Add a metric per cache: cache_entries{name="user"}. A leak you can see on a dashboard is a leak you can alert on.

Pattern 3: Lingering timers, intervals and dangling promises

Symptom in the snapshot: many Timeout objects, each retaining a closure, which retains a request context, which retains a response body. Distance from root is short because timers are rooted in libuv handles.

// LEAK: an interval that nobody clears, capturing a big payload
function startSync(payload) {
  setInterval(() => push(payload), 5000);  // never cleared
}

// LEAK: a timeout kept alive after the request is gone
const t = setTimeout(() => finish(req, res), 30000);  // no clearTimeout on early return

Fixes:

  • Store every handle and clear it in the teardown path: const t = setTimeout(...); try { ... } finally { clearTimeout(t); }.
  • Call .unref() on background timers that must not keep the process alive.
  • Replace manual timeouts with AbortSignal.timeout(ms) and pass the signal to fetch, streams and emitters.
  • Never leave a promise pending forever. A promise that never settles retains its entire continuation chain. Always race long operations against a timeout and reject.
  • Inspect what is keeping the loop busy: process.getActiveResourcesInfo() returns the list of active handles and requests. Log it periodically in staging.

Bonus patterns worth checking

  • Growing external and arrayBuffers instead of heapUsed: you are retaining Buffers, usually from unconsumed streams. Always consume or destroy a stream, and pipe with pipeline() so errors propagate and resources are released.
  • Global logging context: attaching request payloads to a module-level logger or to an error object you re-throw and store.
  • Observers never disconnected: PerformanceObserver, FileHandle watchers, database change streams.
  • Closures over large parameters: a tiny callback can retain a 20 MB request body simply because it sits in the same scope. Extract the small value you need before creating the closure.
  • A library you trusted: pin versions, read changelogs, and test an upgrade in isolation when snapshots point to node_modules internals.

A production-safe debugging checklist

  1. Set a realistic heap ceiling that matches the container limit, for example --max-old-space-size=1536 inside a 2 GB container, so V8 starts collecting aggressively instead of getting OOM-killed.
  2. Add --heapsnapshot-near-heap-limit=2 and mount a writable volume for the dumps.
  3. Chart rss, heapUsed and external separately. Alert on the post-GC baseline trend, not the peak.
  4. Keep one canary instance out of rotation for snapshots so you never freeze user-facing traffic.
  5. Take at least three snapshots and compare the deltas pairwise.
  6. Fix one pattern at a time, deploy, then verify on the same 24 hour chart. Two simultaneous fixes make it impossible to know what worked.
  7. Add a regression test: run the suspicious code path 10,000 times in a loop, force GC, and assert that heapUsed stays within a threshold.
memory leak server

Tooling comparison

Tool Best for Production overhead
process.memoryUsage() + metrics Detecting that a leak exists and when it started Negligible
v8.writeHeapSnapshot() On-demand snapshot without opening a debug port High during the dump, zero otherwise
Chrome DevTools Memory panel Comparing snapshots, reading retainer chains Analysis is offline, zero on the server
clinic doctor / heapprofiler First diagnosis and allocation hotspots Moderate, use on staging or canary
Allocation sampling profiler Continuous low-overhead allocation tracking Low
APM with heap profiling (Datadog, Dynatrace, N|Solid) Always-on monitoring across many instances Low, but adds a vendor agent

A worked example you can reproduce in five minutes

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

const leaky = [];
const bus = new (require('node:events').EventEmitter)();
bus.setMaxListeners(0); // hides the warning, a real-world anti-pattern

http.createServer((req, res) => {
  const payload = Buffer.alloc(1024 * 50).toString('base64'); // 50 KB per request
  bus.on('tick', () => leaky.push(payload));                  // listener + array leak
  setInterval(() => {}, 60000);                               // timer leak
  res.end('ok');
}).listen(3000);

process.on('SIGUSR2', () => console.log(v8.writeHeapSnapshot()));

Run it, send 2,000 requests, take a snapshot, send 2,000 more, take a second snapshot, then compare. In the Comparison view you will see (string) and (closure) with huge positive deltas, and the retainer chain will land squarely on the leaky array and the emitter’s _events object. That is exactly the shape a real leak takes, just faster.

memory leak server

Key takeaways

  • Trust the post-GC baseline, not the peak, to decide whether memory is leaking.
  • One snapshot is a photo, two snapshots are evidence. Always compare.
  • Retained size plus the retainer chain tells you who is at fault. Object counts alone do not.
  • Most production leaks reduce to listeners that are never removed, caches without bounds, and timers that are never cleared.
  • Make memory observable before the next incident: metrics, bounded caches with gauges, and a snapshot trigger you can fire in one command.

Frequently asked questions

How do I fix “JavaScript heap out of memory” in Node.js?

Raising --max-old-space-size only buys time. First confirm whether the heap grows without bound. If it does, find the retained objects with a snapshot comparison and fix the retention. If the workload genuinely needs more memory (large batch processing, big JSON parsing), then increase the limit to roughly 75 percent of the container memory and stream your data instead of buffering it.

Can I take a heap snapshot on a live production server?

Yes, but it pauses the event loop and temporarily increases RSS, so route traffic away from that instance first or use a dedicated canary. Prefer v8.writeHeapSnapshot() over opening the inspector port. If you must use the inspector, bind it to 127.0.0.1 and reach it over an SSH tunnel. Never expose port 9229 to the internet, it is equivalent to remote code execution.

What is the difference between shallow size and retained size?

Shallow size is the memory the object occupies by itself. Retained size is all the memory that would be freed if that object became unreachable, including everything it exclusively references. For leak hunting, retained size is the number that identifies the root cause.

Why does my RSS grow while heapUsed stays flat?

The leak is outside the JS heap. Check external and arrayBuffers for Buffer retention, look at native addons, and remember that heap fragmentation and the allocator can keep freed pages resident. Tools like valgrind or an allocator switch to jemalloc are the next step in that case, not heap snapshots.

Is clinic.js or Chrome DevTools better for memory leak debugging?

They answer different questions. Use clinic.js to get a quick verdict and find which functions allocate the most. Use Chrome DevTools heap snapshot comparison to prove which objects stay alive and which reference keeps them. The fastest workflow uses clinic first, DevTools second.

How often should I check for memory leaks?

Continuously, through metrics. A dashboard with the post-GC heap baseline per service plus an alert when it rises more than a set percentage over 24 hours will catch leaks long before an OOM kill. Add a memory assertion to your load tests so new leaks are caught in CI rather than in production.

Need help? If your Node.js service is restarting on a schedule to stay alive, that is a leak, not a maintenance window. Our engineering team at Santiance runs this exact workflow on production systems, from instrumentation to the root cause fix. Get in touch and we will help you find it.

Leave a Comment