Histograms
Course: Prometheus and Grafana - chapter 8
Histograms let you store data in various buckets in a cumulative fashion

- Add
metrics/requestCount.ts
import client from "prom-client";
export const httpRequestDurationMicroseconds = new client.Histogram({ name: 'http_request_duration_ms', help: 'Duration of HTTP requests in ms', labelNames: ['method', 'route', 'code'], buckets: [0.1, 5, 15, 50, 100, 300, 500, 1000, 3000, 5000] // Define your own buckets here});💡 Buckets here represent the
key pointsyou want to measure in your app. How many people had request handled in 0.1ms, 5ms, 15ms … This is because prometheus is not a DB, it just exposes all the metrics on an endpoint. That endpoint cant server all the data, and hence prometheus doesnt store the exact values, but how many requests were less than 0.1, 5, 15 …
- Update
metrics/index.ts
import { NextFunction, Request, Response } from "express";import { requestCounter } from "./requestCount";import { activeRequestsGauge } from "./activeRequests";import { httpRequestDurationMicroseconds } from "./requestTime";
export const metricsMiddleware = (req: Request, res: Response, next: NextFunction) => { const startTime = Date.now(); activeRequestsGauge.inc();
res.on('finish', function() { const endTime = Date.now(); const duration = endTime - startTime;
// Increment request counter requestCounter.inc({ method: req.method, route: req.route ? req.route.path : req.path, status_code: res.statusCode });
httpRequestDurationMicroseconds.observe({ method: req.method, route: req.route ? req.route.path : req.path, code: res.statusCode }, duration);
activeRequestsGauge.dec(); }); next();}- Go to the metrics endpoint

It says
- There were 0 to
/userrequests that were handled in less than 0.1ms - There were 0 to
/userrequests that were handled in less than 5ms - There were 0 to
/userrequests that were handled in less than 15ms - There were 0 to
/userrequests that were handled in less than 50ms - There were 0 to
/userrequests that were handled in less than 100ms - There were 0 to
/userrequests that were handled in less than 500ms - There were 0 to
/userrequests that were handled in less than 1000ms - There were 1 to
/userrequests that were handled in less than 3000ms - There were 1 to
/userrequests that were handled in less than 5000ms
As you can see, this is cumulative.
Number of requests being handled in less than 5000ms = Number of requests being handled in less than 3000ms + Number of requests that took between 3000-5000ms