Node.js Garbage Collection: How It Works with Examples

Introduction

Node.js is widely used to build web applications, REST APIs, and backend services. While an application runs, it creates objects, arrays, strings, and other values that occupy memory. If memory is not managed properly, the application may consume excessive resources, become slow, or eventually crash.

Node.js uses the V8 JavaScript engine, which automatically manages JavaScript memory through a process called garbage collection. Garbage collection identifies objects that are no longer reachable by the application and reclaims the memory they occupy.

Although garbage collection works automatically, developers still need to write memory-efficient code. Unnecessary references, global variables, and continuously growing caches can prevent objects from being collected.

In this tutorial, you will learn what garbage collection is in Node.js, how it works, how to inspect memory usage, practical examples, common mistakes, and frequently asked interview questions.

What Is Garbage Collection in Node.js?

Garbage collection in Node.js is an automatic memory management process that reclaims memory used by JavaScript objects that are no longer reachable.

When an application creates an object, the JavaScript engine allocates memory for it. As the application runs, some objects become unnecessary. Garbage collection allows the runtime to identify such objects and make their memory available for reuse.

For example:


let user = {
    name: 'Rahul',
    age: 30
};
user = null;

Initially, the user variable references an object. When the variable is assigned null, that reference is removed. If no other references to the object exist, it becomes eligible for garbage collection.

However, garbage collection does not necessarily happen immediately. V8 decides when to perform collection based on its internal memory management strategies.

Garbage collection helps developers avoid manually freeing most JavaScript objects, but it cannot automatically identify whether reachable data is logically unnecessary.

How Does Garbage Collection Work in Node.js?

Node.js uses V8’s garbage collector to manage JavaScript heap memory. One important principle is reachability: objects that can no longer be reached through active references are generally eligible for collection.

V8 uses generational memory management, among other techniques, to improve garbage collection efficiency.

1. Young Generation

The young generation stores many newly created JavaScript objects. A large number of these objects are short-lived and become unnecessary soon after creation.

V8 can collect short-lived objects efficiently using relatively frequent collections of young-generation memory.

2. Old Generation

Objects that survive multiple garbage collection cycles may be moved into the old generation. This area holds longer-lived objects, such as application data that remains in use.

Collecting this memory may require more work than collecting short-lived objects, depending on the amount and structure of live data.

3. Marking and Sweeping

Garbage collectors commonly use techniques that identify reachable objects and reclaim memory associated with unreachable objects.

  • Marking: The collector identifies objects that remain reachable from roots, such as active execution contexts and global references.
  • Sweeping: Memory occupied by unreachable objects can be reclaimed.
  • Compaction: In some situations, the collector moves live objects to reduce memory fragmentation.

Modern V8 garbage collection uses multiple strategies, including concurrent and incremental work, to reduce pauses. The exact process depends on the V8 version and memory conditions.

Syntax: Checking Garbage Collection and Memory Usage

Node.js provides the process.memoryUsage() method to inspect memory consumption.


const memory = process.memoryUsage();

console.log('Heap Used:', memory.heapUsed);
console.log('Heap Total:', memory.heapTotal);
console.log('RSS:', memory.rss);

The main properties are:

  • heapUsed: JavaScript heap memory currently in use.
  • heapTotal: Memory allocated to the V8 JavaScript heap.
  • rss: Total resident memory used by the process, including JavaScript and native allocations.

These values are measured in bytes.

To display heap usage in megabytes:


const memory = process.memoryUsage();

console.log(
    'Heap Used:',
    (memory.heapUsed / 1024 / 1024).toFixed(2),
    'MB'
);

This method helps you monitor memory usage, but it does not directly tell you which objects are preventing garbage collection.

Example: Understanding Garbage Collection in Node.js

Consider an example where an object is created and then becomes unreachable.


function createUser() {
    let user = {
        name: 'Rahul',
        age: 30
    };
    console.log(user);
    user = null;
}
createUser();

Output:


{ name: 'Rahul', age: 30 }

Explanation:

  1. The createUser() function creates a user object.
  2. The user variable references that object.
  3. The object is printed to the console.
  4. Assigning null removes the reference held by user.
  5. When the function finishes, if no other references exist, the object is eligible for garbage collection.

The object may not be collected immediately. JavaScript developers generally should not depend on a specific garbage collection time.

Real-Life Example of Node.js Garbage Collection

Consider an e-commerce application that processes thousands of customer requests. Each request creates temporary objects containing product information, customer details, and calculation results.

After a request finishes, temporary data may no longer be needed. If the application does not retain references to that data, the garbage collector can reclaim the associated memory.

However, suppose the application stores every request in a global array:


const requestHistory = [];

function handleRequest(request) {
    requestHistory.push(request);

    // Process the request
    console.log('Request processed');
}

The array keeps references to every stored request. Even when the requests are no longer useful, their objects remain reachable and cannot be collected.

If the application does not need to retain complete request objects, it can store only essential information or avoid storing the requests entirely.


function handleRequest(request) {
    const requestId = request.id;

    // Process the request
    console.log('Request processed:', requestId);
}

In production applications, logging systems or databases can store information that must be retained. Memory should be reserved for data that needs to remain available during application execution.

This approach reduces unnecessary memory retention and helps prevent memory leaks.

Common Mistakes When Using Garbage Collection

1. Assuming garbage collection is immediate

An object becomes eligible for collection when it is no longer reachable, but the runtime decides when to reclaim its memory. Do not write application logic that depends on immediate collection.

2. Keeping unnecessary references

Global variables, caches, arrays, and maps can retain objects for too long. Remove entries when they are no longer required and set appropriate limits for caches.

3. Ignoring event listener cleanup

Listeners can retain references to objects and other resources. Remove listeners when their lifecycle ends and cleanup is necessary.

4. Assuming null frees memory directly

Assigning null removes a particular reference; it does not directly free the object’s memory. Other references may still exist, and collection may happen later.

5. Relying only on heap usage

An application can consume significant memory outside the JavaScript heap, including memory used by buffers and native components. Monitor RSS and external memory as well.

Conclusion

Node.js garbage collection automatically manages JavaScript memory by reclaiming objects that are no longer reachable. V8 uses techniques such as generational collection and marking to manage memory efficiently.

Developers can monitor memory consumption using process.memoryUsage() and investigate memory leaks using profiling tools and heap snapshots.

By removing unnecessary references, managing caches, cleaning up event listeners, and avoiding excessive data retention, you can reduce memory problems and build more reliable Node.js applications.

Node.js Garbage Collection – Interview Questions

Q 1: What is garbage collection in Node.js?
Ans: Garbage collection is the automatic process of reclaiming memory associated with JavaScript objects that are no longer reachable.
Q 2: Which engine manages JavaScript garbage collection in Node.js?
Ans: The V8 JavaScript engine manages JavaScript memory and garbage collection in Node.js.
Q 3: What is the difference between the young and old generations?
Ans: The young generation generally contains recently created objects, while the old generation contains objects that survive collections and remain in use longer.
Q 4: Can developers manually trigger garbage collection in Node.js?
Ans: Yes, for diagnostic or testing purposes, Node.js can expose garbage collection through the --expose-gc option. The global.gc() function is available when that option is enabled. It should not normally be used as a routine production memory management strategy.
Q 5: What is a memory leak in Node.js?
Ans: A memory leak occurs when an application retains references to objects that are no longer needed, preventing garbage collection from reclaiming their memory.

Related Node.js Tutorials