如何使用 Prometheus 暴露 NestJS 应用的指标(如请求数、响应时间)?
解读
在国内一线/二线互联网公司的后端面试中,Prometheus 几乎成了“标配”监控方案。面试官问这道题,表面看是“怎么埋点”,实质想确认三件事:
- 你是否理解 NestJS 的 IoC 与 AOP 机制,能否优雅地把监控代码从业务里剥离;
- 你是否熟悉 Node.js 性能指标(event loop lag、gc、uv_handles 等),而不仅是“请求数”;
- 你是否具备生产级思维:指标维度如何设计、如何防止 cardinality 爆炸、如何与 Grafana 团队协同。
因此,回答必须体现“装饰器 + 拦截器 + 自定义指标”三位一体,并给出可直接落地的代码片段与踩坑提示。
知识点
- prom-client:Node.js 官方 Prometheus SDK,支持 Counter、Histogram、Gauge、Summary。
- NestJS 拦截器(Interceptor):AOP 切面,适合无侵入地统计响应时间。
- 中间件(Middleware):在拦截器之前执行,可拿到原生 req/res,适合统计请求数。
- 自定义装饰器:@PrometheusTime() 细粒度标记“业务方法”耗时,避免全链路一刀切。
- 标签(label)设计规范:统一 statusCode、method、route、service 四个维度;禁止把 userId、订单号等高频可变字段作为 label。
- 性能陷阱:histogram 的 buckets 数量 × label 组合数 不能超过 10 万,否则内存暴涨;Node.js 单线程,埋点逻辑必须异步非阻塞。
- 暴露路由:/metrics 必须走独立端口(9100)或独立 k8s sidecar,防止业务流量打爆监控端口。
- 安全合规:国内金融、政企项目要求“最小可用端口开放”,/metrics 需做 IP 白名单或内网 SLB 二次鉴权。
答案
步骤一:安装依赖 npm i prom-client @willsoto/nestjs-prometheus // 后者提供官方封装,减少样板代码
步骤二:全局注册 PrometheusModule // app.module.ts import { PrometheusModule } from '@willsoto/nestjs-prometheus';
@Module({ imports: [ PrometheusModule.register({ path: '/metrics', defaultMetrics: { enabled: true }, // 自动采集 event loop、gc、内存 customMetricPrefix: 'nestjs_app', // 指标统一前缀,方便 Grafana 检索 }), ], }) export class AppModule {}
步骤三:自定义业务指标(请求数 + 响应时间) // metrics.service.ts import { Injectable } from '@nestjs/common'; import { InjectMetric } from '@willsoto/nestjs-prometheus'; import { Counter, Histogram } from 'prom-client';
@Injectable() export class MetricsService { constructor( @InjectMetric('http_requests_total') public readonly httpRequests: Counter<string>, @InjectMetric('http_request_duration_seconds') public readonly httpDuration: Histogram<string>, ) {}
recordRequest(method: string, route: string, status: number, duration: number) {
const labels = { method, route, status: ${status} };
this.httpRequests.inc(labels);
this.httpDuration.observe(labels, duration);
}
}
步骤四:拦截器无侵入埋点 // prometheus.interceptor.ts import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { MetricsService } from './metrics.service';
@Injectable() export class PrometheusInterceptor implements NestInterceptor { constructor(private readonly metrics: MetricsService) {}
intercept(ctx: ExecutionContext, next: CallHandler): Observable<any> { const start = Date.now(); const req = ctx.switchToHttp().getRequest(); return next.handle().pipe( tap(() => { const cost = (Date.now() - start) / 1000; const { method, route } = req; const status = ctx.switchToHttp().getResponse().statusCode; // 注意:route 需脱敏,去掉 /users/:id 中的实际 id const routePath = route?.path || req.path; this.metrics.recordRequest(method, routePath, status, cost); }), ); } }
在 main.ts 全局绑定: app.useGlobalInterceptors(new PrometheusInterceptor(app.get(MetricsService)));
步骤五:验证 curl http://localhost:3000/metrics | grep nestjs_app 应看到: nestjs_app_http_requests_total{method="GET",route="/api/v1/order",status="200"} 42 nestjs_app_http_request_duration_seconds_bucket{le="0.1",method="GET",route="/api/v1/order",status="200"} 38 ……
步骤六:生产级加固
- 使用 cluster 模式时,prom-client 默认聚合多进程指标,无需改动;
- 若部署在 k8s,推荐把 /metrics 绑定到 9100 端口,通过 ServiceMonitor 让 Prometheus Operator 自动发现;
- 对大流量接口(如秒杀),可单独定义 Summary 分位数(0.5/0.95/0.99),并调大采样窗口至 5 分钟,降低抓取压力;
- 国内阿里云 Prometheus 按“指标上报量”计费,务必在上线前用
promtool check metrics做 cardinality 审计,确保单指标 label 组合 < 5000。
拓展思考
-
如何监控 GraphQL 解析器? GraphQL 没有“路由”概念,可在自定义 Plugin 里使用
graphql-ws的onResolve钩子,把info.fieldName作为 route 标签,其余逻辑与 REST 保持一致。 -
如何监控微服务 RPC? 在 @nestjs/microservices 的 ClientProxy 工厂层统一封装“调用-响应”拦截器,把
pattern作为 route 标签,把clientId作为额外维度,防止与 HTTP 指标混淆。 -
如何防止高基数导致内存泄漏? 使用
labelValues白名单机制:在 MetricsService 里维护一个 LRU(max 500),遇到新 label 组合先检查是否超限,再决定是否丢弃或聚合到route="unknown"。 -
如何与 SLS(阿里云日志服务)做“双写”? 利用 prom-client 的
register.metrics()方法,在定时任务里把文本格式推送到 SLS 的 Prometheus 兼容接口,实现“云下+云上”双通道,满足金融客户合规审计要求。 -
面试加分项:主动提到 OpenTelemetry。 可以补充:“如果公司未来要接入 Jaeger、SkyWalking,可把上述 Histogram 改为 OTEL 的
ValueRecorder,通过@opentelemetry/exporter-prometheus直接复用现有 Grafana 看板,实现 Tracing 与 Metrics 的关联。”