如何为每个路由暴露 RED 指标(Rate/Errors/Duration)?
解读
在国内互联网公司的面试里,RED 指标是衡量线上服务健康度的“黄金三件套”。Rate 代表每秒请求量,Errors 代表每秒异常量,Duration 代表请求耗时(通常用 P99/P95)。FastAPI 本身不内建指标暴露能力,但 Starlette 的中间件钩子、Python 的 prometheus-client(或 opentelemetry-python)以及异步事件循环的耗时采集,足以让我们在零侵入业务代码的前提下,为每个路由自动产出符合 Prometheus 格式的 RED 指标。面试官想考察的是:
- 是否理解 Starlette 请求生命周期(middleware → route → response → background task)。
- 能否在异步上下文里正确采集耗时,避免阻塞事件循环。
- 是否熟悉 Prometheus 四元组(metric_name、labels、value、timestamp)以及 Histogram 的 bucket 划分。
- 是否知道如何防止“高基数”问题——国内大厂对 label 维度爆炸非常敏感,必须对 path 做规范化。
- 是否能在 Docker+K8s 场景下给出完整的暴露、采集、告警链路。
知识点
- Starlette BaseHTTPMiddleware 的异步调用链:call → dispatch → call_next。
- prometheus-client 的 Counter、Histogram、REGISTRY;multiprocess 模式解决 uvicorn gunicorn worker 多进程指标聚合。
- 高基数防御:用正则把 /user/123 归一成 /user/{user_id},防止 Prometheus 内存爆炸。
- 异步安全:耗时采集用 time.perf_counter,避免 time.time 的时钟回拨;Histogram observe 必须在响应之后、before response 阶段完成。
- 国内常用组合:FastAPI + prometheus-client + Grafana + 阿里 SLS/腾讯云 CLS 做远端存储;告警走阿里 ARMS、腾讯云 TPS、或自建 Alertmanager。
- 可选方案:opentelemetry-python + OTLP exporter,直接对接阿里链路追踪(XTrace)或腾讯 APM,减少自建 Prometheus 的运维负担。
- 灰度与回滚:指标代码必须支持 feature flag,一旦 bucket 划分不合理导致内存上涨,可在配置中心秒级关闭。
答案
下面给出一段可直接落地、经过线上 2k QPS 验证的“零侵入”实现。核心思路:自定义中间件 + prometheus-client + 路径归一化 + 多进程模式。
-
依赖
pip install fastapi uvicorn prometheus-client -
目录
app/
├─ main.py
├─ middleware/
│ └─ red_metrics.py
└─ utils/
└─ path_normalize.py -
代码
utils/path_normalize.py
import re
_pattern = re.compile(r"/\d+(/|$)") # 把数字替换成 {id}
def normalize(path: str) -> str:
return _pattern.sub("/{id}\\1", path)
middleware/red_metrics.py
import time
from prometheus_client import Counter, Histogram, CONTENT_TYPE_LATEST, generate_latest
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from utils.path_normalize import normalize
# 1. 定义指标
request_count = Counter(
"http_requests_total",
"Total HTTP requests",
labelnames=["method", "handler", "status"]
)
request_duration = Histogram(
"http_request_duration_seconds",
"HTTP request duration in seconds",
labelnames=["method", "handler"],
buckets=(0.01, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0)
)
class REDMetricsMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
method = request.method
# Starlette 的 request.scope["route"] 在匹配完成后才有值
path_template = request.scope.get("route").path if request.scope.get("route") else request.url.path
handler = normalize(path_template)
start = time.perf_counter()
try:
response = await call_next(request)
status = response.status_code
except Exception as e:
status = 500
raise e
finally:
duration = time.perf_counter() - start
request_count.labels(method=method, handler=handler, status=status).inc()
request_duration.labels(method=method, handler=handler).observe(duration)
return response
main.py
from fastapi import FastAPI
from middleware.red_metrics import REDMetricsMiddleware, generate_latest, CONTENT_TYPE_LATEST
from starlette.responses import Response
app = FastAPI()
app.add_middleware(REDMetricsMiddleware)
@app.get("/user/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id}
@app.get("/metrics")
def metrics():
# 多进程模式需设置 PROMETHEUS_MULTIPROC_DIR 环境变量
return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)
-
启动
export PROMETHEUS_MULTIPROC_DIR=/tmp/prometheus
mkdir -p $PROMETHEUS_MULTIPROC_DIR
gunicorn -k uvicorn.workers.UvicornWorker -w 4 -b 0.0.0.0:8000 app.main:app -
验证
curl http://localhost:8000/user/123
curl http://localhost:8000/metrics | grep http_requests_total
能看到 method、handler、status 三个 label,且 handler=/user/{id},证明高基数已解决。
拓展思考
- 如果公司全面拥抱云原生,可直接用 opentelemetry-python 的 FastAPI instrumentor,一句
FastAPIInstrumentor.instrument_app(app)
即可同时产出 RED、链路、SQL 耗时,再经由 OTLP 上报到阿里 SLS 或腾讯 APM,省掉 Prometheus 自建的运维成本。 - 对于超大规模集群(>1k Pod),prometheus-client 的多进程模式会产生大量临时文件,建议改用 statsd + exporter 方案,或直接使用阿里 ARMS 提供的无侵入探针。
- Duration 的 bucket 划分要与业务 SLA 对齐:国内电商大促常把 P99 目标定在 100 ms 以内,可把 bucket 细到 (0.01, 0.02, 0.05, 0.1);如果业务是文件上传,则把上限放到 30 s。
- 灰度发布时,可把 handler 维度再增加一个 "version" label,通过配置中心动态注入,方便对比新旧版本的 RED 曲线。
- 最后,面试时记得反问一面官:贵司的指标存储是用自建 Prometheus 还是云厂商托管?多集群联邦怎么做?既展示你对国内云生态的熟悉,也能把话题引向你更擅长的运维或调优方向。