Improve Your Node.js Monitoring with These 10 Metrics

alertyai

Alerty

Posted on August 8, 2024

Improve Your Node.js Monitoring with These 10 Metrics

As a Node.js developer, keeping your applications running smoothly is crucial. But how do you know what's happening under the hood? That's where metrics come in. In this article, we'll explore some key metrics that will help you monitor and optimize your Node.js applications like a pro.

To learn more, you can check out the full blog post.

1. CPU Usage

šŸ§  Keep your app's brain healthy.

Monitor CPU usage to ensure your application isn't overworking itself.

const os = require('os');

function getCPUUsage() {
  const cpus = os.cpus();
  const totalUsage = cpus.reduce((acc, cpu) => acc + cpu.times.user + cpu.times.system, 0);
  const totalIdle = cpus.reduce((acc, cpu) => acc + cpu.times.idle, 0);
  return totalUsage / (totalUsage + totalIdle) * 100;
}
Enter fullscreen mode Exit fullscreen mode

2. Memory Usage

šŸ’¾ Don't let your app become a memory hog.

Track memory usage to prevent leaks and optimize performance.

const v8 = require('v8');

function getMemoryUsage() {
  const memoryUsage = process.memoryUsage();
  const heapStats = v8.getHeapStatistics();
  return {
    rss: memoryUsage.rss,
    heapTotal: memoryUsage.heapTotal,
    heapUsed: memoryUsage.heapUsed,
    external: memoryUsage.external,
    heapSizeLimit: heapStats.heap_size_limit
  };
}
Enter fullscreen mode Exit fullscreen mode

3. Event Loop Lag

ā±ļø Keep your app responsive.

Monitor event loop lag to ensure smooth execution of asynchronous operations.

const lag = require('event-loop-lag');

const lagMonitor = lag(1000);

function getEventLoopLag() {
  return lagMonitor();
}
Enter fullscreen mode Exit fullscreen mode

4. HTTP Request Rate

šŸŒ Track your app's popularity.

Monitor the rate of incoming HTTP requests to gauge traffic and plan for scaling.

const http = require('http');

let requestCount = 0;

http.createServer((req, res) => {
  requestCount++;
  // Your server logic here
}).listen(3000);

function getRequestRate() {
  const rate = requestCount;
  requestCount = 0;
  return rate;
}

setInterval(() => {
  console.log(`Request rate: ${getRequestRate()} requests/second`);
}, 1000);
Enter fullscreen mode Exit fullscreen mode

5. Database Connection Pool

šŸŠā€ā™‚ļø Keep your database connections in check.

Monitor your connection pool to ensure efficient resource utilization.

const mysql = require('mysql');

const pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

function getConnectionPoolStats() {
  return {
    total: pool._allConnections.length,
    free: pool._freeConnections.length,
    queued: pool._connectionQueue.length
  };
}
Enter fullscreen mode Exit fullscreen mode

6. Garbage Collection Metrics

šŸ—‘ļø Keep your app's memory clean.

Monitor garbage collection to optimize memory management.

javascriptCopyconst v8 = require('v8');

const gcStats = v8.getHeapStatistics();

function getGCMetrics() {
  return {
    totalHeapSize: gcStats.total_heap_size,
    usedHeapSize: gcStats.used_heap_size,
    heapSizeLimit: gcStats.heap_size_limit
  };
}
Enter fullscreen mode Exit fullscreen mode

7. Active Handles and Requests

šŸ”„ Track ongoing operations.

Monitor active handles and requests to ensure proper resource management.

javascriptCopyfunction getActiveHandlesAndRequests() {
  return {
    activeHandles: process._getActiveHandles().length,
    activeRequests: process._getActiveRequests().length
  };
}
Enter fullscreen mode Exit fullscreen mode

8. Error Rate

āŒ Stay on top of issues.

Monitor your application's error rate to quickly identify and resolve problems.

javascriptCopylet errorCount = 0;

process.on('uncaughtException', (error) => {
  errorCount++;
  // Log or handle the error
});

function getErrorRate() {
  const rate = errorCount;
  errorCount = 0;
  return rate;
}

setInterval(() => {
  console.log(`Error rate: ${getErrorRate()} errors/minute`);
}, 60000);
Enter fullscreen mode Exit fullscreen mode

9. Response Time

ā±ļø Keep your users happy.

Monitor response times to ensure a snappy user experience.

javascriptCopyconst responseTime = require('response-time');
const express = require('express');

const app = express();

app.use(responseTime((req, res, time) => {
  console.log(`${req.method} ${req.url} - Response time: ${time}ms`);
}));

// Your routes here
Enter fullscreen mode Exit fullscreen mode

10. Third-party Service Dependencies

šŸ”— Don't let external services slow you down.

Monitor the performance of third-party services your app depends on.

javascriptCopyconst axios = require('axios');

async function checkExternalService(url) {
  const start = Date.now();
  try {
    await axios.get(url);
    const duration = Date.now() - start;
    console.log(`External service ${url} response time: ${duration}ms`);
  } catch (error) {
    console.error(`Error checking external service ${url}: ${error.message}`);
  }
}

// Check external services periodically
setInterval(() => {
  checkExternalService('https://api.example.com');
}, 60000);
Enter fullscreen mode Exit fullscreen mode

Bonus Tip: Use a Monitoring Tool

šŸ› ļø Supercharge your monitoring! Consider using a dedicated monitoring tool to automate metric collection and gain deeper insights.
Popular options include:

  • Prometheus with Grafana
  • New Relic
  • Datadog
  • AppDynamics

These tools can provide out-of-the-box monitoring solutions and beautiful dashboards to visualize your Node.js application's performance.
By incorporating these additional metrics and tips, you'll have an even more comprehensive view of your Node.js application's health and performance. Remember, the key to effective monitoring is not just collecting data, but also understanding and acting on the insights it provides. Happy monitoring!

Conclusion

By monitoring these essential metrics, you'll gain valuable insights into your Node.js application's performance and health. Remember, knowledge is power, and with these metrics at your fingertips, you'll be well-equipped to optimize your app and keep it running smoothly.

If you need help monitoring your app, check out https://alerty.ai to learn more about easy frontend monitoring.

Happy monitoring, and may your Node.js apps always perform at their best! šŸš€

šŸ’– šŸ’Ŗ šŸ™… šŸš©
alertyai
Alerty

Posted on August 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related