Node.js Memory Management

Node.js memory management provides means to dynamically allocate memory chunks for programs when they request them and free it when they are no longer needed, so they can be reused. Application-level memory management can be manual or automatic.


The memory space managed by Node is called Heap. Heap is divided into several different spaces called Generations.

New Space

New Space is where objects are first created. It is designed to be small and fast to garbage collect.

Memory in a new space is managed by a pointer. When a new space is created the pointer moves to the next free spot.

New space

When the pointer reaches the end of the space, it goes into a Scavenge operation to identify all of the objects in memory that no longer referenced.

Then it removes these, unpacks the memory and re-allocate the pointer to the next available free spot.

Next free spot

Old Space

Objects that survive ~two garbage collection operations~ are promoted into the old space.

Old space is much larger than the new space, so it implements a different garbage collection algorithm - Mark-sweep

The GC marks the objects being referenced. Anything not marked is unreachable, and the sweep process will remove them.

Mark sweep

The GC stops the process, hence not performant.

Load Test

To perform a load test, let's create a Node.js server.

var http = require('http'); 
var heapdump = require('heapdump'); 

function Bigata()
    var mem = Array(1000000).join('a'); 

var leak = []; 

var server = http.createServer(function(request, response) {
    if(request.uri = '/') { 
        // leak.push(new Biglata);
        response.writeHead(200, { "Content—Type": "text/html" }); 
        response.end('Hello World!');


We can then profile the resulting web page in Chrome DevTools.

Load test console


To trace the server, run the following command:

node --trace_gc server.js