express-prometheus-middleware vs prom-client vs prometheus-api-metrics vs prometheus-gc-stats
Node.js Monitoring Packages
express-prometheus-middlewareprom-clientprometheus-api-metricsprometheus-gc-stats

Node.js Monitoring Packages

These packages are designed to facilitate the integration of Prometheus monitoring into Node.js applications. They provide various functionalities to expose metrics, track application performance, and monitor resource usage, helping developers maintain the health and efficiency of their applications. By utilizing these libraries, developers can gain insights into their application's behavior, optimize performance, and ensure reliability in production environments.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
express-prometheus-middleware096-275 years agoMIT
prom-client03,429126 kB1362 years agoApache-2.0
prometheus-api-metrics013196.8 kB44a year agoApache-2.0
prometheus-gc-stats0876.82 kB92 years agoMIT

Feature Comparison: express-prometheus-middleware vs prom-client vs prometheus-api-metrics vs prometheus-gc-stats

Integration

  • express-prometheus-middleware:

    This package integrates directly with Express.js, allowing you to add Prometheus metrics to your application with minimal configuration. It automatically tracks HTTP requests and exposes metrics on a specified endpoint, making it easy to monitor your Express application.

  • prom-client:

    Prom-client is a standalone Prometheus client that can be used with any Node.js application, not just those built with Express. It provides a flexible API for defining and managing custom metrics, making it suitable for a wide range of applications and use cases.

  • prometheus-api-metrics:

    Designed specifically for REST APIs, this package automatically integrates with your API endpoints to collect metrics without requiring extensive setup. It simplifies the process of monitoring API performance by automatically tracking key metrics relevant to API usage.

  • prometheus-gc-stats:

    This package focuses on garbage collection metrics, providing insights into how often GC occurs and how long it takes. It integrates with your Node.js application to expose GC-related metrics, which is essential for performance tuning.

Metrics Coverage

  • express-prometheus-middleware:

    It provides basic metrics such as request count, response time, and error rates for your Express routes. This coverage is sufficient for general monitoring but may require additional metrics for more in-depth analysis.

  • prom-client:

    Prom-client allows you to define a wide range of custom metrics, including counters, gauges, histograms, and summaries. This flexibility enables you to tailor your monitoring to specific application needs and gather detailed insights.

  • prometheus-api-metrics:

    This package automatically collects metrics specifically for API performance, including request counts, latencies, and error rates. It provides a focused set of metrics that are crucial for monitoring RESTful services effectively.

  • prometheus-gc-stats:

    It specializes in GC metrics, providing detailed information about garbage collection events, including pause times and memory usage. This is particularly useful for applications that need to manage memory efficiently.

Ease of Use

  • express-prometheus-middleware:

    This package is user-friendly and requires minimal setup. Simply add it as middleware in your Express app, and it will start collecting metrics immediately, making it ideal for quick integrations.

  • prom-client:

    While it offers extensive capabilities, prom-client may require more initial setup to define custom metrics. However, once configured, it provides powerful monitoring capabilities that can be tailored to your application's needs.

  • prometheus-api-metrics:

    This package is designed for ease of use, automatically collecting relevant metrics with little configuration. It is particularly beneficial for developers who want to quickly implement monitoring without extensive coding.

  • prometheus-gc-stats:

    It is straightforward to integrate and provides immediate insights into garbage collection performance. This simplicity makes it easy to monitor memory usage without complex configurations.

Performance Impact

  • express-prometheus-middleware:

    The performance impact is minimal, as it only tracks essential metrics for HTTP requests. However, excessive logging or high traffic may lead to increased overhead, so it's important to monitor its impact under load.

  • prom-client:

    Prom-client is designed to be efficient, but the performance impact can vary depending on the number and type of metrics defined. Careful consideration of what metrics to track can help minimize overhead.

  • prometheus-api-metrics:

    This package is optimized for monitoring APIs and is designed to have a low performance impact. It efficiently collects metrics without significantly affecting API response times, making it suitable for production environments.

  • prometheus-gc-stats:

    The performance impact is generally low, but monitoring GC events can introduce some overhead. It is essential to balance the need for GC insights with potential performance trade-offs.

Community Support

  • express-prometheus-middleware:

    This package has a growing community, with active contributions and support available through GitHub. However, it may not have as extensive documentation as more established packages.

  • prom-client:

    Prom-client has a large user base and extensive documentation, making it easy to find support and examples. The community actively contributes to its development, ensuring it stays up-to-date with best practices.

  • prometheus-api-metrics:

    While newer compared to others, prometheus-api-metrics is gaining traction and has a supportive community. Documentation is available, but it may not be as comprehensive as more established libraries.

  • prometheus-gc-stats:

    This package has a dedicated user base and is well-documented, providing clear guidelines for integration and usage. Community support is available, making it easier to troubleshoot issues.

How to Choose: express-prometheus-middleware vs prom-client vs prometheus-api-metrics vs prometheus-gc-stats

  • express-prometheus-middleware:

    Choose this package if you are using Express.js and want a straightforward way to expose Prometheus metrics directly from your Express routes. It integrates seamlessly with your existing middleware and provides out-of-the-box metrics for HTTP requests, making it ideal for applications that already utilize Express.

  • prom-client:

    Opt for prom-client if you need a comprehensive and flexible Prometheus client for Node.js. This package allows you to define custom metrics and is suitable for applications that require detailed monitoring beyond HTTP metrics. It is a good choice if you want to implement metrics tracking in a non-Express context or need more control over metric definitions and collection.

  • prometheus-api-metrics:

    Select prometheus-api-metrics if you are looking for a package specifically designed to monitor RESTful APIs. It automatically collects metrics such as request counts, latencies, and error rates, making it ideal for microservices architectures where you need to monitor multiple API endpoints without extensive manual setup.

  • prometheus-gc-stats:

    Use prometheus-gc-stats if you want to monitor the garbage collection (GC) performance of your Node.js application. This package provides insights into GC events, including pause times and memory usage, which is crucial for optimizing performance and understanding memory behavior in long-running applications.

README for express-prometheus-middleware

Express Prometheus Middleware

npm Dependency Status devDependency Status Conventional Commits Gitter chat

This is a middleware for express servers, that expose metrics for prometheus.

The metrics exposed allows to calculate common RED (Request, Error rate, Duration of requests), and USE (Utilisation, Error rate, and Saturation), metrics

Install

yarn add express-prometheus-middleware
# or
npm i --save express-prometheus-middleware

Usage

Options

NameDescriptionDefault
metricsPathUrl route that will expose the metrics for scraping./metrics
metricsAppExpress app that will expose metrics endpoint, if an app is provided, use it, instead of instantiating a new onenull
collectDefaultMetricsWhether or not to collect prom-client default metrics. These metrics are usefull for collecting saturation metrics, for example.true
collectGCMetricsWhether or not to collect garbage collection metrics via module prometheus-gc-stats. Dependency prometheus-gc-stats is marked as optional, hence if this option is set to true but npm/yarn could not install the dependency, no garbage collection metric will be collected.false
requestDurationBucketsBuckets for the request duration metrics (in seconds) histogramUses prom-client utility: Prometheus.exponentialBuckets(0.05, 1.75, 8)
requestLengthBucketsBuckets for the request length metrics (in bytes) histogramno buckets (The request length metrics are not collected): []
responseLengthBucketsBuckets for the response length metrics (in bytes) histogramno buckets (The response length metrics are not collected) []
extraMasksOptional, list of regexes to be used as argument to url-value-parser, this will cause extra route params, to be replaced with a #val placeholder.no extra masks: []
authenticateOptional authentication callback, the function should receive as argument, the req object and return truthy for sucessfull authentication, or falsy, otherwise. This option supports Promise results.null
prefixOptional prefix for the metrics nameno prefix added
customLabelsOptional Array containing extra labels, used together with transformLabelsno extra labels: []
transformLabelsOptional function(labels, req, res) adds to the labels object dynamic values for each label in customLabelsnull
normalizeStatusOptional parameter to disable normalization of the status code. Example of normalized and non-normalized status code respectively: 4xx and 422.true

Example

const express = require('express');
const promMid = require('express-prometheus-middleware');
const app = express();

const PORT = 9091;
app.use(promMid({
  metricsPath: '/metrics',
  collectDefaultMetrics: true,
  requestDurationBuckets: [0.1, 0.5, 1, 1.5],
  requestLengthBuckets: [512, 1024, 5120, 10240, 51200, 102400],
  responseLengthBuckets: [512, 1024, 5120, 10240, 51200, 102400],
  /**
   * Uncomenting the `authenticate` callback will make the `metricsPath` route
   * require authentication. This authentication callback can make a simple
   * basic auth test, or even query a remote server to validate access.
   * To access /metrics you could do:
   * curl -X GET user:password@localhost:9091/metrics
   */
  // authenticate: req => req.headers.authorization === 'Basic dXNlcjpwYXNzd29yZA==',
  /**
   * Uncommenting the `extraMasks` config will use the list of regexes to
   * reformat URL path names and replace the values found with a placeholder value
  */
  // extraMasks: [/..:..:..:..:..:../],
  /**
   * The prefix option will cause all metrics to have the given prefix.
   * E.g.: `app_prefix_http_requests_total`
   */
  // prefix: 'app_prefix_',
  /**
   * Can add custom labels with customLabels and transformLabels options
   */
  // customLabels: ['contentType'],
  // transformLabels(labels, req) {
  //   // eslint-disable-next-line no-param-reassign
  //   labels.contentType = req.headers['content-type'];
  // },
}));

// curl -X GET localhost:9091/hello?name=Chuck%20Norris
app.get('/hello', (req, res) => {
  console.log('GET /hello');
  const { name = 'Anon' } = req.query;
  res.json({ message: `Hello, ${name}!` });
});

app.listen(PORT, () => {
  console.log(`Example api is listening on http://localhost:${PORT}`);
});

Metrics exposed

  • Default metrics from prom-client
  • http_requests_total: Counter for total requests received, has labels route, method, status
  • http_request_duration_seconds: - Duration of HTTP requests in seconds, has labels route, method, status

The labels route and status are normalized:

  • route: will normalize id like route params
  • status: will normalize to status code family groups, like 2XX or 4XX.

Example prometheus queries

In the examples below, Suppose you tagged your application as "myapp", in the prometheus scrapping config.

Running instances

sum(up{app="myapp"})

Overall error rate

Rate of http status code 5XX responses

sum(rate(http_requests_total{status="5XX", app="myapp"}[5m]))

95% of requests served within seconds

histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{app="myapp"}[5m])) by (le))

95% of request length

histogram_quantile(0.95, sum(rate(http_request_length_bytes_bucket{app="myapp"}[5m])) by (le))

95% of response length

histogram_quantile(0.95, sum(rate(http_response_length_bytes_bucket{app="myapp"}[5m])) by (le))

Average response time in seconds

sum(rate(http_request_duration_seconds_sum{app="myapp"}[5m])) by (instance) / sum(rate(http_request_duration_seconds_count{app="myapp"}[5m])) by (instance)

Overall Request rate

sum(rate(http_requests_total{app="myapp"}[5m])) by (instance)

Request rate by route

In this example we are removing some health/status-check routes, replace them with your needs.

sum(rate(http_requests_total{app="myapp", route!~"/|/healthz"}[5m])) by (instance, route)

CPU usage

rate(process_cpu_system_seconds_total{app="myapp"}[5m])
rate(process_cpu_user_seconds_total{app="myapp"}[5m])

Memory usage

nodejs_heap_size_total_bytes{app="myapp"}
nodejs_heap_size_used_bytes{app="myapp"}