CodePark/ questions / Performance & memory leaks
START PRACTICINGPRACTICE
Backend question · Node.js › Performance & memory leaks

Memory usage of a Node service grows steadily until it crashes. How do you find the leak?

First confirm it is a leak, then compare heap snapshots to find what keeps growing.

1. Confirm the leak. Track process.memoryUsage().heapUsed or container metrics over time under steady load.

  • If the heap keeps growing and never drops after garbage collection, you likely have a leak.
  • If RSS (the total memory the process uses) grows but the heap stays flat, look at native memory or buffers.

2. Take heap snapshots. A heap snapshot is a picture of every object in memory. You can take one in three ways:

  • Start Node with --inspect and use the Memory tab in Chrome DevTools.
  • Call v8.writeHeapSnapshot().
  • Start Node with --heapsnapshot-signal=SIGUSR2, then send that signal to take one in production.

3. Compare. Take one snapshot, run the suspect traffic, then take another. The comparison view shows which object types grew. The retainers panel shows the chain of references that keeps them alive, such as a module-level Map or an array of listeners.

Taking a snapshot pauses the process. It also needs free memory of about twice the heap size. So take snapshots on one instance that you have removed from live traffic.

  • Confirm the leak with heap metrics over time, and compare heap growth with RSS growth.
  • Take heap snapshots with --inspect, v8.writeHeapSnapshot() or --heapsnapshot-signal.
  • Compare a snapshot from before the load with one from after it.
  • Follow the retainers to find the root that keeps the objects alive.
  • Snapshots pause the process and need about twice the heap size in free memory.