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.
Before getting started, make sure you have the following installed:
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
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;
}
}
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.
Analyze the produced JSON generated by the memory profiler using Chrome’s dev tools.
chrome://inspect
.There are other functionalities in the DevTools that could be used to perform additional analyses.