NestJS course Β· Module 12: Containers and CI/CD

Observability - metrics with Prometheus

5 min read Β·
In this lesson5

You met Prometheus in the monitoring module: four metric types, scraping, and a /metrics endpoint written by hand in a controller. It worked - but every new metric meant remembering the registry, and every module meant injecting the service holding them.

NestJS has a ready answer. @willsoto/nestjs-prometheus collects and exposes application metrics in the Prometheus format - and along the way turns metrics into ordinary providers, injected like anything else.

Registering metrics

You declare metrics in a module, through the package's helper functions:

@Module({
  imports: [PrometheusModule.register()],
  providers: [
    makeCounterProvider({
      name: 'http_requests_total',
      help: 'Total number of HTTP requests',
      labelNames: ['method', 'route', 'status'],
    }),
    makeGaugeProvider({
      name: 'active_connections',
      help: 'Number of active connections',
    }),
    makeHistogramProvider({
      name: 'http_request_duration_seconds',
      help: 'HTTP request handling time',
      labelNames: ['method', 'route'],
    }),
  ],
})
export class MetricsModule {}

The order inside makeCounterProvider is fixed: makeCounterProvider({, then name: 'http_requests_total',, then help: '...',, and finally }).

PrometheusModule.register() exposes the /metrics endpoint - you no longer write it yourself. The three helper functions match the three metric types you know: a Counter only rises (request count), a Gauge rises and falls (active connections), a Histogram measures a distribution across buckets (response times). The fourth type, Summary, computes quantiles inside the application.

Use in a service

You inject a registered metric like any provider - except you name it:

@Injectable()
export class MetricsService {
  constructor(
    @InjectMetric('http_requests_total')
    private readonly requestsCounter: Counter<string>,

    @InjectMetric('http_request_duration_seconds')
    private readonly requestDuration: Histogram<string>,
  ) {}

  recordRequest(method: string, route: string, status: number) {
    this.requestsCounter.inc({ method, route, status: String(status) });
  }

  startTimer(method: string, route: string) {
    return this.requestDuration.startTimer({ method, route });
  }
}

@InjectMetric('name') works like the @Inject with a token you met with useValue providers - a metric is not a class, so NestJS cannot match it by type.

Two methods are worth telling apart. inc() raises the counter by one; that is all a Counter can do. startTimer() returns a function you call once the work is finished - only then does the histogram record the measured time:

const timer = this.metricsService.startTimer('GET', '/legions');

await this.legionService.findAll();

timer();

This pattern - take a function, do the work, call the function - is handier than subtracting timestamps by hand, and it takes care of the unit: Prometheus histograms count in seconds, not milliseconds.

The RED method - what to measure first

You could add hundreds of metrics. RED is the acronym naming the three you always start with, ordered by importance:

  1. Rate - requests per second. It tells you whether there is any traffic at all.
  2. Errors - the share of requests ending in failure. It tells you whether the traffic is being served.
  3. Duration - response time, usually as p95 and p99. It tells you whether it is being served well.

The order is not arbitrary and is worth remembering: Rate dropping to zero means nobody can connect - an immediate alarm. Rising Errors is a failure users can see. Rising Duration is a problem still developing.

Note why time is given as percentiles rather than an average. An average of 200 ms sounds fine even when every twentieth user waits five seconds - p95 says outright: "95% of requests finished below this value". That is a number describing the experience rather than blurring it.

What /metrics returns

The endpoint the package exposes hands data back in the Prometheus text format - not JSON, not XML, not CSV:

# HELP http_requests_total Total number of HTTP requests
# TYPE http_requests_total counter
http_requests_total{method="GET",route="/legions",status="200"} 1027
http_requests_total{method="POST",route="/legions",status="201"} 43

The shape is simple and worth being able to read. Lines beginning with # HELP carry the metric's description, and those with # TYPE its type. Then come the measurements themselves: the name, the labels in braces, the value.

This format looks poor next to JSON, but that is the point: Prometheus queries thousands of applications every dozen seconds, so parsing has to be cheap. When you open /metrics in a browser and see a wall of text - that means it works.

Summary

The Empire's eyes are watching, and metrics are ordinary providers:

  • @willsoto/nestjs-prometheus collects and exposes metrics in the Prometheus format - it does not handle WebSockets, test endpoints or generate documentation,
  • PrometheusModule.register() exposes the /metrics endpoint for you,
  • you register metrics as providers: makeCounterProvider, makeGaugeProvider, makeHistogramProvider,
  • registration order: makeCounterProvider({, name:, help:, }),
  • a Counter can only rise (request count); a Gauge rises and falls; a Histogram measures a distribution across buckets; a Summary computes quantiles,
  • @InjectMetric('name') injects a metric by name, because it is not a class and a type will not do,
  • inc() raises the counter; startTimer() returns a function you call after the work - histograms count in seconds,
  • the RED method by importance: Rate (requests per second) β†’ Errors (share of failures) β†’ Duration (p95, p99),
  • give time as percentiles, not an average - an average hides every twentieth user waiting five seconds,
  • /metrics returns the Prometheus text format: # HELP, # TYPE, then the name with labels and a value - not JSON, XML or CSV.

In the next lesson we will go a step beyond numbers - you will meet distributed tracing, which shows a single request's road through many services. For now remember: metrics tell you how many and how fast; RED names the three numbers to check first.

Code for this lesson: src/prometheus-metrics.ts
// Observability - Metrics with Prometheus
console.log("=== PROMETHEUS METRICS ===\n");

// Prometheus metric types
interface MetricType {
  name: string;
  type: 'counter' | 'gauge' | 'histogram' | 'summary';
  description: string;
  example: string;
}

const metricTypes: MetricType[] = [
  {
    name: 'Counter',
    type: 'counter',
    description: 'Only grows (e.g. number of requests)',
    example: 'http_requests_total{method="GET",status="200"} 1547',
  },
  {
    name: 'Gauge',
    type: 'gauge',
    description: 'Grows and shrinks (e.g. active connections)',
    example: 'active_connections 42',
  },
  {
    name: 'Histogram',
    type: 'histogram',
    description: 'Distribution of values in buckets (e.g. response times)',
    example: 'http_request_duration_seconds_bucket{le="0.1"} 1400',
  },
  {
    name: 'Summary',
    type: 'summary',
    description: 'Quantiles (p50, p95, p99)',
    example: 'request_duration_summary{quantile="0.95"} 0.25',
  },
];

console.log("Prometheus metric types:\n");
metricTypes.forEach((m, i) => {
  console.log(`${i + 1}. ${m.name} (${m.type})`);
  console.log(`   Description: ${m.description}`);
  console.log(`   Example: ${m.example}\n`);
});

// RED Method
console.log("=== RED METHOD ===\n");
const red = {
  Rate: 'Number of requests per second',
  Errors: 'Percent of requests with errors',
  Duration: 'Response time (p95, p99)',
};

Object.entries(red).forEach(([k, v]) => {
  console.log(`  ${k}: ${v}`);
});

console.log("\n=== ENDPOINT /metrics ===\n");
console.log("# HELP http_requests_total Total number of requests");
console.log("# TYPE http_requests_total counter");
console.log('http_requests_total{method="GET",status="200"} 1547');

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the @willsoto/nestjs-prometheus package used for?

  2. 2. What characterizes a Counter metric type in Prometheus?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Define three metrics: http_requests_total (Counter with labelNames: method, route, status), active_connections (Gauge), http_request_duration (Histogram)

  • Vertical ordering

    Arrange the elements of the RED method from most important to least frequently checked:

  • Click in order

    Arrange the elements of Counter metric registration in PrometheusModule:

  • Code editor

    Inject metrics via @InjectMetric, use requestsCounter.inc() and requestDuration.startTimer() / timer()

  1. QuestionThe @willsoto/nestjs-prometheus package
  2. QuestionCounter metric type in Prometheus
  3. Coding taskConfiguring Prometheus metrics in NestJS
  4. Put in orderThe RED method - analysis order
  5. Click in orderRegistering a Counter metric in Prometheus
  6. Coding taskUsing metrics in a NestJS service
  7. QuestionThe /metrics endpoint in Prometheus

Useful articles