https://github.com/skellla/fastify-metrics
Prometheus metrics exporter for Fastify
https://github.com/skellla/fastify-metrics
fastify fastify-plugin metrics prometheus
Last synced: 1 day ago
JSON representation
Prometheus metrics exporter for Fastify
- Host: GitHub
- URL: https://github.com/skellla/fastify-metrics
- Owner: SkeLLLa
- License: mit
- Created: 2018-09-27T05:55:28.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2024-09-20T15:55:55.000Z (over 1 year ago)
- Last Synced: 2025-04-02T04:02:55.201Z (about 1 year ago)
- Topics: fastify, fastify-plugin, metrics, prometheus
- Language: TypeScript
- Homepage: https://savelife.in.ua/en/donate-en/
- Size: 1.66 MB
- Stars: 105
- Watchers: 3
- Forks: 33
- Open Issues: 13
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Codeowners: .github/CODEOWNERS
Awesome Lists containing this project
README
# fastify-metrics
[](https://www.npmjs.com/package/fastify-metrics)
[](https://www.npmjs.com/package/fastify-metrics)
[](https://github.com/SkeLLLa/fastify-metrics/actions)
[](https://gitlab.com/m03geek/fastify-metrics/blob/master/LICENSE)
[](https://codecov.io/gh/SkeLLLa/fastify-metrics)
[](https://socket.dev/npm/package/fastify-metrics)
[Prometheus](https://prometheus.io/) metrics exporter for Fastify.
This plugin uses [prom-client](https://github.com/siimon/prom-client) under the hood with optional support for [@platformatic/prom-client](https://github.com/platformatic/prom-client) as a high-performance drop-in replacement.
This plugin also adds two http metrics for your routes:
- Requests duration histogram
- Requests duration summary
## ToC
- [fastify-metrics](#fastify-metrics)
- [ToC](#toc)
- [Fastify support](#fastify-support)
- [Notable changes](#notable-changes)
- [v12.x.x](#v12xx)
- [v11.x.x](#v11xx)
- [v10.x.x](#v10xx)
- [v9.x.x](#v9xx)
- [v6.x.x](#v6xx)
- [Installation](#installation)
- [Using @platformatic/prom-client](#using-platformaticprom-client)
- [Features and requirements](#features-and-requirements)
- [Usage](#usage)
- [Registry clear](#registry-clear)
- [Plugin options](#plugin-options)
- [Route metrics](#route-metrics)
- [Route metrics enabled](#route-metrics-enabled)
- [Route metrics overrides](#route-metrics-overrides)
- [Labels](#labels)
- [Request durations summary](#request-durations-summary)
- [Request durations histogram](#request-durations-histogram)
- [HTTP routes metrics in Prometheus](#http-routes-metrics-in-prometheus)
- [API Docs](#api-docs)
- [Changelog](#changelog)
- [See also](#see-also)
- [License](#license)
## Fastify support
- **v3.x.x** - supports `fastify-1.x`
- **v4.x.x** - supports `fastify-2.x` `prom-client-11.x`
- **v5.x.x** - supports `fastify-2.x` `prom-client-12.x`
- **v6.x.x** - supports `fastify-3.x`
- **v9.x.x** - supports `fastify-4.x` `prom-client-14.x`
- **v11.x.x** - supports `fastify-4.x` `prom-client-15.x`
- **v12.x.x** - supports `fastify-5.x` `prom-client-15.x`
## Notable changes
### v12.x.x
- Fastify v5 support.
- Drop node.js 18 support.
### v11.x.x
- Drop node.js 16 support.
- Upgrade to prom-client 15.1.
### v10.x.x
- Replace route `context.config` with `routeConfig` due to deprecation in fastify v4 and removal in fastify v5. If you had `disableMetrics` option in you route `config`, update fastify to latest version.
- Prefer `request.routeOptions.method` over deprecated `request.routerMethod`.
### v9.x.x
- Fastify v4 support.
- Complete config rewrite, default behaviour changed.
- Support disabling metrics in route config.
- Now collects metrics only for registered routes by default.
- Unknown routes metrics collection disabled by default.
- Removed `metrics` from `request`. Now it uses `WeakMap` and not exposed.
- Add balcklisting possibility for request methods.
- Registry overrides moved to metric configuration.
- Support overriding all Summary and Histogram options for default route metrics.
### v6.x.x
- Fastify v3 support.
- Drop node.js 8 support.
- `enableDefaultMetrics` - now enables only default `prom-client` metrics. Set to `true` by default.
- `enableRouteMetrics` - additional flag that enables route metrics. Set to `true` by default.
## Installation
```sh
npm i fastify-metrics --save
pnpm i fastify-metrics --save
```
[Back to top](#toc)
## Using @platformatic/prom-client
This plugin supports [@platformatic/prom-client](https://github.com/platformatic/prom-client) as an optional drop-in replacement for `prom-client`. It is a performance-focused fork by [Platformatic](https://platformatic.dev/) that provides the same API with lower overhead — optimized internal data structures, reduced memory allocations, and faster metric serialization.
**If `@platformatic/prom-client` is installed, the plugin will use it automatically.** No configuration changes needed. If it's not installed, the plugin falls back to standard `prom-client`.
### Why use it
| | `prom-client` | `@platformatic/prom-client` |
|---|---|---|
| **API** | Standard | Same (drop-in compatible) |
| **Internal storage** | `hashMap` | Optimized `LabelMap` |
| **Memory allocations** | Standard | Reduced |
| **Metric serialization** | Standard | Faster |
| **Node.js support** | >=16 | ^20 \|\| ^22 \|\| >=24 |
### Installation
Just install it alongside `fastify-metrics`:
```sh
npm i @platformatic/prom-client
pnpm i @platformatic/prom-client
```
The plugin auto-detects it on startup. No code changes required.
### Explicit client override
You can also pass the client explicitly via the `promClient` option. This takes precedence over auto-detection:
```js
import fastify from 'fastify';
import metricsPlugin from 'fastify-metrics';
import client from '@platformatic/prom-client';
const app = fastify();
await app.register(metricsPlugin, {
endpoint: '/metrics',
promClient: client,
});
```
### Verifying which client is active
After registration, `fastify.metrics.client` holds the resolved prom-client instance. You can check which one is being used:
```js
await app.ready();
console.log(app.metrics.client); // the active prom-client module
```
[Back to top](#toc)
## Features and requirements
- Collects default server metrics (see [prom-client](https://github.com/siimon/prom-client/tree/master/lib/metrics));
- Collects route response timings
- Adds `metrics` to fastify instance for your custom metrics.
---
- Requires fastify `>=4.0.0`.
- Node.js `>=20.0.0`.
[Back to top](#toc)
## Usage
Add it to your project like regular fastify plugin. Use `register` method and pass options to it.
```js
const fastify = require('fastify');
const app = fastify();
const metricsPlugin = require('fastify-metrics');
await app.register(metricsPlugin, { endpoint: '/metrics' });
```
It also exports client to fastify instance `fastify.metrics.client` which you may use it in your routes.
You may create your metrics when app starts and store it in `fastify.metrics` object and reuse them in multiple routes.
### Registry clear
After calling `registry.clear()` all metrics are removed from registry. In order to add them again to the registry, call `fastify.metrics.initMetricsInRegistry`.
[Back to top](#toc)
### Plugin options
See for details [docs](docs/api/fastify-metrics.imetricspluginoptions.md)
| Property | Type | Default Value |
| ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------- |
| [clearRegisterOnInit?](./docs/api/fastify-metrics.imetricspluginoptions.clearregisteroninit.md) | boolean | `false` |
| [defaultMetrics?](./docs/api/fastify-metrics.imetricspluginoptions.defaultmetrics.md) | [IDefaultMetricsConfig](./docs/api/fastify-metrics.idefaultmetricsconfig.md) | `{ enabled: true }` |
| [endpoint?](./docs/api/fastify-metrics.imetricspluginoptions.endpoint.md) | string \| null \| [`Fastify.RouteOptions`](https://www.fastify.io/docs/api/latest/Reference/Routes/#routes-options) | `'/metrics'` |
| [name?](./docs/api/fastify-metrics.imetricspluginoptions.name.md) | string | `'metrics'` |
| [promClient?](./docs/api/fastify-metrics.imetricspluginoptions.promclient.md) | `prom-client` instance \| null | `null` |
| [routeMetrics?](./docs/api/fastify-metrics.imetricspluginoptions.routemetrics.md) | [IRouteMetricsConfig](./docs/api/fastify-metrics.iroutemetricsconfig.md) | `{ enabled: true }` |
#### Route metrics
| Property | Type | Default Value |
| -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------- |
| [enabled?](./docs/api/fastify-metrics.iroutemetricsconfig.enabled.md) | boolean \| { histogram: boolean, summary: boolean } | `true` |
| [groupStatusCodes?](./docs/api/fastify-metrics.iroutemetricsconfig.groupstatuscodes.md) | boolean | `false` |
| [invalidRouteGroup?](./docs/api/fastify-metrics.iroutemetricsconfig.invalidroutegroup.md) | string | `'__unknown__'` |
| [methodBlacklist?](./docs/api/fastify-metrics.iroutemetricsconfig.methodblacklist.md) | readonly string\[\] | `['HEAD','OPTIONS','TRACE','CONNECT']` |
| [customLabels?](./docs/api/fastify-metrics.iroutemetricsconfig.customlabels.md) | Record<string, string \| ((request: FastifyRequest, reply: FastifyReply) => string)> | `undefined` |
| [overrides?](./docs/api/fastify-metrics.iroutemetricsconfig.overrides.md) | [IRouteMetricsOverrides](./docs/api/fastify-metrics.iroutemetricsoverrides.md) | |
| [registeredRoutesOnly?](./docs/api/fastify-metrics.iroutemetricsconfig.registeredroutesonly.md) | boolean | `true` |
| [routeBlacklist?](./docs/api/fastify-metrics.iroutemetricsconfig.routeblacklist.md) | readonly (string \| RegExp)\[\] | `undefined` |
##### Route metrics enabled
The `enabled` configuration option can be either a boolean which enables/disables generation of both histograms and summaries, or it can be set to an object that allows you to pick individually whether you want histograms or summaries to be generated, for example:
```
{
...
routeMetrics: {
enabled: {
histogram: true,
summary: false
}
}
}
```
would result in the library only generating histograms.
##### Route metrics overrides
You may override default metrics settings. You may provide overrides for two metrics tracking http request durations: `histogram` and `summary`.
```js
const fastify = require('fastify');
const app = fastify();
const metricsPlugin = require('fastify-metrics');
await app.register(metricsPlugin, {
endpoint: '/metrics',
routeMetrics: {
overrides: {
histogram: {
name: 'my_custom_http_request_duration_seconds',
buckets: [0.1, 0.5, 1, 3, 5],
},
summary: {
help: 'custom request duration in seconds summary help',
labelNames: ['status_code', 'method', 'route'],
percentiles: [0.5, 0.75, 0.9, 0.95, 0.99],
},
},
},
});
```
###### Labels
| Property | Type | Default value |
| ------------------------------------------------------------------------------------- | -------------------------------------- | --------------- |
| [getRouteLabel?](./docs/api/fastify-metrics.iroutelabelsoverrides.getroutelabel.md) | (request: FastifyRequest) => string | `undefined` |
| [method?](./docs/api/fastify-metrics.iroutelabelsoverrides.method.md) | string | `'method'` |
| [route?](./docs/api/fastify-metrics.iroutelabelsoverrides.route.md) | string | `'route'` |
| [status?](./docs/api/fastify-metrics.iroutelabelsoverrides.status.md) | string | `'status_code'` |
###### Request durations summary
| Property | Type | Default value |
| ----------------------------------------------------------------------- | ---------- | --------------------------------------- |
| [name?](./docs/fastify-metrics.isummaryoverrides.name.md) | string | `'http_request_summary_seconds'` |
| [help?](./docs/fastify-metrics.isummaryoverrides.help.md) | string | `'request duration in seconds summary'` |
| [percentiles?](./docs/fastify-metrics.isummaryoverrides.percentiles.md) | number\[\] | `[0.5, 0.9, 0.95, 0.99]` |
###### Request durations histogram
| Property | Type | Default value |
| --------------------------------------------------------------------- | ---------- | --------------------------------- |
| [name?](./docs/api/fastify-metrics.ihistogramoverrides.name.md) | string | `'http_request_duration_seconds'` |
| [help?](./docs/api/fastify-metrics.ihistogramoverrides.help.md) | string | `'request duration in seconds'` |
| [buckets?](./docs/api/fastify-metrics.ihistogramoverrides.buckets.md) | number\[\] | `[0.05, 0.1, 0.5, 1, 3, 5, 10]` |
[Back to top](#toc)
### HTTP routes metrics in Prometheus
The following table shows what metrics will be available in Prometheus (subject to the `enabled` configuration option). Note suffixes like `_bucket`, `_sum`, `_count` are added automatically.
| metric | labels | description |
| -------------------------------------- | -------------------------------- | ----------------------------- |
| `http_request_duration_seconds_count` | `method`, `route`, `status_code` | Requests total count |
| `http_request_duration_seconds_bucket` | `method`, `route`, `status_code` | Requests durations by bucket |
| `http_request_summary_seconds` | `method`, `route`, `status_code` | Requests duration percentiles |
| `http_request_summary_seconds_count` | `method`, `route`, `status_code` | Requests total count |
[Back to top](#toc)
## API Docs
See [docs](docs/api/index.md).
[Back to top](#toc)
## Changelog
See [changelog](docs/CHANGELOG.md).
[Back to top](#toc)
## See also
- [fastify-prom-client](https://github.com/ExcitableAardvark/fastify-prom-client) - just simple client that adds aggregated http requests metric.
[Back to top](#toc)
## Support Ukraine
If you find this project useful, please consider [supporting Ukraine's defense](./SPONSOR.md).
## License
Licensed under [MIT](./LICENSE).
[Back to top](#toc)