What is a Node.js memory leak, and how do you tell it apart from normal memory growth?

In a garbage-collected runtime, a leak is memory that stays reachable when it should not. V8 frees only objects that nothing references, so a leak is a forgotten reference: a module-level Map keyed by request ID, a listener never removed, a closure captured by a timer. For backend and platform engineers running monoliths for weeks between deploys, a small per-request leak eventually becomes an out-of-memory crash.

process.memoryUsage() returns five fields. Sample them on a fixed interval, for example every 30 seconds, and send them to your metrics pipeline so you see trends over hours rather than single readings.

Field What it measures What growth suggests
rss Total resident memory of the process Anything, including native memory
heapTotal Memory V8 has reserved for its heap V8 sizing the heap to demand
heapUsed Memory occupied by live JS objects and garbage not yet collected JS objects being retained
external C++ memory tied to JS objects Buffers, native bindings
arrayBuffers ArrayBuffer and Buffer memory, also counted in external Buffer retention

A healthy process shows a sawtooth. heapUsed climbs, drops after each collection, and returns to a stable floor. A leak shows a post-GC floor that keeps rising under steady load. If rss climbs while heapUsed stays flat, look at Buffers, native addons, or allocator fragmentation. Heap snapshots will not show those.

Early growth is often expected. Lazy initialization, warming caches, and filling connection pools all raise memory at startup and then level off. Judge the baseline only after it has stabilized.

// Sample process.memoryUsage() every 30s and log one JSON line per sample.
// Ship these lines to your metrics pipeline and chart them over hours.
const SAMPLE_INTERVAL_MS = 30_000;
const MB = 1024 * 1024;

function sampleMemory() {
  const m = process.memoryUsage();
  const sample = {
    ts: new Date().toISOString(),
    rssMb: +(m.rss / MB).toFixed(1),
    heapTotalMb: +(m.heapTotal / MB).toFixed(1),
    heapUsedMb: +(m.heapUsed / MB).toFixed(1),
    externalMb: +(m.external / MB).toFixed(1),
    // arrayBuffers is already included in external; track it separately
    // to spot Buffer retention specifically.
    arrayBuffersMb: +(m.arrayBuffers / MB).toFixed(1),
    // A large gap between rss and heapTotal + external hints at native
    // memory or allocator fragmentation that heap snapshots will not show.
    nonHeapMb: +((m.rss - m.heapTotal - m.external) / MB).toFixed(1),
  };
  console.log(JSON.stringify(sample));
}

const timer = setInterval(sampleMemory, SAMPLE_INTERVAL_MS);
// unref() so the sampler never keeps the process alive on its own.
timer.unref();
sampleMemory();

// Reading the series: look at the low points of heapUsedMb (the post-GC
// floor) after warm-up. A floor that levels off is normal; a floor that
// keeps rising under steady load is a leak candidate.

A minimal sampler that logs all five process.memoryUsage() fields every 30 seconds as JSON lines, so you can chart the post-GC heapUsed floor and compare rss growth against heap growth over time.

Why diff heap snapshots instead of watching RSS graphs or reviewing code?

A memory dashboard answers one question: is the process growing? RSS and heapUsed graphs can confirm a leak, but they cannot tell you whether the growth is 40,000 orphaned request contexts or one array that keeps getting longer. Reviewing code to find out is slow in a monolith. Hundreds of modules register listeners, populate caches, and hold closures, and any of them could be the culprit. Reading them all is guesswork, and each guess usually means a deploy followed by hours of waiting to see whether the graph flattens.

Heap snapshot diffing replaces that guessing with evidence. Capture snapshots under controlled, repeated load and compare them. Objects that should have been collected but survive every round stand out by constructor name and count. The snapshot also shows the retainer path, which is the chain of references from a GC root down to the leaked object. That chain is often specific enough to point you at a single module-level Map, an event emitter, or a closure. The investigation shrinks from "somewhere in the codebase" to one reference you can break, and you can confirm the fix with another diff instead of another week of watching graphs.

When it fits, and when it doesn't

Use snapshot diffing once you have confirmed that the post-warmup baseline keeps rising and that heapUsed rises with it.

Avoid it in two situations:

  • RSS grows while heapUsed stays flat. The memory lives outside the V8 heap, for example in buffers, native addons, or allocator fragmentation, and snapshots will not show it.
  • The heap is already close to the container's memory limit. Writing a snapshot needs substantial extra memory and pauses the process. On a heap that is nearly full, taking a snapshot can trigger the out-of-memory kill you were trying to diagnose.

When should you use heap snapshot diffing?

Reach for snapshot diffing when these conditions hold together:

  • The post-GC heapUsed floor keeps rising after warm-up under roughly steady load. This is the main signal. A single high reading or a spike that recedes is not enough.
  • heapUsed grows along with rss. That puts the leak inside the V8 heap, where snapshots can see it.
  • The process lives long enough for the leak to matter. Monoliths that run for days or weeks between deploys are the typical case. Processes recycled every few minutes rarely reach an OOM, even with a leak.
  • You see symptoms that point to retained JS objects. Examples include repeated "JavaScript heap out of memory" crashes, restarts by the container runtime for exceeding its memory limit, GC pauses that lengthen as uptime grows, or MaxListenersExceededWarning in the logs.
  • You can reproduce the growth, or you can afford to drain an instance. Snapshots are most useful against a staging reproduction. In production they need an instance taken out of rotation with enough memory headroom to serialize the heap.

It is also worth running a three-snapshot check before a release that changes request lifecycle code, such as middleware, connection handling, or caching. Catching a per-request leak in staging costs less than tracing it after it has been in production for a week.

Use other tools when the growth is outside the heap, when you need the allocating call site rather than the retainer (see the allocation profiling section below), or when memory grows only in step with data you deliberately keep, such as a cache that is still filling toward its configured bound.

How does heap snapshot diffing work?

A heap snapshot is a serialized graph of the V8 heap at one moment. Each node is an object, string, closure, array, or internal V8 structure. Each edge is a reference, such as a property, an array element, a closure's captured variable, or an internal link. The .heapsnapshot file is JSON that encodes this graph, and DevTools rebuilds it for analysis.

Three properties make diffing useful:

  1. Snapshots contain only reachable objects. V8 runs a full garbage collection before writing the snapshot, so anything still present is held by some chain of references. Unlike a raw heapUsed reading, a snapshot does not include garbage that is waiting for collection.
  2. Objects keep stable IDs within a process. While the heap profiler is active, V8 assigns each object an ID that stays the same across snapshots taken from the same process. DevTools uses these IDs to tell which objects are new, which were freed, and which survived. The "Objects allocated between Snapshot 1 and Snapshot 2" filter and the Comparison view's # New, # Deleted, and # Delta columns are both built on them. Snapshots from different processes or restarts cannot be compared this way.
  3. Retained size and retainer paths come from graph analysis. DevTools computes a dominator tree from the GC roots. An object's retained size is the memory that would become unreachable if that object were removed. Its retainer paths are the chains of edges that lead back to a root. These calculations turn a list of millions of objects into a small number of anchors that hold the leaked memory in place.

Diffing takes advantage of these properties. You apply the same workload between snapshots, so any object created per unit of work and still present after more work has passed is something that was meant to be freed and was not. Ranking by delta tells you what is accumulating, and the retainer path tells you what is holding it. The three-snapshot technique below is a disciplined way of choosing when to take those snapshots, so that warm-up allocations and one-off initialization do not look like leaks.

How do you build a reproduction that isolates the leaking route or job?

Snapshot work goes faster when the leak reproduces on demand, away from production. In a monolith, the first job is narrowing hundreds of routes and jobs down to a few suspects.

Narrow the candidates first

Start with the metrics you already have. Line up when heap growth started against deploy history, per-route request counts, and job schedules. A leak that grows with traffic volume usually points to a request handler. Growth in steps at fixed intervals usually points to a scheduled job. If you can, route traffic for one suspect endpoint to a dedicated instance and see whether that instance's heap grows. That tells you more than a code review.

Drive one suspect with a fixed workload

Run a staging instance with production-like configuration: the same pool sizes, cache limits, feature flags, and memory limit. Send it a fixed, repeatable load, either the same request mix at a steady rate or the same job invoked N times. If the workload is identical between runs, a difference in heap growth means something changed in the code.

Don't trust a clean test

Many leaks only show up on paths a happy-path load test never reaches. Examples include listeners attached before a request fails, retries that pile up while a downstream service is slow, and caches keyed by one unusual tenant's data. Deliberately trigger failure paths. Return errors from dependencies, inject latency until timeouts fire, and replay a sample of real production request shapes. A synthetic test that shows no growth is not proof that there is no leak.

This setup takes hours, maybe a day. You get that time back on every later step, because each snapshot comparison and each candidate fix can be checked in minutes instead of waiting days for production memory graphs to drift.

// drive-suspect.mjs: fixed, repeatable workload against ONE suspect route on staging.
// Run: node drive-suspect.mjs   (Node 18+ for global fetch and AbortSignal.timeout)
const BASE = ''; // placeholder staging host
const ROUNDS = 2000;     // same count every run so heap growth is comparable
const CONCURRENCY = 10;  // fixed parallelism, not 'as fast as possible'

// Deterministic mix: happy path plus the paths a clean test skips.
const cases = [
  { name: 'normal',      path: '/api/orders?tenant=t-1001', timeoutMs: 5000 },
  { name: 'rare-tenant', path: '/api/orders?tenant=t-9999-large', timeoutMs: 5000 },
  { name: 'bad-input',   path: '/api/orders?tenant=does-not-exist', timeoutMs: 5000 },
  // Short client timeout aborts mid-request, exercising server-side cleanup on disconnect.
  { name: 'client-abort', path: '/api/orders?tenant=t-1001', timeoutMs: 50 },
];

const tally = {};
async function hit(i) {
  const c = cases[i % cases.length]; // cycle by index: same order every run
  try {
    const res = await fetch(BASE + c.path, { signal: AbortSignal.timeout(c.timeoutMs) });
    await res.arrayBuffer(); // drain the body so the client side does not hold sockets
    tally[`${c.name}:${res.status}`] = (tally[`${c.name}:${res.status}`] ?? 0) + 1;
  } catch (err) {
    tally[`${c.name}:${err.name}`] = (tally[`${c.name}:${err.name}`] ?? 0) + 1;
  }
}

for (let i = 0; i < ROUNDS; i += CONCURRENCY) {
  const batch = [];
  for (let j = i; j < Math.min(i + CONCURRENCY, ROUNDS); j++) batch.push(hit(j));
  await Promise.all(batch);
}

// Confirm each path actually ran; a run with zero errors or aborts proves little.
console.table(tally);

A load driver that hits one suspect route a fixed number of times. It mixes in a rare tenant, invalid input, and client aborts, so each run is identical and covers error and timeout paths.

How does the three-snapshot technique work?

With a reproduction in hand, the three-snapshot technique gives you a repeatable sequence:

 warm-up       N iterations       N iterations
|=========|S1|==================|S2|==================|S3|
 caches,       leak candidates     same objects should
 JIT, pools    get allocated       grow again by ~N

The warm-up matters in a monolith. Module-level caches, connection pools, lazily compiled templates, and JIT-related structures all fill on first use. If you snapshot before they stabilize, every one of them looks like growth. Run the workload until memory plateaus, then take snapshot 1.

Taking a heap snapshot triggers a full garbage collection first. Each snapshot therefore shows only objects that are still reachable, not garbage waiting for the next GC cycle. This is why snapshots are more reliable than a single heap-used reading.

In the Chrome DevTools Memory panel, select snapshot 3, switch the view to Summary, and set the filter to Objects allocated between Snapshot 1 and Snapshot 2. Objects that were created in the middle window and still exist after a further N iterations survived work that should have released them. To check rates, use the Comparison view between snapshots 2 and 3 and sort by # Delta.

The strongest candidates are constructors whose delta tracks N. If 500 requests add about 500 Socket listeners or 500 closures, that is a per-request leak. A one-off allocation, or growth that does not scale with N, is usually a lazy initialization that the warm-up missed.

 ┌─────────────┐  ┌────┐  ┌──────────────┐  ┌────┐  ┌──────────────┐  ┌────┐
 │   Warm-up   │─▶│ S1 │─▶│ N iterations │─▶│ S2 │─▶│ N iterations │─▶│ S3 │
 │ until heap  │  └─┬──┘  │  window A    │  └─┬──┘  │  window B    │  └─┬──┘
 │  plateaus   │    │     └──────────────┘    │     └──────────────┘    │
 └─────────────┘    │                         │                         │
                    ▼                         ▼                         ▼
               ┌─────────┐               ┌─────────┐               ┌─────────┐
               │forced GC│               │forced GC│               │forced GC│
               │then dump│               │then dump│               │then dump│
               └─────────┘               └─────────┘               └─────────┘

 ┌────────────────────────────────────┐   ┌────────────────────────────────┐
 │ Summary view on S3                 │   │ Comparison view, S3 vs S2      │
 │ filter: objects allocated          │   │ sort by # Delta                │
 │ between Snapshot 1 and Snapshot 2  │   │                                │
 │ = alive after window B             │   │ = growth per N iterations      │
 └─────────────────┬──────────────────┘   └───────────────┬────────────────┘
                   └──────────────────┬───────────────────┘
                                      ▼
              ┌──────────────────────────────────────────────┐
              │ delta tracks N          ──▶ per-request leak │
              │ one-off or not N-scaled ──▶ missed lazy init │
              └──────────────────────────────────────────────┘

The three-snapshot sequence: warm up until the heap plateaus, take snapshots S1 through S3 with N iterations of load between each one, and note that every snapshot forces a GC first; DevTools then shows which window-A allocations survived window B and which deltas grow with N.

How do you capture heap snapshots from a running Node process safely?

Node ships three capture paths, and none needs a third-party module.

--inspect with chrome://inspect. Start the process with --inspect, open chrome://inspect, attach, and use the Memory tab's "Take heap snapshot." This is the fastest option during local reproduction. The default bind is 127.0.0.1:9229. Keep it there and reach remote hosts through an SSH tunnel, because an open inspector port grants arbitrary code execution.

v8.writeHeapSnapshot() behind an admin trigger. Call it from a route reachable only on localhost or an authenticated admin path. It writes a .heapsnapshot file and returns the filename. This lets you time each capture between load phases of the three-snapshot run.

--heapsnapshot-signal. Start with --heapsnapshot-signal=SIGUSR2, then run kill -USR2 <pid>. You get no code changes and no network surface. Choose a signal that your process manager or runtime does not already use.

To analyze, open DevTools, go to the Memory tab, and load the files.

Option Effort Production suitability Security exposure
--inspect Low Poor High if bound beyond localhost
writeHeapSnapshot() trigger Medium Good Depends on endpoint auth
--heapsnapshot-signal Low Good Requires shell access

Capture is stop-the-world. The process serves nothing until the write finishes, and on a large heap that pause can be long. Serializing the snapshot can also need memory on the order of the heap size, which can push the process into an OOM kill. Drain the instance and remove it from the load balancer before you capture.

Snapshots contain live strings, including tokens, session data, PII, and secrets. Store them with access control and a short retention limit, and never attach them to public tickets.

node --inspect=127.0.0.1:9229 server.js
ssh -N -L 9229:127.0.0.1:9229 deploy@app-host-01
curl -X POST -H "Authorization: Bearer $ADMIN_TOKEN" \


mkdir -p /var/lib/app/heapdumps && chmod 700 /var/lib/app/heapdumps
cd /var/lib/app/heapdumps
node --heapsnapshot-signal=SIGUSR2 /srv/app/server.js &
APP_PID=$!

kill -USR2 "$APP_PID"

chmod 600 /var/lib/app/heapdumps/*.heapsnapshot

find /var/lib/app/heapdumps -name '*.heapsnapshot' -mtime +7 -delete

Shows the three built-in capture paths (a loopback inspector reached over an SSH tunnel, a localhost-only authenticated trigger, and --heapsnapshot-signal), plus locked-down storage and retention for the resulting .heapsnapshot files.

How do you read retainer paths and recognize common monolith leak patterns?

Open the snapshot in Chrome DevTools, switch the Memory panel to Comparison view against the baseline, and sort by Retained Size. Shallow size is the memory an object holds directly. Retained size is what the garbage collector would free if that object disappeared, including everything reachable only through it. A small Map with a large retained size is usually the leak's anchor.

Select an instance and read the Retainers pane from the top down. Each row names the object holding the one below it. Keep going until you reach a GC root, such as a module-level variable, the global object, or an active timer or handle. The constructor tells you what is leaking. The retainer path tells you why it is still reachable, and the why is what you fix.

Pattern Typical retainer path Usual fix
Unbounded cache or memoization map Map → module closure → system / Context Add a size or TTL bound, or use WeakMap keyed by an object
Module-level registry Array or Set on a module export Unregister on teardown
Per-request listener on long-lived emitter _events → array of listener closures once, or remove the listener in finally
Uncleared timer or interval Timeout → callback closure clearInterval, or unref plus explicit cleanup
Closure capturing req/res IncomingMessage held by a context Copy only the needed fields
Per-request data in globals global → property Pass request data explicitly or use AsyncLocalStorage
Third-party client holding references Client internals → your callbacks Reuse one client, then close it on shutdown

A MaxListenersExceededWarning in the logs is often the first sign of the listener pattern.

Bounding a cache or switching to a WeakMap can change hit rates, latency, or correctness. Have the team that owns the code review the fix before you merge it.

What are the alternatives when snapshots are ambiguous or the leak is outside the V8 heap?

Sometimes a diff points at thousands of Object or Array instances with retainer paths that end in framework internals. In that case you need to know which code allocated them, not only what holds them. Chrome DevTools offers two profiles for this.

Approach What it tells you Overhead Where to run it
Allocation instrumentation timeline Allocating stack for each object still live at the end of recording High, because every allocation is tracked Local reproduction or staging
Allocation sampling profile Statistical breakdown of allocations by call stack Low Staging, or production with care

The instrumentation timeline is precise. It slows the process enough to change request timing, which can hide timing-dependent leaks. Sampling misses small or rare allocations, but it is cheap enough to run long enough to catch slow growth. A practical order is to run sampling first, then use instrumentation on the reproduction once you have a suspect route.

If RSS climbs while heapUsed stays flat, snapshots will not show the leak. Compare the external and arrayBuffers fields of process.memoryUsage() against RSS. Growth there points to Buffers or ArrayBuffers that are still referenced, or to native addons allocating outside V8. If none of those fields move, consider allocator fragmentation. Freed memory that the allocator does not return to the OS still counts toward RSS.

Raising --max-old-space-size and scheduling restarts are mitigations, not fixes. A larger heap delays the OOM, but it also produces larger snapshots and can lengthen GC pauses. Restarts hide the symptom, and they can mask a second leak that later grows into the same restart window.

How do you prove the fix and add guardrails that cut future investigation cost?

Proving the fix means rerunning the exact reproduction that exposed the leak: same route or job, same request mix, same iteration count. Start Node with --expose-gc, call global.gc() before each measurement, and compare post-GC heapUsed across rounds. A fixed build rises during warm-up and then flattens. Take a fresh three-snapshot diff as well. The object type you traced earlier should no longer grow with the number of requests.

For guardrails, sample process.memoryUsage() on an interval and export heapUsed, heapTotal, external, arrayBuffers, and rss (code example below). Alert on the slope of the post-GC baseline, for example the rolling minimum of heapUsed over several hours. Do not alert on a fixed byte threshold. A fixed threshold either fires on legitimate traffic spikes or fires too late to act. A sustained positive slope flags a leak hours before the OOM, and the same rule works regardless of instance size.

Write a runbook that covers:

  • who may trigger a production snapshot,
  • how to drain the instance from the load balancer first,
  • where snapshot files go.

Snapshots contain request bodies, tokens, and user data, so store them in access-controlled, encrypted storage with a short retention period.

Illustrative estimate (assumed numbers, not a benchmark)

Payback (incidents) = one-time hours ÷ (hours per incident before − hours per incident after)

  • One-time cost: harness 16 h + metrics and alerts 8 h + runbook 4 h = 28 h.
  • Before: 3 engineers × 6 h = 18 h per incident.
  • After: 1 engineer × 4 h = 4 h per incident.

28 ÷ (18 − 4) = 2 incidents to pay back the investment.

How can heap snapshot diffing save engineering time?

Most of the time spent on a leak investigation goes into slow feedback loops, not the fix itself. Snapshot diffing shortens those loops in four ways.

  • It replaces deploy-and-wait cycles with minutes-long checks. Without snapshots, each hypothesis means shipping a change and watching production memory for hours or days. With a staging reproduction and the three-snapshot sequence, you can test a hypothesis in a single run of the load driver and confirm or rule it out the same day.
  • It narrows the search before anyone reads code. The Comparison view names the constructor that is growing, and the retainer path names the reference that holds it. Instead of several engineers splitting up a monolith's modules to review, one engineer starts at a specific Map, emitter, or closure and works outward.
  • It makes the fix verifiable. Rerunning the same reproduction and diff gives a clear before-and-after result: the delta for the leaking type either still tracks N or it does not. That avoids the common pattern of merging a plausible fix, closing the ticket, and reopening it a week later when memory climbs again.
  • The setup is reusable. The load driver, memory sampler, slope-based alert, and capture runbook stay in place after the first incident. The next leak is detected earlier, often while the change that caused it is still small and recent, and the investigation starts at the snapshot step instead of from nothing.

The payback calculation in the previous section shows how to reason about this tradeoff. Its inputs are assumed, so substitute your own team's figures for setup effort and per-incident hours. In general, the more often a monolith has memory incidents and the more people each one involves, the sooner the one-time setup pays for itself.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to node.js memory leak heap snapshot, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.