Node.js Memory Leak Playbook: Catch the Leak Before It Crashes Your Service at 3 A.M.

Your service dies at night. Not every night — twice last week, then nothing for four days. The pager fires at 03:14, the container has been OOMKilled, RSS sat at 1.8 GB against a 2 GB limit, and by morning the only evidence left is a restart count and a graph that goes up and then falls off a cliff. If you have ever opened that graph and thought "great, but where is the leak", this playbook is for you: a decision rule for choosing between passive monitoring and active profiling, and a ready brief you can hand to your AI assistant to do the actual work.

The uncomfortable part is that the two situations people lump together under "memory leak" need opposite responses. A leak that reproduces in ten minutes under load is a profiling job — heap snapshots, a diff, a retaining path, a fix by lunchtime. A leak that shows up once a day in production and never on staging is a monitoring job first, and profiling a service you cannot reproduce is how teams burn two weeks and ship nothing.

The signs that tell you this is your problem

Before choosing an approach, confirm you actually have a leak and not a capacity problem. The symptoms that point at a leak specifically:

  • RSS climbs monotonically across hours and does not come back down after traffic drops. Sawtooth patterns that return to a stable floor are normal GC behaviour, not a leak.
  • heapUsed after a forced GC keeps rising across identical load cycles. This is the single most reliable signal — the floor of the heap, not the peaks, is what grows.
  • Restarts correlate with traffic, not with time. A leak driven by requests grows with request count; a leak driven by timers or connections grows with uptime regardless of traffic.
  • The crash is an OOM kill, not an exception. The process never logs an error because the kernel kills it. If you see JavaScript heap out of memory in logs instead, you have a different problem — a single allocation spike, not a slow leak.

A quick sanity check that costs nothing: plot process.memoryUsage().heapUsed sampled after global.gc() (run the process with --expose-gc on staging) against request count. If the two lines rise together, you have a leak with a request-shaped trigger. If heap grows while requests are flat, look at timers, caches, event listeners, and connection pools first.

Why it happens, and what it costs you

The mechanism is almost always the same: something holds a reference to an object that your code believes is gone. Node's GC is a mark-and-sweep collector — it frees what is unreachable from the roots (the stack, globals, closures still alive, active handles). A leak is not "memory that was not freed"; it is a reference you did not know you kept. More on the topic: “Node.js Backend Development: Who the Course Fits, Where the Real Work Begins, and What the Syllabus Won't Tell You”.

The usual suspects, in rough order of how often they show up in real services:

  1. Unbounded caches and maps. A Map keyed by user ID or request ID that never evicts. One entry per user is fine at 10,000 users and fatal at 2 million.
  2. Listeners added per request. emitter.on(...) inside a handler without a matching removeListener, or listeners on a long-lived singleton that accumulate one per request.
  3. Closures captured by timers. setInterval that closes over a request object and is never cleared — the interval keeps the whole request graph alive.
  4. Growing buffers and arrays. Log buffers, retry queues, or metrics arrays that are pushed to but never trimmed.
  5. Native or external memory. Buffers, sockets, and addon allocations that live outside the V8 heap — heapUsed looks flat while RSS climbs.

That last one matters for diagnosis: if RSS grows but heapUsed does not, heap snapshots will show you nothing. You are looking at external memory, and you need to instrument Buffer allocations or check your connection handling instead.

The cost is not the RAM. It is the pager. A service that OOMKills at night costs you the night, then costs you the morning reconstructing what happened from graphs, then costs you a day of guessing. Multiply by however many weeks it takes to find it by reading code.

The decision rule: reproduce in N minutes, or monitor until you can

This is the fork in the road, and it is testable. Write down one number before you start: how many minutes of synthetic load does it take to reproduce the growth on staging?

  • Reproducible within your window (say, 15–30 minutes of load): go straight to active profiling. Heap snapshots under load, diff, retaining path, fix, regression test. This is the fast path and it should take a day, not a week.
  • Not reproducible, or only in production roughly once a day: do not start with snapshots. Build cheap continuous monitoring first — thresholds on RSS and post-GC heapUsed, an alert, and automatic snapshot capture when the threshold trips. Then localise from the captured dump. Profiling a service you cannot reproduce is guessing with extra steps.
Reproduce in minutes or monitor until you can
1
Confirm it is a leak
Post-GC heapUsed rises across identical load cycles
2
Reproduces on staging in under 30 min?
Synthetic load, fixed request count
3
Yes: active profiling
Heap snapshots, diff, retaining path, fix
4
No: continuous monitoring
RSS thresholds, alert, one triggered snapshot
5
Localise from the captured dump
Then fix and add a regression test

Why not just profile always? Because a heap snapshot of a 1.5 GB process is a multi-second stop-the-world pause, and taking it on a hunch in production means your users feel it. On staging, with a reproduction, it is free. The rule is really about where you can afford to stop the world.

Situation First move Tool Time to answer
Reproduces on staging in under 30 min of load Active profiling --inspect, heap snapshots, clinic.js Hours
Floating, production-only, ~daily Continuous monitoring + trigger RSS/heapUsed thresholds, auto-snapshot Days, but no user impact
RSS grows, heapUsed flat External memory investigation Buffer/connection instrumentation Variable
Sawtooth that returns to a stable floor Not a leak Resize the container, tune GC Minutes

Brief for your AI

Hand this block to your AI assistant as-is. It assumes the assistant is working in your repository and does not know your service.

A. Role and context

You are a backend developer working inside an existing Node.js repository that you did not write. The service is a long-running HTTP server (or worker) that shows slow memory growth. The stack is Node.js with whatever framework and libraries are already in package.json — read it, do not assume. What is known: the service's RSS grows over time and the process is eventually OOMKilled. What is NOT known: whether the growth is in the V8 heap or in external memory, which code path causes it, and whether it reproduces on staging. Do not assume any of this — establish it. More on the topic: “Your Backend Is a Slow Leak: LLM Prompts That Catch Memory Hogs, Query Bloat, and Crash Triggers Before the Pager Goes Off”.

B. Goal and Definition of Done

The goal is a located root cause, a minimal fix, and a regression test that fails before the fix and passes after. Done means all of the following are true:

  • A written statement of the cause: which object is retained, by which reference, from which code path.
  • The fix is merged as a small diff, with a one-line reason per change.
  • A test exists that reproduces the growth and passes only with the fix.
  • A before/after measurement is recorded: heapUsed after forced GC at a fixed number of requests, before and after.

"Improved memory usage" is not done. A number is done.

C. Boundaries

  • Do not change the public API, the database schema, or any user-visible behaviour.
  • Do not add dependencies for the fix itself. Diagnostic tooling may be used locally but must not ship to production.
  • Do not rewrite modules that are not implicated by the evidence.
  • Stop and ask if the reproduction cannot be established within the agreed window — do not start guessing at fixes.

D. Phases — think first, act second

Phase 0 — Understand (no edits). Read the entry point, the HTTP handler registration, and every place that stores state across requests: module-level Map/Set/arrays, caches, event emitter registrations, setInterval/setTimeout calls, and connection pools. List every call site of each. Then write a hypothesis in plain text: "I believe X is retained by Y because Z." Editing in this phase is forbidden.

Phase 1 — Plan and risks. Write the reproduction plan: what synthetic load, how many requests, how long, which metric decides. State what could break (the load test itself, staging data) and how you roll back. State the cheapest experiment that would confirm or kill the hypothesis.

Phase 2 — Prove the hypothesis. Run the load, sample heapUsed after global.gc(), take two heap snapshots at different request counts, diff them, and find the retaining path of the fastest-growing object type. If the hypothesis fails, go back to Phase 0 with the new evidence — do not patch around it.

Phase 3 — Implement. Minimal change, one at a time, each with its stated reason. If the fix is an eviction policy on a cache, say what the bound is and why that number.

Phase 4 — Verify. Re-run the identical load and compare the same metric. Run the full test suite and the linter. Show the commands and their output.

Phase 5 — Report. Done / verified with command X / left open / risks.

E. Forbidden

  • Acting without a stated hypothesis.
  • Inventing API names, flags, or measurements. If a tool is not installed, say so.
  • Adding --expose-gc or diagnostic flags to production configuration.
  • Reporting "should be fixed" without a measurement.
  • Guessing when information is missing — ask and stop.

F. Report format

A short list: what was done; how each claim was verified (the command); what numbers moved; what remains unknown; what a human must check before merge.

The prompts, in order

Send these one after another. Do not skip ahead — each one produces the input for the next.

1. Diagnose. "Read the repository and list every place where state is held across requests: module-level collections, caches, event listeners, timers, pools. For each, give the file, the line, and every call site. Do not change anything. Then state, in one paragraph, your best hypothesis about what retains memory and why."

2. Plan. "Given your hypothesis, write a reproduction plan: the synthetic load (endpoints, concurrency, request count), the metric that decides, and how long it runs. State what could break and how to roll back. Keep it under 200 words."

3. Prove. "Write the load script and the sampling script. The sampling must record heapUsed after a forced GC at fixed request intervals. Run it, take two heap snapshots at different counts, diff them, and report the top three object types by growth with their retaining paths. If the hypothesis is not confirmed, say so and return to diagnosis."

4. Implement. "Apply the minimal fix for the confirmed retaining path. One change at a time, each with a one-line reason. Do not touch anything else. Then add a regression test that fails without the fix."

5. Verify. "Re-run the identical load and report heapUsed after forced GC at the same request counts, before and after. Run the test suite and the linter and paste the output. If the number did not move, say so plainly."

6. Review. "Produce the report in the format from the brief. Flag anything a human must verify, and anything you could not measure."

The mechanics your AI will need (verify against your version)

The brief assumes the assistant can run these. Everything below is standard Node.js tooling; check flags against the Node version in your package.json engines field, since diagnostic flags have changed across major versions. More on the topic: “Node.js Backend Development: Where You Win and Where You Pay — An Analysis for Those Choosing Their Path”.

  • Forced GC sampling: run staging with --expose-gc and call global.gc() before reading process.memoryUsage().heapUsed. Without the forced GC you are measuring garbage, not retained memory.
  • Heap snapshots: start with node --inspect (or --inspect-brk to catch the process before it allocates), connect Chrome DevTools or a client, and take snapshots at two points. The diff view is what you read — the absolute snapshot is noise.
  • clinic.js: clinic doctor for the shape of the problem, clinic heapprofiler for allocation sites. Treat these as examples of commands to confirm against the installed version, not as scripts to paste blindly.
  • Triggered snapshots: in production, a threshold check on RSS that calls v8.writeHeapSnapshot() once and then disables itself. This is the auto-capture step from the decision rule — one snapshot on the way up, not a loop.
Snapshot size is not free Writing a heap snapshot of a 1.5 GB process pauses it for seconds and writes a file of similar size to disk. In production, capture once per incident and put the file somewhere with room. A loop of snapshots will fill the disk and take the service down faster than the leak.

Where this advice stops working

The decision rule and the brief are built for a leak that lives in the V8 heap. They break in specific, recognisable ways:

RSS grows, heapUsed is flat. Heap snapshots will show nothing because the memory is external — Buffers, sockets, native addons. Check connection counts and Buffer allocation before you take a single snapshot. The brief's Phase 0 still applies; the Phase 2 tools do not.

The leak is in a dependency. If the retaining path ends inside a library, you cannot fix it in your code. You can bound it (close the connection, clear the listener the library gave you) or upgrade. The regression test is still yours to write — it should fail against the old version.

The service is multi-process. With a cluster or PM2 in fork mode, one worker may leak while others are fine. Sampling the wrong worker gives you a flat line and a false all-clear. Pin the diagnostic to the worker with the highest RSS.

The growth is legitimate. A cache that is supposed to grow until it hits a bound, or a JIT warmup plateau, is not a leak. If the post-GC heap floor is stable across identical cycles, you have a capacity problem — resize the container and stop profiling.

How to verify it got better

Success is one number moving: heapUsed after forced GC at a fixed request count. Pick the count before you start (say, 50,000 requests at concurrency 20), measure it on the current code, and measure it again after the fix. A leak shows as a line that rises with request count; a fix shows as a line that flattens.

What counts as success: the post-GC heap floor is flat across two consecutive load cycles of the same size, and the regression test fails on the old code and passes on the new one. Both conditions, not one.

If the number did not move, do not ship the fix. Three things to check, in order: did the load actually hit the suspected code path (add a counter, confirm it fired); was the measurement taken after GC (without it you are reading noise); is the growth in external memory after all (compare RSS to heapUsed). If the answer to the last one is yes, you were profiling the wrong heap and Phase 0 needs to start over with Buffers and connections in scope.

If the number moved but the production graph still climbs, the leak you fixed was real but not the only one. That is normal in a service that has been running for years. Fix them one at a time, each with its own regression test, and let the overnight graph be the judge.

The one number that decides Post-GC heapUsed at a fixed request count, before and after. If it does not flatten, nothing else you did counts as a fix.

What to do with this tonight

If your service crashed last night, do not open a profiler yet. Answer one question first: can you make it grow on staging in under half an hour of load? If yes, hand the brief to your AI and start at Phase 0 — you will have a retaining path by tomorrow. If no, the first commit is the monitoring: a threshold on RSS, an alert, and a single triggered snapshot on the way up. That commit does not fix the leak, but it turns a 3 a.m. mystery into a file you can open in the morning — and that is the difference between guessing for a month and finding it in a day.

← All posts

Ask AI about this article

Ask a question about this article — ASI Biont will answer based on its text.