Monitoring the performance and resource usage of a Node.js application in production is vital to ensure a seamless user experience and resolve any performance bottlenecks. To achieve this, you can use various monitoring tools and libraries available for Node.js.
Here are some popular methods:
1. Performance Hooks
Node.js has built-in performance hooks that provide a way to measure the performance of specific operations using High-resolution timers. You can use these hooks to monitor the time taken by various tasks within your application.
Example:
const { performance, PerformanceObserver } = require('perf_hooks');
function someFunction() {
// Your function logic
}
const wrappedFunction = performance.timerify(someFunction);
const obs = new PerformanceObserver((list) => {
console.log(list.getEntries()[0].duration);
obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });
wrappedFunction();
2. System Metrics
Recording system metrics like CPU usage, memory usage, and event loop lag will offer insights into the resource usage of your application.
Example:
const os = require('os');
const pidusage = require('pidusage');
setInterval(async () => {
const { cpu, memory } = await pidusage(process.pid);
const freeMemory = os.freemem();
const totalMemory = os.totalmem();
console.log(`CPU: ${cpu.toFixed(2)}%`);
console.log(`Memory: ${(memory / (1024 * 1024)).toFixed(2)} MB`);
console.log(`Free Memory: ${(freeMemory / (1024 * 1024)).toFixed(2)} MB`);
console.log(`Total Memory: ${(totalMemory / (1024 * 1024)).toFixed(2)} MB`);
}, 1000);
In the example above, we use the built-in ’os’ module and ’pidusage’ library to monitor CPU and memory usage.
3. Application Performance Monitoring (APM) Tools
Several APM tools like Elastic APM, New Relic, and AppDynamics offer comprehensive monitoring solutions for Node.js applications. These tools provide real-time performance data and alerts, and easily integrate into your application with minimal changes in the code.
Example of using Elastic APM:
Install Elastic APM Node.js agent:
npm install elastic-apm-node --save
Add this code at the beginning of your application:
const apm = require('elastic-apm-node').start({
serviceName: 'your-service-name',
secretToken: 'your-secret-token',
serverUrl: 'your-apm-server-url'
});
// Your application code
4. Custom Performance Metrics
Depending on your application, you might want to expose custom performance metrics through an API or store them in a database for further analysis.
Example of exposing custom metrics with Prometheus:
Install Prometheus client for Node.js:
npm install prom-client --save
Add an endpoint in your application for exposing metrics:
const client = require('prom-client');
const app = require('express')();
const httpRequestCounter = new client.Counter({
name: 'http_requests_total',
help: 'Total number of HTTP requests',
});
app.get('/metrics', (_, res) => {
res.set('Content-Type', client.register.contentType);
res.end(client.register.metrics());
});
app.use((_, __, next) => {
httpRequestCounter.inc();
next();
});
// Your routes
app.listen(3000);
Monitoring the performance and resource usage of a Node.js application in production is crucial to maintain a healthy application. By using performance hooks, system metrics, APM tools, and custom performance metrics, you can quickly identify and solve performance bottlenecks and provide a smooth user experience.