在 service 层实现“业务指标”自定义埋点,并展示如何与 Prometheus 的 native histogram 对接

解读

国内面试官问这道题,核心想验证三件事:

  1. 你是否真的在 service 层写代码,而不是把指标埋点全扔给中间件;
  2. 你是否理解 Prometheus native histogram(v2.40+ 支持的稀疏桶)相比传统 histogram 的优势——桶数固定、客户端计算分位数、服务端无需 recording rule 即可做 heatmap;
  3. 你是否能把 Go-kit 的“业务逻辑零依赖”哲学落地:指标代码可插拔、单测可 mock、不污染核心业务函数。

一句话:让候选人“徒手”在 service 里写一段可灰度、可热升级、符合国内可观测规范(兼容阿里云 SLS、腾讯云 TMP、自建 VictoriaMetrics)的 native histogram 埋点,并解释为什么选它而不是 summary 或传统 histogram。

知识点

  1. Prometheus native histogram 的稀疏桶、零热图误差、客户端直方图合并特性;
  2. Go-kit service 层编码约定:接口隔离、依赖倒置、业务包不直接 import prometheus;
  3. kit 中间件(ServiceMiddleware)链式组装,指标中间件对业务透明;
  4. prometheus/client_golang v1.19+ 的 prometheus.HistogramOpts.NativeHistogramBucketFactor 等字段;
  5. 国内常用标签规范:{app_id,cluster,zone,method,status,biz_line},避免高基数;
  6. 单测技巧:用 prometheus.NewPedanticRegistry() 断言指标输出,用 httptest 模拟并发;
  7. 灰度发布:通过 feature flag 动态切换 histogram 桶因子,避免重启。

答案

下面给出一套可直接跑进面试官笔记本的“最小可运行”代码,分三步:定义业务指标、写 service 实现、写 kit 中间件对接 Prometheus native histogram。

步骤 1:定义业务指标(放在 internal/metrics 包,业务层只依赖接口)

package metrics

import "github.com/prometheus/client_golang/prometheus"

// BizMetrics 业务指标接口,service 层只依赖它,方便单测 mock
type BizMetrics interface {
    ObserveOrderAmount(city string, amount float64)
}

// Prometheus 实现
type promMetrics struct {
    orderAmount prometheus.Histogram
}

// NewPrometheusBizMetrics 构造函数,返回接口
func NewPrometheusBizMetrics(reg prometheus.Registerer) BizMetrics {
    h := prometheus.NewHistogram(prometheus.HistogramOpts{
        Name: "biz_order_amount_native",
        Help: "订单金额分布(native histogram)",
        // 0.5 的桶因子,1.2 倍增长,覆盖 1 分到 10 万
        NativeHistogramBucketFactor:     1.2,
        NativeHistogramMaxBucketNumber:  160,
        NativeHistogramMinResetDuration: 0, // 不自动 reset
        ConstLabels: prometheus.Labels{
            "app_id":  "order",
            "cluster": os.Getenv("CLUSTER"),
        },
    })
    reg.MustRegister(h)
    return &promMetrics{orderAmount: h}
}

func (p *promMetrics) ObserveOrderAmount(city string, amount float64) {
    p.orderAmount.With(prometheus.Labels{"city": city}).Observe(amount)
}

步骤 2:service 层代码(internal/service/order.go)

package service

import "demo/internal/metrics"

type OrderService interface {
    Create(uid, city string, amount float64) (orderID string, err error)
}

type orderSvc struct {
    metrics metrics.BizMetrics
}

func NewOrderSvc(m metrics.BizMetrics) OrderService {
    return &orderSvc{metrics: m}
}

func (s *orderSvc) Create(uid, city string, amount float64) (string, error) {
    // 核心业务逻辑
    orderID := uuid.NewString()
    // 自定义埋点:只在 service 层写一行
    s.metrics.ObserveOrderAmount(city, amount)
    return orderID, nil
}

步骤 3:main 里组装 kit 中间件(cmd/order/main.go)

package main

import (
    "demo/internal/metrics"
    "demo/internal/service"
    "github.com/go-kit/kit/endpoint"
    kithttp "github.com/go-kit/kit/transport/http"
    "github.com/prometheus/client_golang/prometheus/promhttp"
    "net/http"
)

func main() {
    reg := prometheus.NewRegistry()
    bizM := metrics.NewPrometheusBizMetrics(reg)

    svc := service.NewOrderSvc(bizM)

    // 可选:再加 kit 日志、熔断、限流中间件
    var ep endpoint.Endpoint
    ep = makeCreateEndpoint(svc)
    // 这里不再包指标中间件,因为业务指标已在 service 层埋好

    r := http.NewServeMux()
    r.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{
        EnableOpenMetrics: true,
    }))
    r.Handle("/create", kithttp.NewServer(ep, decodeRequest, encodeResponse))

    http.ListenAndServe(":8080", r)
}

运行后,访问 /metrics 即可看到:

# HELP biz_order_amount_native 订单金额分布(native histogram)
# TYPE biz_order_amount_native histogram
biz_order_amount_native{city="shanghai",app_id="order",cluster="hz1",le="1.0"} 3
biz_order_amount_native{city="shanghai",app_id="order",cluster="hz1",le="1.2"} 7
...

Grafana 侧直接选 “Heatmap” 面板,无需 recording rule 即可画出 99 分位热图。

拓展思考

  1. 高基数城市码怎么办?
    国内常见做法是在 service 层做“城市等级”映射(一线/二线/三线),把标签从 city 换成 city_tier,桶数立刻从 400+ 降到 3,避免 Prometheus 内存爆炸。

  2. 如何支持灰度变更桶因子?
    把 NativeHistogramBucketFactor 放到配置中心(Nacos/Apollo),kit 启动时注入,再配合热更新 goroutine 调用 prometheus.Registry.Unregister+Register,可实现秒级调整而无需滚动发布。

  3. 与 tracing 联动?
    在 service 层埋点处把 trace_id 作为 exemplar 塞进 histogram:

    h.(prometheus.ExemplarObserver).ObserveWithExemplar(amount, prometheus.Labels{"trace_id": span.SpanContext().TraceID().String()})
    

    这样 VictoriaMetrics 或阿里云 TMP 都能在 heatmap 下钻到具体慢请求。

  4. 单测如何断言?
    用 prometheus/testutil.GatherAndCompare 直接比对期望的桶序列,确保不同 amount 落在正确稀疏桶,避免“肉眼”数指标。

  5. 为什么不用 summary?
    summary 的 φ 分位在客户端计算,无法聚合多实例;native histogram 服务端可任意聚合,且桶稀疏,适合国内大规模集群。