Memory Leak Hunting in Node.js¶
Is Node.js eating memory? A systematic guide to finding and fixing memory leaks.
Detection¶
setInterval(() => console.log(Heap: ${Math.round(process.memoryUsage().heapUsed/1024/1024)} MB), 10000);
Chrome DevTools¶
node –inspect app.js
chrome://inspect -> Memory -> Heap snapshot¶
Causes¶
Event Listeners¶
// emitter.on(‘data’, handler) in a loop // emitter.once() or removeListener
Closures¶
A closure holds a reference to a large object that the GC would otherwise collect.
Global Cache¶
// const cache = {}; cache[key] = data; // grows without limit // LRUCache with max size
Unclosed Streams¶
Always close DB connections, file streams and HTTP connections.
LRU Cache¶
import { LRUCache } from ‘lru-cache’; const cache = new LRUCache({ max: 500 });
Procedure¶
Heap snapshot -> compare 3 snapshots -> find growing objects -> fix.