给出基于 Prometheus 的“规则命中率”指标暴露代码,实现 SLA 监控

解读

国内实时风控、日志 ETL 等 Storm Topology 普遍用“规则引擎”做决策,规则命中率(命中的规则数 / 总触发规则数)直接反映 SLA 质量。面试官想验证两点:

  1. 能否在不改 Storm 源码的前提下,用 Prometheus Java Client 把指标从 Bolt 内部暴露出去;
  2. 能否把指标落到 Prometheus 可拉取的 /metrics 端点,并配套给出 SLI(≥99.9%)与告警规则,形成可落地的 SLA 监控闭环。
    回答必须体现:指标命名规范、标签设计、多线程安全、容错、本地性能损耗可控,以及与国内常用 Prometheus+Grafana+Alertmanager 技术栈的对接方式。

知识点

  1. Prometheus Java Client:Counter、Gauge、Histogram 的线程安全使用,CollectorRegistry 隔离。
  2. Storm Metric API:IMetric、MetricRegistry、TopologyContext#registerMetric,如何把自定义对象暴露给 Storm 的 MetricConsumer。
  3. Push vs Pull 模型:Storm 进程一般无固定端口,需内嵌 HTTPServer(io.prometheus.client.HTTPServer)或推送到 Pushgateway;国内更倾向内嵌 HTTPServer,端口注册到 Consul/Nacos,方便 Prometheus 拉取。
  4. 标签设计:必须包含 topology_id、component_id、task_id、rule_id、cluster_name(适配多环境)。
  5. SLA 计算:命中率 = hit / total,用两个 Counter 分别累积,PromQL 做 rate() 后相除,避免 Gauge 累加带来的 race condition。
  6. 性能:指标更新必须无锁、采样频率可配置,防止高频事件打爆 HTTPServer。
  7. 国内合规:端口监听需绑定 0.0.0.0 并做 ACL,日志脱敏,避免把客户规则 ID 明文打到标签。

答案

  1. 依赖(Maven)
<dependency>
  <groupId>io.prometheus</groupId>
  <artifactId>simpleclient</artifactId>
  <version>0.16.0</version>
</dependency>
<dependency>
  <groupId>io.prometheus</groupId>
  <artifactId>simpleclient_httpserver</artifactId>
  <version>0.16.0</version>
</dependency>
  1. 指标定义(单例、线程安全)
public final class RuleHitMetrics {
    private static final RuleHitMetrics INSTANCE = new RuleHitMetrics();
    public static RuleHitMetrics get() { return INSTANCE; }

    private final Counter ruleTotal = Counter.build()
            .name("storm_rule_eval_total")
            .labelNames("topology", "component", "task", "rule")
            .help("Total rule evaluations")
            .register();
    private final Counter ruleHit = Counter.build()
            .name("storm_rule_hit_total")
            .labelNames("topology", "component", "task", "rule")
            .help("Total rule hits")
            .register();

    private RuleHitMetrics() {}

    public void incEval(String topology, String component, int task, String rule) {
        ruleTotal.labels(topology, component, String.valueOf(task), rule).inc();
    }
    public void incHit(String topology, String component, int task, String rule) {
        ruleHit.labels(topology, component, String.valueOf(task), rule).inc();
    }
}
  1. Bolt 内埋点(execute 方法)
public class RuleBolt extends BaseRichBolt {
    private String topologyId;
    private String componentId;
    private int taskId;

    @Override
    public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) {
        this.topologyId = context.getStormId();
        this.componentId = context.getThisComponentId();
        this.taskId = context.getThisTaskId();
        // 启动 Prometheus HTTP 服务器,端口用环境变量 PROM_PORT 或随机
        int port = Integer.parseInt(System.getenv().getOrDefault("PROM_PORT", "0"));
        try {
            HTTPServer server = new HTTPServer(port);
            // 注册到 Consul(略)
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void execute(Tuple tuple) {
        String ruleId = tuple.getStringByField("rule_id");
        boolean hit = doEval(tuple);
        RuleHitMetrics.get().incEval(topologyId, componentId, taskId, ruleId);
        if (hit) {
            RuleHitMetrics.get().incHit(topologyId, componentId, taskId, ruleId);
        }
        // ack
    }
}
  1. Prometheus 采集配置(prometheus.yml)
scrape_configs:
  - job_name: 'storm-rule'
    consul_sd_configs:
      - server: 'consul.example.com:8500'
        services: ['storm-rule-metrics']
    relabel_configs:
      - source_labels: ['__meta_consul_service_address']
        target_label: __address__
        regex: '([^:]+)'
        replacement: '${1}:9100'  # 实际端口由服务元数据传入
  1. SLI 与告警规则(rule.yml)
groups:
  - name: storm_rule_sla
    interval: 30s
    rules:
      - record: storm:rule_hit_rate5m
        expr: |
          sum(rate(storm_rule_hit_total[5m])) by (topology)
          /
          sum(rate(storm_rule_eval_total[5m])) by (topology)
      - alert: StormRuleSlaBreach
        expr: storm:rule_hit_rate5m < 0.999
        for: 5m
        labels:
          severity: critical
          team: risk
        annotations:
          summary: "规则命中率低于 SLA 99.9%"
          description: "topology {{ $labels.topology }} 命中率 {{ $value | humanizePercentage }}"
  1. Grafana 面板(核心 PromQL)
  • 命中率:storm:rule_hit_rate5m
  • 总量:sum(rate(storm_rule_eval_total[5m])) by (topology)

拓展思考

  1. 多租户隔离:在标签里加入 tenant_id,结合 Prometheus 的 head series 限额,防止高基数打爆 TSDB。
  2. 热升级:Bolt 指标代码通过 Storm 的 blobstore 动态下发,无需重编译拓扑。
  3. 采样降级:当 QPS>20k/s 时,在 Bolt 内做 1/100 采样,并在 Counter 上同时乘以 100,保证 SLA 曲线不失真。
  4. 链路追踪:把 rule_id 写入 OpenTelemetry Span,与 Prometheus 指标通过 Exemplar 关联,实现“指标+追踪”一体化,方便定位命中率突降的根因。