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

A Node.js memory leak in an API server is almost always a reference problem, not an allocation problem. Some object created while handling a request stays reachable from a long-lived root after the response is sent. That root might be a module-level cache, an event emitter, a timer, or a closure. Because V8's garbage collector only frees unreachable objects, every request adds a little to the retained set, and nothing ever takes it away.

V8 makes this hard to spot. It grows the heap generously, runs major collections lazily, and may hold on to memory it has already freed. A heap that climbs for a while is not proof of a leak. The signal you want is a rising floor: heapUsed measured just after full GCs keeps going up under steady, constant traffic.

Pattern What you see Likely cause
Sawtooth heapUsed rises, drops after GC, and returns to a stable baseline Normal allocation churn
Plateau after warm-up Growth that levels off once caches and JIT state settle Bounded caches, lazy GC
Rising post-GC floor The baseline creeps up with request count JavaScript heap leak
RSS grows, heap flat Process memory rises while heapUsed stays stable Buffers, native addons, allocator fragmentation

RSS graphs alone mislead because they mix the JavaScript heap with external buffers, native allocations, and memory the allocator hasn't returned to the OS. Always plot heap and RSS separately.

The investigation should belong to the engineers who own the service's request lifecycle and its long-lived state. Platform engineers should supply the metrics and the safe snapshot tooling.

Who should use heap snapshot leak hunting?

This technique fits anyone running a long-lived Node.js process whose post-GC heap floor rises with traffic. That usually means HTTP and RPC API servers, WebSocket gateways, queue consumers and background workers. Short-lived processes such as CLI tools, build scripts and serverless functions that are torn down after each invocation rarely need it. Their leaks disappear when the process exits, unless the runtime reuses warm instances across invocations.

Responsibilities within a team break down like this:

  • Service owners, meaning the backend engineers who write the handlers, caches and client wrappers, should run the investigation. Reading a retainer chain needs knowledge of which objects are meant to live for one request and which for the life of the process. The people who wrote that code have that knowledge.
  • Platform and SRE engineers should supply what the investigation depends on: separate heapUsed and RSS metrics, a way to drain an instance from the load balancer, an authenticated way to trigger snapshots, and a secure place to store the files.
  • On-call engineers should know how to recognise a rising post-GC floor and how to capture snapshots without causing an outage. They can then hand reproducible evidence to the service owner without having to diagnose the leak during an incident.

Don't reach for heap snapshots first if rss grows while heapUsed stays flat. A snapshot only covers the V8 heap. That pattern points to native memory, and a different set of tools is needed (see the last section).

How does heap snapshot leak hunting work?

A heap snapshot is a serialized graph of the V8 heap at a single moment. Every JavaScript object, string, closure context, array and internal V8 structure is a node. Every reference between them, such as a property, an array element, a closure's captured context or a Map entry, is an edge. The snapshot also records the GC roots: the global object, the active handles behind timers and sockets, the stack, and V8's internal references.

Before writing the snapshot, V8 runs a full garbage collection. Anything left in the graph is therefore reachable from a root. That is why a snapshot helps with reference leaks. The garbage collector has already decided the objects in it must stay, and the graph records why.

The tooling then derives three views from this graph:

  1. Counts and sizes per constructor. Grouping nodes by constructor name shows which types are numerous or large.
  2. Retained size. DevTools computes which objects dominate others, meaning every path from a root to object B passes through object A. An object's retained size is its own size plus the size of everything it dominates. This is how a small Map shows up as owning hundreds of megabytes.
  3. Retainer paths. For any object, the tool walks the edges backward to a root. This gives you the chain of references that keeps the object alive.

One snapshot shows what exists. Two snapshots taken under controlled load show what changed. A leak is growth proportional to work done, so the method is to hold the workload constant, capture snapshots at fixed intervals, find the constructors whose counts rise by the same amount each interval, and follow their retainer paths back to the long-lived structure in your code. The sections below cover each step: capturing safely, the three-snapshot sequence, reading the views, and the patterns you will usually find at the end of a retainer path.

How do you capture a heap snapshot safely?

Locally: --inspect and DevTools

On a development machine, start the process with node --inspect, open chrome://inspect in Chrome, attach to the target, and use the Memory tab's "Take heap snapshot." Keep the inspector bound to localhost. An inspector port reachable from the network gives anyone who can connect to it the ability to execute arbitrary code inside your process.

Staging: write snapshots to disk

On remote instances, have the process write the file itself. v8.writeHeapSnapshot() writes a .heapsnapshot file and returns its filename, so you can call it from an authenticated admin route or a timer. Alternatively, start Node with --heapsnapshot-signal=SIGUSR2 and send that signal when you want a capture. Avoid SIGUSR1, because Node reserves it for activating the inspector. Either way, copy the file off the host and load it into DevTools on your workstation.

When not to take one

Capturing a snapshot is synchronous. The event loop stops while V8 walks the entire heap, and on a large heap that pause can be long enough to fail health checks and time out in-flight requests. Serializing the heap graph can also require extra memory comparable to the heap itself. On an instance already close to its container limit, the snapshot can be the thing that triggers the OOM kill.

The file contains everything that was live in memory, including bearer tokens, session data, database credentials, and request bodies with personal data. Treat it like a production core dump: restrict who can access it, encrypt it in transit, and delete it when the investigation ends.

For these reasons, reproduce the leak in staging when you can. If the leak only appears under real traffic, remove one production instance from the load balancer, wait for its in-flight requests to finish, and capture snapshots from that instance.

node --inspect=127.0.0.1:9229 server.js
cd /srv/app
node --heapsnapshot-signal=SIGUSR2 server.js &
APP_PID=$!

ps -o rss= -p "$APP_PID"

kill -USR2 "$APP_PID"

ls -lh /srv/app/*.heapsnapshot

chmod 600 /srv/app/*.heapsnapshot
scp /srv/app/*.heapsnapshot analyst@workstation.example.internal:~/dumps/
rm -f /srv/app/*.heapsnapshot

Shows how to bind the inspector to localhost for local debugging, trigger a heap snapshot with --heapsnapshot-signal on a staging or drained instance after checking memory headroom, and then handle the resulting file as sensitive data.

How does the three-snapshot technique work?

Start by warming the process up. Send a few hundred requests that match your test mix and discard the results. The first requests to any Node.js service allocate things that are meant to stay: compiled code, lazily initialized modules, connection pool entries, populated caches. If you snapshot before that settles, the diff fills up with one-time allocations that look like growth.

Then follow the sequence:

  1. Take snapshot 1.
  2. Send exactly N identical requests, for example 1,000.
  3. Take snapshot 2.
  4. Send the same N requests again.
  5. Take snapshot 3.

Wait for in-flight requests to drain before each capture. V8 runs a full garbage collection before it writes a snapshot, so objects that are only temporarily alive drop out, but objects held by pending work stay in.

Keep the load reproducible. Use the same endpoints, the same payloads, a fixed concurrency level and a fixed set of IDs. With a constant request mix, a bounded cache fills during warm-up and stops changing. Anything that keeps growing is then a suspect, not noise from varied traffic.

Next, open snapshot 3 in Chrome DevTools, switch to the Comparison view, and compare it against snapshot 2. Sort by # Delta. Look for constructors whose delta is close to N, or a clean multiple of N, and that grew by the same amount between snapshots 1 and 2. Growth that is proportional to request count and repeats across both intervals is the signature of a leak. A one-off jump is not.

A memory dashboard can tell you that RSS rises over hours. It can't tell you which object type is growing or which request path allocates it. This process answers both questions in a single run, and you can repeat it exactly to confirm a fix.

// drive.mjs - reproducible load for the three-snapshot technique (Node 18+).
// Start the server with: node --heapsnapshot-signal=SIGUSR2 server.js
// Then run:              BASE_URL=<server base URL> node drive.mjs <server-pid>
const pid = Number(process.argv[2]);
const BASE = process.env.BASE_URL; // scheme, host and port of the server under test
if (!BASE || !pid) throw new Error('usage: BASE_URL=<base url> node drive.mjs <server-pid>');
const N = 1000;          // identical batch size between snapshots
const CONCURRENCY = 10;  // fixed, so allocation patterns repeat
const IDS = Array.from({ length: 20 }, (_, i) => `user-${i + 1}`); // fixed ID set
const BODY = JSON.stringify({ sku: 'SKU-1234', qty: 2 });          // fixed payload
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

// Request i always maps to the same endpoint and ID, so every batch is the same mix.
function request(i) {
  const user = IDS[i % IDS.length];
  if (i % 2 === 0) return fetch(`${BASE}/api/orders?user=${user}`);
  return fetch(`${BASE}/api/orders?user=${user}`, {
    method: 'POST', headers: { 'content-type': 'application/json' }, body: BODY,
  });
}

async function run(count) {
  let next = 0;
  const worker = async () => {
    while (next < count) {
      const res = await request(next++);
      await res.arrayBuffer(); // consume the body so nothing stays pending
    }
  };
  await Promise.all(Array.from({ length: CONCURRENCY }, worker)); // all requests drained
}

async function snapshot(label) {
  await sleep(2000);            // let timers and background work from the batch settle
  process.kill(pid, 'SIGUSR2'); // server writes a .heapsnapshot file to its working directory
  console.log(`snapshot ${label} requested`);
  await sleep(15000);           // writing blocks the server; give it time to finish
}

await run(300); // warm-up: fills caches, pools, lazy modules; results discarded
await snapshot(1); await run(N);
await snapshot(2); await run(N);
await snapshot(3);

A load driver that warms up the server, then triggers heap snapshots via --heapsnapshot-signal between two batches of exactly N requests with a fixed endpoint mix, payload, ID set and concurrency, so Comparison-view deltas can be read against N.

How do you read a heap snapshot in Chrome DevTools?

Load the snapshot file into the Memory panel of Chrome DevTools. Two size columns matter, and confusing them sends you after the wrong object.

Metric What it measures When it matters
Shallow size Memory held by the object itself, excluding anything it references Large strings, buffers, typed arrays
Retained size Memory that would be freed if this object were collected, including everything reachable only through it Finding the owner of a leak, such as a cache Map holding thousands of entries

A Map with a small shallow size and a retained size of hundreds of megabytes is a strong lead. Its own bookkeeping is cheap, but it keeps everything it points to alive.

The Summary view groups objects by constructor. It is useful for spotting a type with an implausible count. The Comparison view compares two snapshots and shows new, deleted and delta counts per constructor. A type whose delta grows by roughly the same amount between every pair of snapshots is your candidate.

Counts tell you what is growing. The Retainers panel tells you why it is still in memory. Select an instance, and the panel shows the chain of references that leads back to a GC root, such as a module-level variable, an active timer or an event emitter. Read the chain from the object outward until you reach code you own. That link is usually where the fix goes.

That chain is only readable if the names in it mean something. In a minified bundle, retainers show up as single-letter properties and functions like e or t. Anonymous callbacks appear as generic (closure) entries, with nothing to tell you which handler created them. During an investigation, run an unminified build and give callbacks names. A retainer path that reads onUserCacheMiss → handlers → Router points you to a specific file. An anonymous chain means guessing.

Why do closures leak, and how do they show up in retainer chains?

V8 does not give each closure its own snapshot of the variables it uses. When a function scope contains inner functions, V8 allocates one context object for that scope and stores every variable that any inner function references. All closures created in that scope point to the same context. If one closure outlives the request, it keeps every captured variable in that shared context alive, including variables it never reads.

The minimal leaking example is a route handler that parses a large request body into payload, passes a small inline callback that reads payload to a validation helper, and registers () => log(req.id) on a process-wide event emitter to react to config changes. The listener only uses req.id. Because the validation callback captured payload, payload sits in the same context, and the emitter's listener array now holds the parsed body for the life of the process. Every request adds another listener and another body.

In the Retainers panel, the path to the leaked object reads roughly payload in system / Context → context in () → an entry in the emitter's listener array → _events → your emitter. The system / Context row is the signal: the object is held by a scope, not by a property you assigned.

The fix has two parts. Build the listener in a small factory function that receives only req.id, so its context holds a single string. Then remove the listener when the response emits close. The first part limits what a leak can retain, and the second part removes the leak.

const http = require('node:http');
const { EventEmitter } = require('node:events');
const { randomUUID } = require('node:crypto');

const configEvents = new EventEmitter(); // process-wide, lives forever
const log = (id) => console.log('config changed during request', id);
const validate = (check) => check();

// LEAKY: both arrows share one context holding `payload` and `req`.
function handleLeaky(req, res, body) {
  const payload = JSON.parse(body); // large parsed body
  validate(() => Array.isArray(payload.items)); // pulls `payload` into the context
  // Reads only req.id, but retains the shared context, so `payload` stays alive.
  // One listener and one body are added per request. Node warns after 10 listeners.
  configEvents.on('change', () => log(req.id));
  res.end('ok');
}

// FIXED, part 1: the factory's context holds only one string.
function makeConfigListener(id) {
  return () => log(id);
}

function handleFixed(req, res, body) {
  const payload = JSON.parse(body);
  validate(() => Array.isArray(payload.items));
  const onChange = makeConfigListener(req.id);
  configEvents.on('change', onChange);
  // FIXED, part 2: unregister when the response closes, so nothing outlives the request.
  res.on('close', () => configEvents.off('change', onChange));
  res.end('ok');
}

http.createServer((req, res) => {
  req.id = randomUUID();
  let body = '';
  req.on('data', (chunk) => { body += chunk; });
  req.on('end', () => handleFixed(req, res, body)); // swap in handleLeaky to reproduce
}).listen(3000);

In the leaky handler, the config listener reads only req.id but shares a V8 context with the validation callback, so it keeps every parsed body alive. The fixed handler builds the listener in a factory that captures only the id and removes it when the response closes.

What other patterns cause most API server leaks?

Closures are only one source of leaks. Most other API server leaks follow the same shape: something with a short lifetime is referenced from something that lives as long as the process.

Unbounded module-level maps. A Map declared at module scope and keyed by request ID, user ID or URL grows with every new key. Nothing deletes old entries. Choose the fix based on the key's lifetime:

  • If the key is an object that something else owns, such as a req, a socket or a session object, use a WeakMap. Its entries become collectable once the key object is collectable.
  • If the key is a string or number, a WeakMap cannot hold it. Use a bounded LRU with a maximum size and, if useful, a TTL.

Per-request listeners on long-lived emitters. Calling client.on('error', …) inside a handler adds one listener per request to a database client, Redis connection or keep-alive socket. MaxListenersExceededWarning is the early signal. Raising the limit hides the leak and does not fix it. Instead, register the listener once at startup. If it must be per request, remove it on both close and error.

Timers and unsettled promises. An interval handle that is never passed to clearInterval keeps its callback alive indefinitely. A promise that never resolves or rejects does the same for its then callbacks and everything they capture. A common cause is waiting on an event that never fires. Wrap such waits in a timeout that settles the promise and removes the listener.

Request state in globals. A global "current request" map defeats the purpose of AsyncLocalStorage. Put per-request data in the store itself, and do not copy it into module-level structures.

Pattern Early signal Fix
Unbounded cache Map.size keeps rising LRU (primitive keys) or WeakMap (object keys)
Per-request listeners MaxListenersExceededWarning Register once, or remove on close/error
Uncleared interval Timer count grows clearInterval on teardown
Unsettled promise Pending work keeps growing Timeout that settles and cleans up
Global request state Map keyed by request ID Keep the data in the AsyncLocalStorage store
const { once } = require('node:events');

// BEFORE: each request adds an 'error' listener to a shared, long-lived client.
// The closure captures res and is never removed, so listeners pile up until
// MaxListenersExceededWarning appears.
app.get('/orders/:id', async (req, res) => {
  db.on('error', (err) => res.status(502).end(err.message));
  res.json(await db.query('SELECT * FROM orders WHERE id = $1', [req.params.id]));
});

// AFTER: register process-wide handlers once, at startup.
db.on('error', (err) => console.error('db client error', err));

// If a listener must be per request, remove it on every exit path.
app.get('/orders/:id/stream', (req, res) => {
  const onError = (err) => {
    if (!res.headersSent) res.status(502).end();
  };
  const cleanup = () => db.off('error', onError);
  db.on('error', onError);
  // 'close' fires after a normal finish and when the client aborts.
  res.once('close', cleanup);
  // ... stream rows into res ...
});

// BEFORE: if 'ready' never fires, this promise never settles. Its continuation
// and everything it captures (req, res) stay reachable indefinitely.
//   await once(queue, 'ready');

// AFTER: the abort signal rejects the promise and removes the listener.
app.post('/jobs', async (req, res) => {
  try {
    await once(queue, 'ready', { signal: AbortSignal.timeout(5000) });
    res.status(202).json(await queue.add(req.body));
  } catch (err) {
    // AbortError on timeout. Fail fast instead of holding the request.
    res.status(503).end();
  }
});

Before/after fixes for two leak patterns: per-request listeners on a long-lived client, either registered once at startup or removed when the response closes, and a wait on an event that may never fire, bounded by an AbortSignal timeout so the promise always settles and its listener is removed.

How can this approach save engineering time?

Without snapshots, leak hunting usually means inference. Engineers watch a memory graph, guess which recent change caused the growth, deploy a candidate fix, and wait hours or days to see whether the slope changes. Each guess costs a full observation cycle. Meanwhile someone keeps the service alive with restarts. The three-snapshot method shortens this loop in several concrete ways:

  • It replaces waiting with a controlled run. A leak that takes days to exhaust memory under production traffic becomes visible in a staging run of a few thousand identical requests. The signal is a delta per N requests, not an absolute memory level, so you don't have to wait for an OOM.
  • It names the object and the owner. The Comparison view tells you which constructor grows. The Retainers panel tells you which module-level structure, emitter or timer holds it. That removes the bisecting of commits and the reading of unrelated code.
  • It makes verification cheap and repeatable. The same driver script that exposed the leak confirms the fix. You compare the deltas before and after the change, instead of deploying and watching a dashboard.
  • It cuts restart toil. Scheduled or threshold-based restarts stop being a permanent on-call task once the root cause is fixed.
  • It improves over time. Named callbacks, an unminified debug build, an authenticated snapshot trigger and a saved load script make the next investigation start from step one, not from tooling setup.

An illustrative estimate, with every input assumed rather than measured: suppose a guess-and-deploy approach takes an assumed four attempts to find the cause, and each attempt costs an assumed one hour of engineering work plus a 24-hour observation window. That is about four engineer-hours and four calendar days. Suppose instead a three-snapshot investigation costs an assumed half day of engineering time, including writing the load driver, capturing and reading snapshots, and verifying the fix, and needs no multi-day observation window. Under these assumptions, the engineering hours are similar, but calendar time drops from days to hours, and so does the period during which the service depends on restarts. Your own numbers depend on how reproducible the leak is, how long your observation windows are, and whether snapshot tooling is already in place.

The savings shrink when the leak is in native memory, only appears on rare production-only paths, or can't be reproduced under synthetic load. In those cases, budget for the alternatives described in the next section.

How do you verify a fix, and what are the alternatives when snapshots aren't enough?

To verify a fix, rerun the exact load that exposed the leak and take snapshots after warm-up and after several more rounds of the same requests. Writing a heap snapshot triggers a full garbage collection first, so the counts reflect what is actually retained. The constructor that used to grow, such as Closure, Timeout or your own request class, should hold the same count across rounds, and its retainer chain should no longer lead back to the module-level structure you fixed. One flat run can be luck. Repeat it, and use more than one traffic mix.

A clean diff is not proof that no leak exists. Leaks that grow over days, or that only fire on rare error paths or tenant-specific inputs, may never show up in a short local test. Snapshots also show only the V8 heap. Native addon allocations, Buffer backing stores (which appear as external in process.memoryUsage()) and allocator fragmentation can push rss up while heapUsed stays flat. If rss and heapUsed drift apart, switch to native memory profiling.

Each mitigation has a cost:

Approach Benefit Cost
WeakMap / WeakRef Entries die with their keys GC timing is nondeterministic, so tests and cache behavior become harder to reason about
Bounded cache Memory has a known ceiling Lower hit rate and more backend latency. The size is a capacity decision
Restart on memory threshold Keeps the service up Hides the root cause, and restarts become more frequent as traffic grows

Treat restart-on-threshold as a stopgap while you find the leak, not as the fix.

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, 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.