Opening: A Memory Graph Shaped Like a Saw
The server's memory graph creeps up all day. 300 MB, 400 MB, 500 MB. Then it drops straight down to 80 MB and starts climbing again.
Each drop is an instance dying from running out of memory and being restarted. The Cloud Run logs say memory limit exceeded. Whoever was paying at that second gets an error.
No exception. No line of code that is obviously wrong. Just something that gets stored and never released. This part is about memory leaks in Node.js: the two most common causes, and how to find them by comparing two heap snapshots.
Warm-Up Quiz: Do You Still Remember?
Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.
Question 1. When does JavaScript release an object from memory?
- A. When the function that created it returns
- B. When nothing can reach it anymore
- C. After 5 minutes of not being used
Show the answer to question 1
B. The garbage collector only removes objects that are unreachable from everywhere. As long as one reference remains, for example from a global Map, the object lives on even if it is never used again.
Question 2. This cache stores event search results per city and page. Any problem?
const cache = new Map();
function cariEvent(kota, halaman) {
const kunci = `${kota}:${halaman}`;
if (cache.has(kunci)) return cache.get(kunci);
const hasil = queryDatabase(kota, halaman);
cache.set(kunci, hasil);
return hasil;
}
- A. No, a cache makes things faster
- B. Yes,
cachegrows without limit
Show the answer to question 2
B. (cariEvent = find events, kota = city, halaman = page, kunci = key.) Nothing is ever removed. Every new city and page combination adds an entry, forever. If kota comes from user input, anyone can create millions of new keys.
Question 3. You see MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 kursi listeners added. What does it mean?
- A. The process is about to stop
- B. A warning: there are more than 10 listeners for one event, and some are probably never removed
Show the answer to question 3
B. It is only a warning, and the process keeps running. The default limit is 10. Sometimes many listeners are legitimate, but often it means a listener is added per request and never removed.
Question 4. What is the most reliable way to find which objects are leaking?
- A. Add
console.logto every function - B. Take two heap snapshots at different times and compare the difference
- C. Raise the memory limit
Show the answer to question 4
B. One snapshot shows what is in memory. Two snapshots show what grew, which is what we are looking for. Raising the memory limit only delays the crash.
What did you score? Let's take them apart.
1. A Leak Means "Still Reachable"
JavaScript has no free(). The garbage collector (GC) works like a cleaner who only throws away things nobody is holding.
The trouble is that "holding" happens by accident all the time:
- an object stored in a global
Mapor array, - a callback (closure) that keeps a reference to a big object,
- a listener attached to a long-lived object,
- a
setIntervaltimer that is never cleared.
In every case, the GC sees the object as still reachable, so it stays. Memory keeps rising until it hits the container limit, and the process is killed.
Remember too: in Part 3 we called an in-memory cache acceptable state, as long as the data may be stale. This part adds a second condition: its size must be bounded.
2. Cause 1: An Unbounded Cache
I ran the cache from question 2 with keys that are almost always new, 20,000 calls per round, and forced a GC before measuring:
for (let putaran = 1; putaran <= 5; putaran++) {
for (let i = 0; i < 20_000; i++) cariEvent(`kota-${Math.random()}`, i % 10); // keys are almost always new
global.gc?.();
console.log(`putaran ${putaran}: ${cache.size} entri, heap ${mb()}`);
}
putaran 1: 20000 entri, heap 17 MB
putaran 2: 40000 entri, heap 30 MB
putaran 3: 60000 entri, heap 43 MB
putaran 4: 80000 entri, heap 57 MB
putaran 5: 100000 entri, heap 70 MB
(putaran = round, entri = entries.) Even after GC, the heap keeps rising and never comes down. That is the signature of a leak: it rises after GC, not just rises.
Click the diagram to see it full size.
The fix: put a limit on it. Here is a small LRU (least recently used) cache that relies on the fact that a Map keeps insertion order:
class LruCache {
constructor(max) { this.max = max; this.items = new Map(); }
get(key) {
if (!this.items.has(key)) return undefined;
const value = this.items.get(key);
this.items.delete(key); // move to the back = most recently used
this.items.set(key, value);
return value;
}
set(key, value) {
this.items.delete(key);
this.items.set(key, value);
if (this.items.size > this.max) {
const oldest = this.items.keys().next().value; // a Map keeps insertion order
this.items.delete(oldest);
}
}
get size() { return this.items.size; }
}
const cache = new LruCache(1_000);
putaran 1: 1000 entri, heap 4 MB
putaran 2: 1000 entri, heap 4 MB
putaran 3: 1000 entri, heap 4 MB
putaran 4: 1000 entri, heap 4 MB
putaran 5: 1000 entri, heap 4 MB
Flat. In a real project, the lru-cache library gives you the same thing plus expiry (TTL) and size limits in bytes. If the data must be the same on every instance, the cache moves to Redis with EX (Part 3).
3. Cause 2: Listeners That Are Never Removed
This pattern shows up a lot in real-time features: every connected client adds a listener to a shared bus.
const { EventEmitter } = require('node:events');
const bus = new EventEmitter(); // for example a shared "seat changed" bus
// Called every time an SSE/WebSocket client connects.
function sambungkanKlien(id) {
bus.on('kursi', (event) => {
// send to client id...
});
// the client disconnects? its listener stays on the bus, forever.
}
for (let i = 1; i <= 12; i++) sambungkanKlien(i);
console.log('listener aktif:', bus.listenerCount('kursi'));
listener aktif: 12
(node:5408) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 kursi listeners added to [EventEmitter]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit
(sambungkanKlien = connect client, kursi = seat, listener aktif = active listeners.) Each listener is a closure holding a reference to the client and everything tied to it. The client left long ago, but the bus still holds on.
The fix: remove the listener when the connection closes.
const bus = new EventEmitter();
bus.setMaxListeners(10_000); // there really are many clients, and listeners are removed properly
function sambungkanKlien(id, koneksi) {
const kirim = (event) => { /* send to client id... */ };
bus.on('kursi', kirim);
koneksi.once('close', () => bus.off('kursi', kirim)); // remove it when the client disconnects
}
listener aktif: 12
setelah semua klien putus: 0
(The last line reads "after every client disconnected: 0".) The order matters: fix the removal first, then raise setMaxListeners. Raising the limit without removing listeners only silences the alarm.
The same goes for a setInterval per connection (clear it when the connection closes) and a Redis Pub/Sub subscription per request.
4. Finding a Leak: Compare Two Heap Snapshots
In a real app, you do not know which Map is growing. The method:
- Run the app and give it some load (a warm-up), so legitimate caches are already filled.
- Take the first snapshot.
- Apply load for a few more minutes, for example with k6 or autocannon.
- Take the second snapshot.
- Compare: open both in Chrome DevTools (the Memory tab), select the second snapshot, switch the view to Comparison, then sort by Size Delta or # Delta.
To take a snapshot from code:
const v8 = require('node:v8');
const a = v8.writeHeapSnapshot(); // snapshot 1: after the warm-up
// ...a few minutes of load...
const b = v8.writeHeapSnapshot(); // snapshot 2
Or without changing code: start with node --heapsnapshot-signal=SIGUSR2 server.js, then send kill -USR2 <pid> at two different times.
In my example, the cache got 10,000 entries before the first snapshot and 50,000 more before the second. The files were 16 MB and 74 MB. The difference per constructor, which I computed from both files with a small script (the columns match DevTools' Comparison view):
Constructor # Delta Size Delta
Object +50000 +1.5 MB
Float64Array +0 +0.0 MB
global +0 +0.0 MB
Uint8Array +0 +0.0 MB
Exactly +50,000 Objects, the same as the number of entries added. In DevTools, click that row and look at the Retainers panel: it shows who is holding those objects, down to the variable name (for example cache in find-events.js). That is where the leak lives.
Two practical notes:
- Taking a snapshot pauses the process briefly, and the Node.js docs say it needs about twice the current heap size in memory. Do it on staging, or on one instance taken out of traffic.
- Compare after load of the same kind. You are looking for something that keeps growing, not something that is simply big.
5. Before There Is a Leak: Monitor
- A memory graph per instance in Cloud Run or your container dashboard. A saw shape that climbs and drops is the clearest sign.
process.memoryUsage()on an internal endpoint or in periodic logs:heapUsedthat keeps rising under steady load is suspicious.- A deliberate limit: set
node --max-old-space-size=…below the container's memory limit, so Node.js gets to collect garbage more aggressively before the container is killed from outside.
Summary
- Objects are freed when unreachable. A leak = something still holds them.
- Cause 1: an unbounded cache. In the test: 17 → 70 MB after GC. With an LRU of 1,000 entries: flat at 4 MB.
- Cause 2: listeners that are never removed.
MaxListenersExceededWarningis the alarm. Remove onclose, then raise the limit. - Find it with two heap snapshots and the Comparison view. The Retainers panel shows who is holding on.
- Monitor the memory graph, and look for "rises after GC".
Closing & What's Next
The saw-shaped graph from the opening usually ends at a single line: an unbounded Map, or one bus.on without a bus.off.
There is another way to run out of memory, and it needs no bug at all: loading a million rows at once to export them to CSV. In the next part we look at streams and backpressure, the way to move large data without holding all of it in memory.
Grab your coffee, see you in the next part!

Written by Muhammad Fari Madyan
Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

