liquidx-studio.github.io

LiquidXLogo.png


How to profile the memory usage of a Nest js app

Author: Amjad Hossain and Nobel Khandaker

We can use memory profiling to identify potential memory leaks and other memory-related issues in NestJS apps running on the V8 engine.

Prerequisites

Before getting started, make sure you have the following installed:

Installing the Dependencies

We can use either v8-profiler or v8 modules to profile the memory usage of our Node JS app.

yarn add v8-profiler
yarn add v8

Enabling the Profiler in the app

The following snippet adds an endpoint /profile/memory to our app. When this endpoint is invoked, the profiler will profile the memory usage of the app for 5 seconds and export the results as a JSON object.

import { Controller, Get } from '@nestjs/common';
import * as profiler from 'v8-profiler';
import v8 from 'v8';

@Controller()
export class AppController {
  @Get('/profile/memory/v8-profiler')
  async profileMemory(): Promise<string> {
    profiler.startProfiling('memory');
    await new Promise((resolve) => setTimeout(resolve, 5000));
    const profile = profiler.stopProfiling('memory');
    return new Promise((resolve) => {
      profile.export((error, result) => {
        profile.delete();
        return resolve(JSON.stringify(result));
      });
    });
  }

  @Get('/profile/memory/v8')
  async profileMemory(): Promise<string> {
    const snapshot = await v8.getHeapSnapshot();
    const profile = JSON.stringify(snapshot);
    return profile;
  }
}

Generating the Memory Profile

To generate the memory profile, we will need to access the newly created endpoint in our NestJS application. Here’s an example of how to do this using the axios module:

import axios from 'axios';

(async () => {
  const response = await axios.get('http://localhost:3000/profile/memory');
  console.log(response.data);
})();

In this code, we are sending a GET request to the /profile/memory endpoint of our NestJS application running on localhost:3000. When the response is received, we log the data to the console.

Analyzing the Memory Profile

Analyze the produced JSON generated by the memory profiler using Chrome’s dev tools.

  1. Open the Chrome browser and navigate to chrome://inspect.
  2. Click on the Open dedicated DevTools for Node link.
  3. In the newly opened DevTools window, click on the Profiler tab.
  4. Click on the Load button and select the memory profile JSON file generated by our NestJS application.
  5. Once the profile is loaded, click on the Summary tab to see an overview of the memory usage.
  6. Click on the Comparison tab to compare the memory usage of different snapshots.

There are other functionalities in the DevTools that could be used to perform additional analyses.