如何为 SQL 查询耗时添加 Histogram?
解读
在国内高并发、高可用场景下,面试官问“怎么给 SQL 查询耗时加 Histogram”,并不是想听“装个 Prometheus 就行”,而是想看候选人能否把“观测性”做成产品级闭环:
- 指标语义正确(Histogram 而非 Summary),方便后续按标签做 P95、P99 计算;
- 对 FastAPI 异步生态友好,不能阻塞事件循环;
- 代码侵入性低,可灰度、可回滚;
- 能区分 主库/从库、业务模块、慢查询阈值,方便 SRE 统一告警。
回答时要体现“Python 类型提示 + 异步 + 中间件/代理层”三板斧,并给出可落地的代码片段。
知识点
- Prometheus Histogram 四要素:name、labels、buckets、exemplar(可选)。
- FastAPI 中间件与 BackgroundTask 的异步生命周期。
- SQLAlchemy 1.4+ 事件系统(
before_cursor_execute/after_cursor_execute),支持异步引擎。 time.perf_counter在异步上下文里的高精度耗时计算。prometheus_client的Histogram是线程安全但不是协程安全,需用aioprometheus或prometheus-client的regCollector+fastapi自定义路由/metrics解决并发写。- 国内云原生场景:Histogram 必须带
cluster、idc、env标签,方便多环境聚合。 - 慢查询阈值可配置化,结合 SLS/CLS 日志告警,形成“指标+日志+追踪”三位一体。
答案
步骤一:定义指标
from aioprometheus import Histogram
sql_duration = Histogram(
'sql_query_duration_seconds',
'SQL 执行耗时(含网络)',
{'buckets': (.005, .01, .025, .05, .075, .1, .25, .5, .75, 1.0, 2.5, 5.0, 7.5, 10.0),
'labels': {'endpoint', 'method', 'table', 'sql_type', 'is_slow'}}
)
步骤二:SQLAlchemy 异步事件钩子
from sqlalchemy import event
from sqlalchemy.ext.asyncio import AsyncEngine
import time
def install_timer(engine: AsyncEngine):
@event.listens_for(engine.sync_engine, "before_cursor_execute")
def before(*args):
args[-1]._start = time.perf_counter()
@event.listens_for(engine.sync_engine, "after_cursor_execute")
def after(conn, cursor, statement, parameters, context, executemany):
cost = time.perf_counter() - getattr(context, '_start', 0)
table = _extract_table(statement)
sql_type = statement.split()[0].upper()
is_slow = 'true' if cost > 0.1 else 'false'
# 在协程外写指标,需保证线程安全
sql_duration.labels(
endpoint='', method='', table=table,
sql_type=sql_type, is_slow=is_slow
).observe(cost)
步骤三:FastAPI 中间件补充 endpoint & method
@app.middleware("http")
async def add_endpoint_label(request: Request, call_next):
response = await call_next(request)
# 把 endpoint 和 method 注入上下文,供 after_cursor_execute 读取
request.state.endpoint = f"{request.method}:{request.url.path}"
return response
在 after 回调里通过 context.connection.info 把 request.state 传进去即可补全标签。
步骤四:暴露 /metrics
from aioprometheus import render
@app.get("/metrics")
async def metrics():
return Response(content=render(sql_duration.registry), media_type="text/plain")
完成以上四步后,Prometheus 即可按 sql_query_duration_seconds 做 P99 告警,也能在 Grafana 里按 is_slow="true" 直接下钻到具体慢 SQL。
拓展思考
- 多租户场景:把
tenant_id作为标签是否会造成高基数?国内常规做法是“标签值枚举 ≤ 100”,超限后转 Exemplar 或日志追踪。 - 连接池级联故障:Histogram 只能看耗时,不能看排队时间,可再引入
sql_queue_time_secondsHistogram,通过before_checkout/after_checkout事件实现。 - 灰度降级:利用 FastAPI 的
Depends把histogram_enabled做成动态配置,紧急情况下直接关闭指标收集,避免观测自身成为性能瓶颈。 - 合规审计:国内金融项目要求“谁、何时、查了哪张表”,可把 Histogram 的 Exemplar 与 OpenTelemetry TraceID 绑定,再推送到蓝鲸或阿里云 SLS,实现一键溯源。