Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(metrics): expose HTTP RED metrics (request rate + duration) (#709)

Yudhi Armyndharisebe45254b66f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0cfda721d..92daadd13 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
explicitly (`provenance: true`) so the attestation pair is self-documenting rather than reliant on
the action default.
+- **HTTP RED metrics.** The `/api/metrics` endpoint now exposes
+ `http_requests_total{method,route,status}` and an `http_request_duration_seconds` histogram (per
+ route), recorded by a global interceptor. Route labels use the Express route pattern (bounded —
+ `/api/sessions/:id`, not the raw URL) with a `Controller#handler` fallback, and `/api/health` +
+ `/api/metrics` are not counted. Conventional unprefixed names so a generic RED dashboard or a 5xx
+ error-rate alert matches them directly.
+
### Fixed
- **OpenAPI export script under current env validation.** `scripts/export-openapi.ts` had been broken
diff --git a/src/common/interceptors/request-metrics.interceptor.spec.ts b/src/common/interceptors/request-metrics.interceptor.spec.ts
new file mode 100644
index 000000000..d1850b7e0
--- /dev/null
+++ b/src/common/interceptors/request-metrics.interceptor.spec.ts
@@ -0,0 +1,93 @@
+jest.mock('../metrics/request-metrics', () => ({
+ recordHttpRequest: jest.fn(),
+ renderHttpRequestMetrics: jest.fn(() => []),
+ resetHttpRequestMetrics: jest.fn(),
+}));
+
+import { Observable } from 'rxjs';
+import { RequestMetricsInterceptor } from './request-metrics.interceptor';
+import { recordHttpRequest } from '../metrics/request-metrics';
+
+const mockedRecord = recordHttpRequest as jest.MockedFunction<typeof recordHttpRequest>;
+
+interface Ctx {
+ ctx: Record<string, unknown>;
+ listeners: { finish?: () => void; close?: () => void };
+}
+
+function makeContext(opts: {
+ method?: string;
+ routePath?: string;
+ statusCode?: number;
+ className?: string;
+ handlerName?: string;
+}): Ctx {
+ const req = { method: opts.method ?? 'GET', route: opts.routePath ? { path: opts.routePath } : undefined };
+ const listeners: { finish?: () => void; close?: () => void } = {};
+ const res = {
+ statusCode: opts.statusCode ?? 200,
+ on: (event: string, cb: () => void): void => {
+ listeners[event as 'finish' | 'close'] = cb;
+ },
+ };
+ const ctx = {
+ switchToHttp: () => ({ getRequest: () => req, getResponse: () => res }),
+ getClass: () => ({ name: opts.className ?? 'SessionController' }),
+ getHandler: () => ({ name: opts.handlerName ?? 'list' }),
+ };
+ return { ctx, listeners };
+}
+
+const noopHandler = { handle: (): Observable<unknown> => new Observable<unknown>() };
+
+describe('RequestMetricsInterceptor', () => {
+ beforeEach(() => mockedRecord.mockClear());
+
+ it('records on response finish with method/route/status and a duration', () => {
+ const { ctx, listeners } = makeContext({ method: 'GET', routePath: '/api/sessions', statusCode: 200 });
+ new RequestMetricsInterceptor().intercept(ctx as never, noopHandler as never);
+ listeners.finish?.();
+ expect(mockedRecord).toHaveBeenCalledTimes(1);
+ const [method, route, status, seconds] = mockedRecord.mock.calls[0];
+ expect(method).toBe('GET');
+ expect(route).toBe('/api/sessions');
+ expect(status).toBe(200);
+ expect(seconds).toBeGreaterThanOrEqual(0);
+ });
+
+ it('skips /api/health and /api/metrics entirely (no observation, no listener)', () => {
+ for (const path of ['/api/health', '/api/health/live', '/api/metrics']) {
+ const { ctx, listeners } = makeContext({ routePath: path });
+ new RequestMetricsInterceptor().intercept(ctx as never, noopHandler as never);
+ listeners.finish?.();
+ expect(mockedRecord).not.toHaveBeenCalled();
+ mockedRecord.mockClear();
+ }
+ });
+
+ it('records the final status set by exception filters (e.g. 500)', () => {
+ const { ctx, listeners } = makeContext({ routePath: '/api/sessions', statusCode: 500 });
+ new RequestMetricsInterceptor().intercept(ctx as never, noopHandler as never);
+ listeners.finish?.();
+ expect(mockedRecord.mock.calls[0][2]).toBe(500);
+ });
+
+ it('falls back to Controller#handler when the Express route is unavailable', () => {
+ const { ctx, listeners } = makeContext({
+ routePath: undefined,
+ className: 'MessageController',
+ handlerName: 'sendText',
+ });
+ new RequestMetricsInterceptor().intercept(ctx as never, noopHandler as never);
+ listeners.finish?.();
+ expect(mockedRecord.mock.calls[0][1]).toBe('MessageController#sendText');
+ });
+
+ it('records once even if both finish and close fire', () => {
+ const { ctx, listeners } = makeContext({ routePath: '/api/sessions' });
+ new RequestMetricsInterceptor().intercept(ctx as never, noopHandler as never);
+ listeners.finish?.();
+ listeners.close?.();
+ expect(mockedRecord).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/common/interceptors/request-metrics.interceptor.ts b/src/common/interceptors/request-metrics.interceptor.ts
new file mode 100644
index 000000000..efefee269
--- /dev/null
+++ b/src/common/interceptors/request-metrics.interceptor.ts
@@ -0,0 +1,54 @@
+import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
+import { Observable } from 'rxjs';
+import type { Request, Response } from 'express';
+import { recordHttpRequest } from '../metrics/request-metrics';
+
+/**
+ * Records one HTTP RED observation per request into the in-process request-metrics store.
+ *
+ * Listens for the response's `finish` (and `close`, for premature disconnects) rather than tapping
+ * the handler observable, because exception filters set the final `res.statusCode` AFTER the
+ * interceptor's observable chain — `finish`/`close` see the real status (2xx/4xx/5xx). The `recorded`
+ * guard keeps it to one observation per request even when both events fire.
+ *
+ * Route label: the Express route pattern when available (bounded — `/api/sessions/:id`, not the raw
+ * URL), falling back to `Controller#handler` (always available, strictly bounded).
+ */
+const SKIPPED_PREFIXES = ['/api/health', '/api/metrics'];
+
+@Injectable()
+export class RequestMetricsInterceptor implements NestInterceptor {
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
+ const req = context.switchToHttp().getRequest<Request>();
+ const res = context.switchToHttp().getResponse<Response>();
+ const route = resolveRoute(context, req);
+ if (route === null || SKIPPED_PREFIXES.some(prefix => route.startsWith(prefix))) {
+ return next.handle();
+ }
+ const method = (req.method ?? 'UNKNOWN').toUpperCase();
+ const start = process.hrtime.bigint();
+ let recorded = false;
+ const record = (): void => {
+ if (recorded) return;
+ recorded = true;
+ const seconds = Number(process.hrtime.bigint() - start) / 1e9;
+ recordHttpRequest(method, route, res.statusCode ?? 200, seconds);
+ };
+ res.on('finish', record);
+ res.on('close', record);
+ return next.handle();
+ }
+}
+
+function resolveRoute(context: ExecutionContext, req: Request): string | null {
+ const expressRoute = (req as unknown as { route?: { path?: string } }).route?.path;
+ if (expressRoute) return expressRoute;
+ try {
+ const className = context.getClass()?.name;
+ const handlerName = context.getHandler()?.name;
+ if (className && handlerName) return `${className}#${handlerName}`;
+ } catch {
+ // ExecutionContext not populated for a non-HTTP caller — should not happen for a real request.
+ }
+ return null;
+}
diff --git a/src/common/metrics/request-metrics.spec.ts b/src/common/metrics/request-metrics.spec.ts
new file mode 100644
index 000000000..5399c0fab
--- /dev/null
+++ b/src/common/metrics/request-metrics.spec.ts
@@ -0,0 +1,54 @@
+import { recordHttpRequest, renderHttpRequestMetrics, resetHttpRequestMetrics } from './request-metrics';
+
+describe('request-metrics (HTTP RED store)', () => {
+ beforeEach(() => resetHttpRequestMetrics());
+
+ const lines = () => renderHttpRequestMetrics().join('\n');
+
+ it('records one request into http_requests_total{method,route,status}', () => {
+ recordHttpRequest('GET', '/api/sessions', 200, 0.01);
+ expect(lines()).toContain('http_requests_total{method="GET",route="/api/sessions",status="200"} 1');
+ });
+
+ it('aggregates the counter across repeated identical requests', () => {
+ recordHttpRequest('GET', '/api/sessions', 200, 0.01);
+ recordHttpRequest('GET', '/api/sessions', 200, 0.02);
+ recordHttpRequest('GET', '/api/sessions', 500, 0.03);
+ expect(lines()).toContain('http_requests_total{method="GET",route="/api/sessions",status="200"} 2');
+ expect(lines()).toContain('http_requests_total{method="GET",route="/api/sessions",status="500"} 1');
+ });
+
+ it('records duration into the histogram with cumulative buckets', () => {
+ recordHttpRequest('GET', '/api/sessions', 200, 0.05);
+ const out = lines();
+ // 0.05 falls into le="0.05" and every larger bucket, but NOT le="0.025" or below.
+ expect(out).toContain('http_request_duration_seconds_bucket{method="GET",route="/api/sessions",le="0.05"} 1');
+ expect(out).toContain('http_request_duration_seconds_bucket{method="GET",route="/api/sessions",le="0.025"} 0');
+ expect(out).toContain('http_request_duration_seconds_bucket{method="GET",route="/api/sessions",le="+Inf"} 1');
+ expect(out).toContain('http_request_duration_seconds_count{method="GET",route="/api/sessions"} 1');
+ expect(out).toMatch(/http_request_duration_seconds_sum\{method="GET",route="\/api\/sessions"} 0\.05\d*/);
+ });
+
+ it('emits HELP/TYPE headers exactly once per metric, regardless of series count', () => {
+ recordHttpRequest('GET', '/api/sessions', 200, 0.01);
+ recordHttpRequest('POST', '/api/messages', 201, 0.01);
+ const out = lines();
+ expect(out.split('# HELP http_requests_total').length - 1).toBe(1);
+ expect(out.split('# TYPE http_requests_total').length - 1).toBe(1);
+ expect(out.split('# HELP http_request_duration_seconds').length - 1).toBe(1);
+ expect(out.split('# TYPE http_request_duration_seconds').length - 1).toBe(1);
+ });
+
+ it('escapes special label characters (quote, backslash, newline) in the route label', () => {
+ recordHttpRequest('GET', '/api/"weird"/path', 200, 0.01);
+ expect(lines()).toContain('route="/api/\\"weird\\"/path"');
+ });
+
+ it('reset clears both the counter and the histogram', () => {
+ recordHttpRequest('GET', '/api/sessions', 200, 0.01);
+ resetHttpRequestMetrics();
+ const out = lines();
+ expect(out).not.toContain('http_requests_total{');
+ expect(out).not.toContain('http_request_duration_seconds_count{');
+ });
+});
diff --git a/src/common/metrics/request-metrics.ts b/src/common/metrics/request-metrics.ts
new file mode 100644
index 000000000..daa5d6517
--- /dev/null
+++ b/src/common/metrics/request-metrics.ts
@@ -0,0 +1,109 @@
+/**
+ * HTTP RED metrics — request rate + duration, recorded per route — emitted in Prometheus text
+ * exposition format alongside the business metrics in MetricsService.render().
+ *
+ * Kept dependency-free (no prom-client), mirroring webhook-delivery-metrics.ts: an in-process store
+ * that resets only on restart (Prometheus counters handle a restart as a reset, which rate()/
+ * increase() already tolerate). Conventional unprefixed names (http_requests_total,
+ * http_request_duration_seconds) so a generic RED dashboard/alert matches them.
+ */
+
+// Prometheus-default-style buckets covering typical web request latencies (seconds).
+const DURATION_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
+
+interface CounterSeries {
+ method: string;
+ route: string;
+ status: string;
+ count: number;
+}
+
+interface HistogramSeries {
+ method: string;
+ route: string;
+ /** Cumulative count of observations <= DURATION_BUCKETS[i]. */
+ buckets: number[];
+ sum: number;
+ count: number;
+}
+
+// Composite keys keep a single observation's labels grouped without mutating the stored values.
+const requestCounts = new Map<string, CounterSeries>();
+const requestDurations = new Map<string, HistogramSeries>();
+
+function escapeLabelValue(value: string): string {
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
+}
+
+/**
+ * Record one HTTP request: increments the `{method,route,status}` counter and observes the duration
+ * in the `{method,route}` histogram (cumulative buckets + sum + count).
+ */
+export function recordHttpRequest(method: string, route: string, status: number, durationSeconds: number): void {
+ const methodLabel = method.toUpperCase();
+ const statusLabel = String(status);
+
+ const ckey = `${methodLabel}|${route}|${statusLabel}`;
+ const counter = requestCounts.get(ckey);
+ if (counter) {
+ counter.count += 1;
+ } else {
+ requestCounts.set(ckey, { method: methodLabel, route, status: statusLabel, count: 1 });
+ }
+
+ const hkey = `${methodLabel}|${route}`;
+ let histogram = requestDurations.get(hkey);
+ if (!histogram) {
+ histogram = {
+ method: methodLabel,
+ route,
+ buckets: Array.from({ length: DURATION_BUCKETS.length }, () => 0),
+ sum: 0,
+ count: 0,
+ };
+ requestDurations.set(hkey, histogram);
+ }
+ histogram.sum += durationSeconds;
+ histogram.count += 1;
+ for (let i = 0; i < DURATION_BUCKETS.length; i++) {
+ if (durationSeconds <= DURATION_BUCKETS[i]) histogram.buckets[i] += 1;
+ }
+}
+
+/** Render the RED metrics as Prometheus text-exposition lines (empty until something is recorded). */
+export function renderHttpRequestMetrics(): string[] {
+ const lines: string[] = [];
+ if (requestCounts.size === 0 && requestDurations.size === 0) return lines;
+
+ if (requestCounts.size > 0) {
+ lines.push('# HELP http_requests_total Total HTTP requests by method, route, and HTTP status.');
+ lines.push('# TYPE http_requests_total counter');
+ for (const c of requestCounts.values()) {
+ lines.push(
+ `http_requests_total{method="${escapeLabelValue(c.method)}",route="${escapeLabelValue(c.route)}",status="${escapeLabelValue(c.status)}"} ${c.count}`,
+ );
+ }
+ }
+
+ if (requestDurations.size > 0) {
+ lines.push('# HELP http_request_duration_seconds HTTP request duration in seconds.');
+ lines.push('# TYPE http_request_duration_seconds histogram');
+ for (const h of requestDurations.values()) {
+ const labels = `method="${escapeLabelValue(h.method)}",route="${escapeLabelValue(h.route)}"`;
+ for (let i = 0; i < DURATION_BUCKETS.length; i++) {
+ lines.push(`http_request_duration_seconds_bucket{${labels},le="${DURATION_BUCKETS[i]}"} ${h.buckets[i]}`);
+ }
+ lines.push(`http_request_duration_seconds_bucket{${labels},le="+Inf"} ${h.count}`);
+ lines.push(`http_request_duration_seconds_sum{${labels}} ${h.sum}`);
+ lines.push(`http_request_duration_seconds_count{${labels}} ${h.count}`);
+ }
+ }
+
+ return lines;
+}
+
+/** Reset all RED series (test-only; the live process never calls this). */
+export function resetHttpRequestMetrics(): void {
+ requestCounts.clear();
+ requestDurations.clear();
+}
diff --git a/src/modules/metrics/metrics.module.ts b/src/modules/metrics/metrics.module.ts
index 8868fcd36..06cae5e01 100644
--- a/src/modules/metrics/metrics.module.ts
+++ b/src/modules/metrics/metrics.module.ts
@@ -1,12 +1,18 @@
import { Module } from '@nestjs/common';
+import { APP_INTERCEPTOR } from '@nestjs/core';
import { ConfigModule } from '@nestjs/config';
import { MetricsController } from './metrics.controller';
import { MetricsService } from './metrics.service';
import { StatsModule } from '../stats/stats.module';
+import { RequestMetricsInterceptor } from '../../common/interceptors/request-metrics.interceptor';
@Module({
imports: [ConfigModule, StatsModule],
controllers: [MetricsController],
- providers: [MetricsService],
+ providers: [
+ MetricsService,
+ // Global: one HTTP RED observation per inbound request, skipped for /api/health and /api/metrics.
+ { provide: APP_INTERCEPTOR, useClass: RequestMetricsInterceptor },
+ ],
})
export class MetricsModule {}
diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.ts
index 1c3f974de..9bccf14c5 100644
--- a/src/modules/metrics/metrics.service.ts
+++ b/src/modules/metrics/metrics.service.ts
@@ -3,6 +3,7 @@ import { ConfigService } from '@nestjs/config';
import { timingSafeEqual } from 'crypto';
import { StatsService } from '../stats/stats.service';
import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';
+import { renderHttpRequestMetrics } from '../../common/metrics/request-metrics';
/**
* Prometheus exposition for OpenWA. Kept dependency-free (no prom-client) — the
@@ -104,6 +105,10 @@ export class MetricsService {
lines.push('# TYPE openwa_webhook_delivery_failures_total counter');
lines.push(`openwa_webhook_delivery_failures_total ${getWebhookDeliveryFailuresTotal()}`);
+ // HTTP RED metrics (request rate + duration per route), recorded by RequestMetricsInterceptor.
+ // Included in the same cached render — a few seconds of staleness is fine for Prometheus.
+ lines.push(...renderHttpRequestMetrics());
+
const text = lines.join('\n') + '\n';
this.cachedRender = { at: now, text };
return text;