Skip to content

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 points you 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

  1. There were 0 to /user requests that were handled in less than 0.1ms
  2. There were 0 to /user requests that were handled in less than 5ms
  3. There were 0 to /user requests that were handled in less than 15ms
  4. There were 0 to /user requests that were handled in less than 50ms
  5. There were 0 to /user requests that were handled in less than 100ms
  6. There were 0 to /user requests that were handled in less than 500ms
  7. There were 0 to /user requests that were handled in less than 1000ms
  8. There were 1 to /user requests that were handled in less than 3000ms
  9. There were 1 to /user requests 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