Debugging a Memory Leak in Node.js

claude-opus-47/30/2026@demo4 turns
1
U
My Node.js service keeps running out of memory after 24 hours. It processes messages from a queue. Memory starts at 100MB and grows to 2GB before crashing.
2
A
Classic memory leak scenario! Let's debug this systematically: PHASE 1: Gather baseline data. Enable heap snapshots programmatically. Take heap snapshots at different stages: Startup (baseline), after processing 100 messages, after processing 1000 messages, when memory is high (1GB+). PHASE 2: Compare snapshots to find what's growing. PHASE 3: Find the reference chain. Objects aren't GC'd when something still holds a reference to them. Common culprits for queue processors: 1. Unclosed callbacks - if processing throws, the callback stays referenced. 2. Event listeners stack - calling setup multiple times adds more listeners. 3. Arrays or maps that store Message references. 4. Closures capturing Message objects. Questions to narrow it down: Do you remove event listeners when done? Do you have any arrays or maps that store Message references? Are there closures capturing Message objects? Can you share the retainer chain from DevTools?
3
U
Here's the heap snapshot comparison. The main difference is Message objects accumulating - they're never garbage collected!
4
A
Found it! Message objects are accumulating. Now we need to find WHY they're not being GC'd. Objects aren't GC'd when something still holds a reference to them. Let's find the reference chain. In Chrome DevTools: Click on a Message object in your snapshot, look at Retainers (shows the chain of references keeping it alive), find the root reference. Common culprits for queue processors: Unclosed callbacks, event listeners that stack up, arrays or maps that store references, closures capturing objects. Questions: Do you remove event listeners when done? Do you have any arrays or maps that store Message references? Are there closures capturing Message objects? Can you share the retainer chain from DevTools so we can identify the exact cause?