tajawal
Published in

tajawal

Memory Leaks in NodeJS | Quick Overview

Image Credit

Memory Management in NodeJs:

Memory Management in NodeJs is done via V8: ‘which is the engine that makes it possible to run JavaScript on the server outside the browser’.

Image Credit

Most Common Causes:

According to what we explained in Memory management, We can define three of the most common memory leak causes, you need to be careful while using them in your code.

Global Variables

As they have a direct path to the root node, they will stay in memory as long as the application is running so you need to be careful when setting global variables and the amount of data you’ll set to them.

Multiple References

Setting multiple references to the same object may cause a problem also as you may remove one ref and forget the other which will keep your object still exists in the Heap.

Closures

In closures simply you keep references to objects to be used later. this feature has many advantages but if it’s used without caution it may cause big issues as these references will keep objects in heap and these objects might be large ones, not just simple objects.

How To Detect

Image credit
  • Node-Memwatch: Very helpful in the production as it emits specific events once there’s abnormal memory usage or potential leak in your app so you can handle these events or expect that there’s a problem coming😄.
  • Node-Inspector: Very useful especially when used with Chrome DevTools in the development phase as it enables you to perform stress tests on your application and monitor the memory usage performance to check if there’s any potential leak in your code and find where exactly that leak might happen.

Quick Demo on Node-Inspector & Chrome DevTools:

  • Firstly, run your app with options:
    expose-gc to be able to run the garbage collector explicitly
    inspect=9222 to be able to attach the Chrome Debugger to your app on port 9222
    so the command should be:
    node --expose-gc --inspect=9222 app.js
  • now open this URL chrome://inspect from your Chrome to open chrome devices inspector

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store