如何基于MicroProfile Metrics暴露模型推理延迟的直方图?

解读

在国内金融、运营商、政务云等关键业务场景中,AI 推理服务往往被封装成 REST 或 gRPC 端点并部署在 JBoss EAP 集群内。面试官问“暴露模型推理延迟的直方图”,核心想验证三件事:

  1. 你是否理解 MicroProfile Metrics 在 JBoss EAP 上的实现原理(SmallRye Metrics 子系统)
  2. 能否把“业务指标”与“容器平台指标”打通,满足 Prometheus + Grafana 的监控规范
  3. 是否具备生产级意识:直方图 bucket 边界如何选、是否开启压缩、是否对 P99 敏感、是否影响 STW 停顿

因此,回答必须给出“可落地的完整代码 + 配置 + 验证命令”,并主动说出国内甲方常见的合规细节(如三级等保要求指标落盘加密、跨中心双活时序库一致性)。

知识点

  1. JBoss EAP 7.4+ 内置 MicroProfile 4.x,SmallRye Metrics 自动将 @Metric 注解的指标注册到 /metrics 端点
  2. 直方图(Histogram)与摘要(Summary)区别:Histogram 在服务端聚合,适合 Prometheus 拉取;Summary 在客户端聚合,不适合多实例聚合
  3. 指标 ID 命名必须满足“三级等保”审计正则:[a-zA-Z_][a-zA-Z0-9_]*,且单位用“_seconds”结尾,否则 Grafana 大盘模板无法识别
  4. 生产环境需开启 metrics-histogram-bucket-expire 参数,防止 bucket 无界增长导致 Old GC
  5. 在 OpenShift 4.x 上,ServiceMonitor 默认每 30 s 拉取一次,bucket 数量建议 ≤20,否则 1.5 h 后磁盘 WAL 翻倍
  6. 如果推理框架是 TensorFlow-Java 或 ONNX-Runtime,需在 finally 块里记录,否则 JIT 内联后采样点丢失,P99 偏低 10% 以上

答案

步骤一:在 pom.xml 引入 BOM,确保版本与 EAP 一致

<dependency>
    <groupId org.jboss.bom</groupId>
    <artifactId>jboss-eap-microprofile</artifactId>
    <version>7.4.9.GA</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>
<dependency>
    <groupId>org.eclipse.microprofile.metrics</groupId>
    <artifactId>microprofile-metrics-api</artifactId>
</dependency>

步骤二:编写应用级直方图,注意 bucket 边界覆盖国内常见推理耗时区间(50 ms、100 ms、200 ms、500 ms、1 s、2 s、5 s)

@ApplicationScoped
public class InferenceRegistry {
    @Inject
    @Metric(name = "model_inference_latency_seconds",
            absolute = true,
            description = "Histogram of AI model inference duration",
            unit = MetricUnits.SECONDS,
            tags = {"model=resnet50","version=v2.1"})
    Histogram latencyHist;

    public void recordLatency(long startNanos){
        double seconds = (System.nanoTime() - startNanos) / 1_000_000_000d;
        latencyHist.update(seconds);
    }
}

步骤三:在 REST 端点埋点,保证采样不受 JIT 优化影响

@Path("/predict")
public class PredictResource {
    @Inject InferenceRegistry registry;

    @POST
    @Timed(name = "predict_timer")   // 可选,与直方图互补
    public Response predict(ImageDTO dto){
        long start = System.nanoTime();
        try{
            byte[] output = model.run(dto.getImage());
            return Response.ok(output).build();
        }finally{
            registry.recordLatency(start);
        }
    }
}

步骤四:在 WEB-INF/jboss-deployment-structure.xml 中关闭隐式模块扫描,防止加载冲突

<jboss-deployment-structure>
    <deployment>
        <exclude-subsystems>
            <subsystem name="microprofile-metrics-smallrye"/>
        </exclude-subsystems>
        <dependencies>
            <module name="org.wildfly.extension.microprofile.metrics-smallrye" export="true"/>
        </dependencies>
    </deployment>
</jboss-deployment-structure>

步骤五:启动 EAP 并验证

$JBOSS_HOME/bin/jboss-cli.sh -c
/subsystem=microprofile-metrics-smallrye:write-attribute(name=exposed-subsystems,value=["deployment.*"])
reload

浏览器访问 https://<pod-ip>:8443/metrics,应出现:

# HELP model_inference_latency_seconds Histogram of AI model inference duration
# TYPE model_inference_latency_seconds histogram
model_inference_latency_seconds{model="resnet50",version="v2.1",le="0.05"}  31.0
...
model_inference_latency_seconds{model="resnet50",version="v2.1",le="+Inf"}  100.0

步骤六:在 Grafana 侧使用 histogram_quantile(0.99, ...) 计算 P99,并配置 Recording Rule 降低查询压力。满足央行《金融分布式系统监控规范》对“实时 P99 告警≤30 s”要求。

拓展思考

  1. 如果推理服务采用 GraalVM 原生镜像,Histogram 的 update() 方法会被编译为静态二进制,此时需使用 MetricRegistry 的 histogram() 编程式注册,否则指标丢失
  2. 在两地三中心场景下,Prometheus 联邦查询会出现 bucket 维度漂移,可通过 label_replace 统一 cluster 标签,并在 Thanos Receive 做降采样
  3. 若甲方要求“零信任”,需开启 TLS 双向认证,并在 microprofile-config.properties 中配置 mp.metrics.secure=true,同时在 EAP 的 elytron 子系统里挂载国密 SM2 证书
  4. 当模型热更新时,版本标签会瞬间增加,导致 cardinality 爆炸;可自定义 MetricFilter,在 MetricRegistry 中移除 1 h 内无更新的版本标签,防止 etcd 容量超限
  5. 未来升级到 Jakarta EE 10 及 MicroProfile 6.0 后,直方图将默认采用 Exponential Bucket,需提前在 DevOps 流水线里验证现有 Grafana 大盘是否兼容,否则 P99 曲线会出现跳变