如何基于 TraceQL 定位慢 SQL 超过 500ms 的链路
解读
在国内云原生与微服务落地场景中,TraceQL 是 Grafana Tempo 2.0+ 推出的类 SQL 分布式追踪查询语言,用于从海量 trace 数据中快速筛选瓶颈。面试官问“定位慢 SQL 超过 500ms 的链路”,核心考察三点:
- 是否理解 TraceQL 语法与执行模型;
- 能否把“慢 SQL”抽象为 span 属性过滤条件;
- 能否结合 Linux 内核视角(cgroup、CPU throttle、iowait)解释慢根因,而不仅是把 SQL 甩给 DBA。
回答必须体现“先定位、再下钻、后验证”的闭环,并给出可落地的命令行与配置片段,否则会被认为“纸上谈兵”。
知识点
- TraceQL 基础语法:{ .http.status_code=500 }、{ span.db.statement =~ "(?i)select.*" }、duration > 500ms。
- span 语义规范:db.type、db.statement、db.operation、peer.service、span.kind=client。
- Grafana Tempo 与 OpenTelemetry Collector 的 pipeline:receiver → processor(attributes/spanmetrics) → exporter → Tempo。
- Linux 侧慢 SQL 常见根因:
- CPU throttle:cgroup cpu.stat.nr_throttled 突增;
- iowait:pidstat -d 1 观察 await;
- 内存回收:sar -B 看 pgscand/s;
- 网络 RTT:ss -itp 看 rtt。
- 关联手段:trace-id 写入 Nginx 日志 X-Trace-Id,再通过 Loki LogQL {app="nginx"} |= “traceID” 联动。
答案
步骤一:在 Grafana Explore 选择 Tempo 数据源,输入 TraceQL
{ span.db.statement =~ ".*" && duration > 500ms }
→ 返回所有耗时超过 500ms 且包含 SQL 语句的 span。
步骤二:若业务系统未规范埋点,需在 OpenTelemetry Collector 的 processor 里强制注入属性:
processors:
attributes:
actions:
- key: db.statement
from_attribute: db.query
action: upsert
- key: db.type
value: mysql
action: insert
确保后续 TraceQL 可用 db.type="mysql" 进一步过滤。
步骤三:对结果列表按最大耗时排序,点击 trace-id 进入瀑布图,定位耗时最长的 span,记录其
span.kind=client && db.statement 与 peer.service=order-mysql。
步骤四:下钻到 Linux 宿主机,以 peer.service 的 Pod 名为 order-mysql-xxx,执行
kubectl exec -it order-mysql-xxx — bash
mysql -e "SELECT * FROM performance_schema.events_statements_summary_by_digest
WHERE AVG_TIMER_WAIT/1e12 > 0.5 ORDER BY SUM_TIMER_WAIT DESC LIMIT 1\G"
拿到 digest_text 与 execution_count,确认与 TraceQL 里的 db.statement 匹配。
步骤五:再回到客户端 Pod(trace 中上游 span),检查当时资源约束:
- cat /sys/fs/cgroup/cpu/cpu.stat | grep nr_throttled
若 5s 内突增 >100,说明 CPU 限流导致 SQL 发送慢; - pidstat -d 1 5 | grep mysqld
若 await>30ms,%util>80,则磁盘瓶颈; - sar -n TCP,ETCP 1 5
若 retrans/s>5,则网络丢包重传。
步骤六:把以上指标与 trace 时间戳对齐,在 Grafana 同一张 dashboard 叠加 Tempo trace、Pod CPU throttled rate、MySQL io await,形成“证据链”。
步骤七:根因明确后,给出修复动作:
- CPU throttle → 调大 cgroup quota 或提高 Pod limit;
- io wait → 换 SSD 或调整 innodb_io_capacity;
- 网络重传 → 调大 net.core.wmem_max 或启用 RDMA。
复测:发布补丁后,再次执行 TraceQL
{ span.db.statement =~ "相同SQL" && duration > 500ms }
若 30 分钟内无结果,则闭环完成。
拓展思考
-
采样率冲突:国内为了节省成本,常把 Head-based 采样率调到 1/100,导致慢 SQL 被丢弃。可改为 Tail-based 采样,在 Collector 配置
tail_sampling:
policies:
- name: slow-sql
type: latency
latency: {threshold_ms: 500, upper_threshold_ms: 0}
保证大于 500ms 的 trace 必采。 -
Code-Level 自动注入:在 Go 项目里用 sqlcommenter,把 trace-id 作为 /trace_id=xxx/ 注释打进 SQL,方便 DBA 慢日志直接关联调用链。
-
eBPF 无侵入补充:若应用未埋点,可用 pixie 或 deepflow 的 eBPF 探针,自动解析 MySQL 协议,生成 span,再通过 TraceQL 统一查询,实现“0 代码改造”治理慢 SQL。