Does your Node.js API container keep climbing in RAM until Kubernetes kills it with OOMKilled every few hours?
Memory leaks in production rarely crash on localhost, because they hide inside long-lived caches, unclosed event listeners, and retained closures that only grow over thousands of requests.
The good news is that Node.js includes built-in V8 heap diagnostics that pinpoint the exact leaking object in minutes. In this guide, we show you how to capture heap snapshots, compare memory growth, and fix the most common Node.js memory leaks.
Executive Summary
- Confirm a Real Leak First: Watch
process.memoryUsage().heapUsedafter garbage collection; a true leak climbs steadily in a sawtooth pattern that never returns to baseline. - Use Three-Snapshot Comparison: Take three V8 heap snapshots in Chrome DevTools under load and filter by Objects allocated between Snapshot 1 and Snapshot 2.
- Fix the Big Four Culprits: Unbounded in-memory
Mapcaches, danglingEventEmitterlisteners, unclosed timers, and large closure scopes cause most Node.js leaks. - Set Explicit Heap Limits: Configure
--max-old-space-sizeto match your container’s cgroup memory limit so Node.js logs useful diagnostics before the kernel kills it.
Table of Contents
- Common Node.js Memory Leak Symptoms and Causes
- Method 1: Capture and Compare V8 Heap Snapshots
- Method 2: Fix the Four Most Common Leak Patterns
- Frequently Asked Questions
- You May Also Like
- Primary Sources and References
Common Node.js Memory Leak Symptoms and Causes
Not every RAM spike is a memory leak. V8 delays garbage collection when free memory is plentiful, so healthy services naturally rise and fall.
| Leak Pattern | What Happens in RAM | Typical Root Cause | Quick Fix |
|---|---|---|---|
| Unbounded Cache | heapUsed grows linearly with unique users | Plain {} or Map with no eviction limit | Replace with a bounded LRU cache (max + ttl) |
| Listener Leak | MaxListenersExceededWarning in logs | Adding .on() inside request handlers | Register listeners once or call .off() |
| Retained Closure | Old request payloads stay in Retainers | Background timers holding req or Buffer | Pass only small IDs into closures |
| Native / Buffer Growth | rss rises while heapUsed stays flat | Unclosed streams or native C++ addons | Destroy streams in finally / pipeline() |

Method 1: Capture and Compare V8 Heap Snapshots
You do not need expensive APM agents to find a leak. Use Node.js’s built-in v8 module or --inspect flag to capture snapshots safely.
Step 1: Write a Safe On-Demand Heap Snapshot Trigger
In staging or an isolated canary pod, expose an internal admin hook (never public) or listen for SIGUSR2 using Node’s native v8.writeHeapSnapshot():
import v8 from "node:v8";
process.on("SIGUSR2", () => {
const filePath = v8.writeHeapSnapshot();
console.error(`Heap snapshot written to ${filePath}`);
});Step 2: Use the Three-Snapshot Method Under Load
Send synthetic traffic to your service and take three snapshots with kill -USR2 <pid>:
- Snapshot 1: Right after warm-up (baseline).
- Snapshot 2: After 1,000 requests.
- Snapshot 3: After another 1,000 requests.
Open Chrome DevTools > Memory > Load, load all three .heapsnapshot files, select Snapshot 3, and switch the view dropdown from Summary to Objects allocated between Snapshot 1 and Snapshot 2. Objects that survived two full load cycles are your leak.
Pro Tip: Always inspect the Retainers pane at the bottom of Chrome DevTools for the largest surviving array or closure. It shows the exact variable name and file holding the reference alive.
Method 2: Fix the Four Most Common Leak Patterns
Once you spot the retaining path, one of these fixes almost always clears the leak.
Step 1: Cap In-Memory Caches with an LRU Limit
Never store per-user sessions or API responses in an unbounded new Map() or module-level array. Use an LRU cache with a strict max item count and TTL so old entries are evicted automatically.
Step 2: Clean Up Event Listeners and Streams
When attaching listeners inside a per-request function or WebSocket handler, always remove them when the request ends or use .once(). For file and HTTP streams, use stream/promises pipeline() so Node.js destroys streams automatically on errors or client disconnects.
import { pipeline } from "node:stream/promises";
import fs from "node:fs";
export async function streamReport(res, filePath) {
await pipeline(fs.createReadStream(filePath), res);
}Step 3: Align --max-old-space-size with Container Limits
By default, older Node.js versions or mismatched cgroup limits can let V8 grow past your Docker or Kubernetes memory limit. Set NODE_OPTIONS="--max-old-space-size=1536" on a 2 GB container so V8 runs aggressive garbage collection before the OS triggers OOMKilled.
Note: Writing a heap snapshot pauses the Node.js event loop for a few seconds and uses extra RAM. Always pull the affected pod out of the load balancer before capturing a snapshot in production.
Frequently Asked Questions
Why does rss memory keep rising even when heapUsed is stable?
heapUsed measures only JavaScript objects managed by V8. Rising rss with flat heapUsed usually points to Node Buffer allocations, unclosed file descriptors, or native C++ addons.
Can console.log() cause a memory leak in Node.js?
Logging massive objects at high request rates can back up stdout buffers if the log consumer is slow, holding references to those objects in memory longer than expected.
Does restarting Node.js pods on a schedule fix a memory leak?
Scheduled restarts only hide the symptom. They drop in-flight requests and mask bugs that will eventually trigger OOMKilled during a sudden traffic surge.
Are WeakMap and WeakSet safe from memory leaks?
Yes, for object keys. Because WeakMap holds weak references to its keys, the garbage collector can reclaim an entry automatically as soon as no other code references that key object.
You May Also Like
We hope this guide helped you diagnose and fix memory leaks in your Node.js microservices. Written by the TeckScaler Editorial Engineering Team. Continue tuning your backend performance:
- Low-Latency Web Apps with Next.js, Node.js, and PostgreSQL.
- Tune PostgreSQL Connection Pooling for Serverless APIs.
- What Is Database Connection Pooling: PgBouncer Explained.
Primary Sources and References
- Node.js Diagnostics: Memory Management and Heap Snapshots (Official Node.js Documentation)
- Node.js
v8.writeHeapSnapshot()API Reference (Official Node.js Documentation) - Node.js Stream
pipeline()Documentation (Official Node.js Documentation)



