Sobes.tech
Middle+

How do you handle memory leaks when they occur?

sobes.tech AI

Answer from AI

To detect and fix memory leaks, I use the following methods:

  1. Monitoring: Regularly track memory consumption using built-in Node.js tools such as --expose-gc, process.memoryUsage(), or external tools like PM2 or Prometheus/Grafana.
  2. Profiling tools:
    • Heap Snapshots: Take "heap snapshots" at different times using Chrome DevTools (or any other debugger supporting the V8 protocol) and compare them to identify objects that grow over time and should not.
    // Example of using heapdump to create a heap snapshot
    const heapdump = require('heapdump');
    
    // ... your code ...
    
    // Creating a heap snapshot
    heapdump.writeSnapshot((err, filename) => {
        if (err) console.error(err);
        else console.log('Heap snapshot saved to:', filename);
    });
    
    • CPU Profiling: Sometimes leaks are not directly related to memory but to infinite loops or excessive CPU usage, which can indirectly lead to memory issues.
  3. Code analysis: Manually review code for common causes of leaks:
    • Unremoved event handlers.
    // Example of a leak: unremoved event handler
    const EventEmitter = require('events');
    const emitter = new EventEmitter();
    
    function handler() { /* ... */ }
    
    emitter.on('myEvent', handler);
    
    // If the emitter continues to exist and the reference to the handler is lost
    // or the object it is attached to should be destroyed,
    // the handler will keep it in memory.
    
    // Correct:
    // emitter.off('myEvent', handler);
    
    • Uncleared timers (setInterval, setTimeout).
    • Closures that accidentally hold references to large objects.
    • Global variables that are not cleared.
    • Caches that grow infinitely without eviction mechanisms.
    • Forgotten promises or callbacks that hold context in memory.
  4. Automated testing: Write tests that simulate long-term application operation and check memory consumption stability.
  5. Code reviews: Involve colleagues in analyzing code for potential leaks.
How do you handle memory leaks when they occur… - sobes.tech