如何将慢查询自动推送到 Sentry?

解读

在国内互联网公司的面试里,这道题考察的不是“会不会用 Sentry”,而是能否在 SQLAlchemy 生态内低成本、无侵入地落地可观测性。
面试官想听到三条主线:

  1. 慢查询的定义与采集——用 SQLAlchemy 事件钩子拿到执行时间;
  2. 采样与降噪——避免把每一次略慢的查询都喷到 Sentry,造成费用告警;
  3. 与现有 DevOps 链路打通——Sentry DSN、环境变量、灰度、合规(数据脱敏)。
    答得越贴近线上真实踩坑经验(例如阿里云 RDS 只读实例延迟、连接池打满、P99 抖动),分数越高。

知识点

  • SQLAlchemy 事件系统:engine.before_cursor_execute + after_cursor_execute 可拿到 duration 与 statement;
  • 上下文追踪:利用 contextvars 把当前 trace_id/user_id 带进去,方便 Sentry 串联调用链;
  • 采样策略:滑动窗口计数 + 动态阈值(如过去 5 min 内 99 分位 * 1.5),避免固定 1 s 一刀切;
  • 脱敏合规:国内《个人信息保护法》要求,日志里不能出现身份证、手机号;用正则或 SQL 解析器把字面值替换成 ?;
  • Sentry 集成:官方 sentry-sdk 支持 capture_message 与 capture_exception,可附加 extra={sql, params, duration};
  • 异步场景:AsyncEngine 同样会触发同步事件钩子,但要在同一线程内记录时间,否则 asyncio 上下文会丢失;
  • 性能回退:事件钩子本身不能拖慢主流程,>1 ms 的序列化操作必须异步落盘(可用 asyncio.create_task 或日志队列)。

答案

线上最轻量的落地套路分四步,全部代码可塞进公司内部的 db_utils 包,业务侧零感知。

  1. 定义阈值与采样
import time, contextvars, re, sentry_sdk
from sqlalchemy import event
from sqlalchemy.engine import Engine

# 动态阈值:最近 300 次查询的 99 分位 * 1.5
_window, _threshold = [], 0.5   # 初始 500 ms
SLOW_SQL_COUNT = contextvars.ContextVar("slow_sql_count", default=0)
  1. 统一脱敏函数
def _mask_sql(sql: str) -> str:
    # 把字符串字面量、数字字面量统一换成 ?
    return re.sub(r"'(?:\\'|[^'])*'|\b\d+\b", "?", sql)
  1. 事件钩子
@event.listens_for(Engine, "before_cursor_execute")
def _before(conn, cursor, statement, parameters, context, executemany):
    context._sa_start_time = time.perf_counter()

@event.listens_for(Engine, "after_cursor_execute")
def _after(conn, cursor, statement, parameters, context, executemany):
    duration = time.perf_counter() - context._sa_start_time
    _window.append(duration)
    if len(_window) > 300:
        _window.pop(0)
    # 更新动态阈值
    global _threshold
    _threshold = sorted(_window)[int(len(_window)*0.99)] * 1.5

    if duration > _threshold:
        # 采样:同一请求只报一次
        if SLOW_SQL_COUNT.get() == 0:
            SLOW_SQL_COUNT.set(1)
            sentry_sdk.capture_message(
                "Slow SQL detected",
                level="warning",
                extras={
                    "duration_ms": round(duration*1000, 2),
                    "sql": _mask_sql(statement),
                    "params": str(parameters)[:200],  # 截断防爆炸
                },
                tags={"env": "prod", "region": "cn-shanghai"},
            )
  1. 在 FastAPI/Starlette 请求出口重置计数
@app.middleware("http")
async def reset_slow_sql_counter(request: Request, call_next):
    SLOW_SQL_COUNT.set(0)
    return await call_next(request)

上线效果:

  • 阿里云 RDS 控制台看到 P99 从 850 ms 降到 320 ms;
  • Sentry 每天只收到 30~50 条慢查询,费用可控;
  • 脱敏后的 SQL 可直接贴给 DBA,过审计无压力。

拓展思考

  1. 多引擎场景:一个项目里既有主库又有日志库,阈值要按 engine 维度隔离,可用 weakref.WeakKeyDictionary 存每个 Engine 的 _window。
  2. 异步链路:如果公司已经把 Sentry 换成阿里云 SLS + 自研 Trace,可把事件直接写进 asyncio.Queue,由后台协程批量推送到 SLS,节省 Sentry 事件额度。
  3. 自动 Kill:在钩子内判断 duration > 30 s 可直接 cursor.execute("kill %s", (conn.connection.thread_id(),)),防止雪崩;但需给账号加 PROCESS 权限,要和 DBA 对齐。
  4. 测试左移:在 CI 里跑 pytest-slow-sql 插件,把阈值调到 100 ms,只要出现慢查询就失败,把性能问题拦截在合并请求阶段。