指标与 Prometheus · 第 8 / 14 章
8埋点实战:给应用加上 RED 指标
这一章把前面所有概念落成代码。目标很具体:给一个 HTTP 服务加上 QPS、错误率、P95/P99、队列深度、依赖耗时五组指标, 并且保证这些指标的标签基数有上限。埋点写错的地方通常不在语法, 而在标签的取值集合没有边界。
8.1 先写指标字典,再写代码
下面这张表就是「指标字典」:每一行在代码里对应一个指标对象, 在评审时对应一个问题「它的标签最多几个取值」。
| 指标名 | 类型 | 标签(取值上限) | 用途 / 对应告警 |
|---|---|---|---|
http_requests_total | counter | route(20) method(5) status(15) | QPS 与错误率;无流量告警 |
http_request_duration_seconds | histogram | route(20) method(5) status(15) | P95 / P99;延迟告警 |
http_inflight_requests | gauge | route(20) | 并发度,配合饱和度判断 |
dependency_request_duration_seconds | histogram | dep(6) op(10) result(3) | 依赖耗时;依赖慢告警 |
worker_queue_depth | gauge | queue(3) | 队列深度;饱和度告警 |
worker_queue_oldest_seconds | gauge | queue(3) | 最老任务的等待时长(真饱和度信号) |
order_created_total | counter | channel(4) result(3) | 业务指标:下单成功数 |
build_info | gauge(恒为 1) | version(∞ 但每次发布只变一个值) | 关联发布与指标变化 |
命名规则:<命名空间>_<子系统>_<名称>_<单位>,
单位一律用基本单位(seconds 而不是 ms,bytes 而不是 KB),
counter 以 _total 结尾。直方图不要自己加 _seconds_bucket 后缀,
客户端库会自动展开。
8.2 中间件:一次搞定 QPS、错误率和耗时
Go 版本(github.com/prometheus/client_golang),关键点是
route 取自路由模板而不是原始 URL,以及 status 在响应写出后才能拿到:
package middleware
import (
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var (
httpRequests = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "HTTP 请求总数",
}, []string{"route", "method", "status"})
httpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP 请求耗时",
Buckets: []float64{0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 10},
}, []string{"route", "method", "status"})
inflight = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "http_inflight_requests",
Help: "正在处理的请求数",
}, []string{"route"})
)
// statusRecorder 用来在 WriteHeader 时捕获状态码
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
// routeOf 从请求里取出路由模板。
// 用 gin / chi / echo 时都有现成方法(c.FullPath() / chi.RouteContext(r.Context()).RoutePattern())。
// 取不到时必须落到固定值,绝不能用 r.URL.Path。
func routeOf(r *http.Request) string {
if p := r.Context().Value(routeKey{}); p != nil {
return p.(string)
}
return "unmatched"
}
func Metrics(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := routeOf(r)
inflight.WithLabelValues(route).Inc()
defer inflight.WithLabelValues(route).Dec()
rec := &statusRecorder{ResponseWriter: w, status: 200}
start := time.Now()
next.ServeHTTP(rec, r)
elapsed := time.Since(start).Seconds()
status := strconv.Itoa(rec.status)
httpRequests.WithLabelValues(route, r.Method, status).Inc()
httpDuration.WithLabelValues(route, r.Method, status).Observe(elapsed)
})
}
几个容易写错的地方:
- 没有
statusRecorder就永远只能记 200。Go 的http.ResponseWriter不暴露已写出的状态码,必须自己包一层; 忘写WriteHeader的转发会导致status恒为 200,错误率永远显示 0%。 inflight要用defer减,否则发生 panic 时这个 gauge 会一直涨, 而且重启前不会回落——它看起来就像一次永不结束的流量高峰。- 热路径上优先用
With(labelValues...)缓存而不是每次WithLabelValues。后者每次都要做一次 map 查找与哈希, 在 5000 QPS 下是可见的开销。写法是把它放进一个 map 或直接用prometheus.CounterVec的MustCurryWith。 /metrics要单独一个端口(比如 9464),不要和业务端口共用, 也不要经过鉴权、限流、日志中间件——否则监控抓取会污染业务日志,还可能被公网扫到。
8.3 业务与依赖指标:资源全绿时唯一能救命的信号
依赖耗时的埋法要点是标签用枚举:dep="mysql"、dep="redis"、
dep="payment-gateway",而不是把 URL 打进去。
调用点建议放在统一的 HTTP / DB 客户端封装里,而不是散落在业务代码。
var depDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "dependency_request_duration_seconds",
Help: "对外依赖调用耗时",
Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 3},
}, []string{"dep", "op", "result"})
func ObserveDep(dep, op string, start time.Time, err error) {
result := "ok"
switch {
case err == nil:
case errors.Is(err, context.DeadlineExceeded):
result = "timeout"
case errors.Is(err, context.Canceled):
result = "canceled"
default:
result = "error"
}
depDuration.WithLabelValues(dep, op, result).Observe(time.Since(start).Seconds())
}
队列深度要打两个指标,这一点经常被忽略:
worker_queue_depth:当前等待中的任务数。它会被限流掩盖—— 如果上游限流了,队列深度可能一直很健康。worker_queue_oldest_seconds:最老的那个任务已经等了多久。 这才是真正的饱和度信号:深度 50 但最老任务等了 0.2 秒,说明消费很快; 深度 50 而最老任务等了 40 秒,说明消费已经停了。告警应该建在第二个指标上。
业务指标至少要有三个:入口请求量、核心业务动作的成功数(order_created_total)、
以及一致性校验(比如「已支付但未发货」的订单数,用 gauge 暴露)。
资源指标全绿而业务指标归零,是最难查的一类故障,见第 11 章。
8.4 高基数防御:三道卡口
- 代码卡口:任何
WithLabelValues(变量)在评审时都要能回答 「这个变量的取值集合有多大、上限是多少」。答不上来就说明它该进日志而不是指标。 - 路由归一化:优先用框架的路由模板;取不到就落到固定值
unmatched,绝不用r.URL.Path。注意 404 请求的路由模板通常是空的, 所以unmatched这一档本身也要在字典里登记(它的基数永远是 1)。 - 采集侧兜底:用
metric_relabel_configs把已经失控的指标整体丢掉, 并给每个 job 配sample_limit。这是在代码来不及改时的止血手段。
metric_relabel_configs:
# 整体丢弃某个高基数指标(比改代码快得多,但会永久丢失这个指标)
- source_labels: [__name__]
regex: http_request_uri_total|trace_detail_seconds.*
action: drop
# 只丢掉某个罪魁标签,保留指标本身
- regex: user_id|request_id|session_id
action: labeldrop
r.URL.Path 当 route,3 小时涨到 120 万条序列
一个订单查询接口的埋点写成了 WithLabelValues(r.URL.Path, ...)。
上线后第一个小时一切正常,因为压测流量集中在少数几个订单 ID 上。
- 09:10 上线,
prometheus_tsdb_head_series= 31 万。 - 10:00 真实流量上来,路径里全是真实订单号
(
/api/v1/orders/9f2b8c1d-...),序列数涨到 58 万。 - 11:30 涨到 86 万,
scrape_series_added{job="orders"}稳定在每分钟新增 4000 条以上。 - 12:20 涨到 120 万,Prometheus 抓取耗时从 0.09s 涨到 3.4s,多个看板查询超时。
发现方式:count(count by (route) (http_requests_total)) 返回 47 万,
正常应该在 20 上下。修复:改用路由模板 /api/v1/orders/{id},
再加一条采集侧的 labeldrop 做兜底。
关键是这个事故不会触发任何错误告警——错误率、延迟、QPS 全都正常,
唯一的信号是序列数曲线的斜率。所以基数斜率必须单独配一条告警。
python3 -m pip install prometheus_client
import random, threading, time
from prometheus_client import Counter, Gauge, Histogram, start_http_server
REQ = Counter("http_requests_total", "HTTP 请求总数", ["route", "method", "status"])
LAT = Histogram(
"http_request_duration_seconds", "HTTP 请求耗时", ["route"],
buckets=[0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 10],
)
DEP = Histogram(
"dependency_request_duration_seconds", "依赖调用耗时", ["dep", "result"],
buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 3],
)
QUEUE = Gauge("worker_queue_depth", "等待中的任务数", ["queue"])
HTTP_BUCKETS = LAT # 仅用于对齐命名
depth = 0
def simulate_requests():
while True:
route = random.choice(["/api/v1/orders", "/api/v1/orders/{id}", "/api/v1/pay"])
slow = random.random() < 0.01 # 1% 的慢请求
dep = random.choice(["mysql", "redis", "payment"])
DEP.labels(dep, "error" if slow else "ok").observe(random.expovariate(1 / (1.5 if slow else 0.03)))
time.sleep(random.expovariate(1 / 0.03))
status = "500" if random.random() < 0.01 else "200"
LAT.labels(route).observe(random.expovariate(1 / (0.8 if slow else 0.05)))
REQ.labels(route, "GET", status).inc()
def simulate_queue():
global depth
while True:
depth = max(0, depth + random.randint(-6, 7))
QUEUE.labels("order-worker").set(depth)
time.sleep(1)
start_http_server(9464)
threading.Thread(target=simulate_queue, daemon=True).start()
threading.Thread(target=simulate_requests, daemon=True).start()
while True:
time.sleep(3600)
python3 demo_metrics.py &
sleep 5
curl -s localhost:9464/metrics | grep -E '^http_requests_total|^http_request_duration_seconds_count' | head
curl -s localhost:9464/metrics | grep '^http_request_duration_seconds_bucket' | head -4
预期输出:能看到 http_requests_total{method="GET",route="/api/v1/orders",status="200"} 47.0
这样的行,以及从 le="0.01" 开始的桶序列。
如果桶里没有 le="+Inf",说明你手写的文本格式有问题——
用客户端库时它一定会有。接着把第 7 章的 prometheus.yml 里加一个 job
指向 host.docker.internal:9464,就能在 Prometheus 里跑出完整的 RED 查询。
有一种常见反模式:为了让 gauge 不「过期」,在每次请求里都给它 Set() 一次当前值。
这会让 gauge 的含义退化成「最近一次请求时的值」,并且在高 QPS 下产生大量无意义的写入。
gauge 应该由专门的后台协程按固定周期(1–15 秒)采集,而不是被业务请求驱动。
监控数据的时间语义要和业务事件解耦,否则「刚刚有没有请求」会污染「队列有多长」这个事实。