编写 Grafana Synthetic Monitoring 脚本,检测首页 TTFB 超过 500ms 告警

解读

这道题表面上是“写一段脚本”,本质上是考察候选人能否把“Nginx 作为统一流量入口”的性能指标与“国内可落地的可观测体系”打通。
在国内生产环境,Grafana 的 Synthetic Monitoring 插件(原 Worldping)常被用来做黑盒拨测,但默认只给“响应码、RTT、TLS 握手时间”等字段,TTFB(Time to First Byte)需要自行在脚本层计算并推送至 Prometheus,再由 Grafana 侧配置告警。
面试官想确认三件事:

  1. 你能否准确给出 TTFB 的定义与采集点(首字节到达时刻 – 请求开始时刻)。
  2. 你能否用最小侵入、零依赖的方式把指标推送到企业内已有的 Prometheus(push 或 pull 均可)。
  3. 你能否把阈值、标签、持续时长、恢复条件写成国内告警通道(飞书/钉钉/企业微信)能直接消费的 Grafana Alert Rule。

知识点

  1. TTFB 与 RT 的区别:TTFB 只包含“到首字节”的耗时,不含下载完整 Body 的时间,更能反映 Nginx 本身及上游的回源状况。
  2. Grafana Synthetic Monitoring 的两种实现路径:
    A. 官方插件:基于 Blackbox Exporter,只能拿到 probe_http_duration_seconds{phase=”got_first_byte”},需要二次计算。
    B. 自定义脚本:用 Node.js/Python/Shell 起定时任务,直接计算 TTFB 并 push 到 Pushgateway,再让 Prometheus 拉取。
  3. Prometheus 指标命名规范:以 nginx_homepage_ttfb_seconds 为指标名,标签至少包含:cluster、idc、job、uri,方便多环境聚合。
  4. 告警规则三要素:阈值 500ms、for 持续 2 个采集周期(默认 15s*2=30s)、labels.severity=page,annotations 中给出中文摘要与跳转链接。
  5. 零中断热升级场景:脚本必须支持在 Nginx reload(USR2+WINCH)期间重试,避免因老 worker 退出导致误报。

答案

下面给出一条可直接落地、不依赖黑盒 exporter 的“Python + Pushgateway”最小脚本,以及配套的 Grafana Alert Rule YAML。
假设:

  1. 脚本 homepage_probe.py
#!/usr/bin/env python3
import time, requests, os
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

URL = os.getenv("PROBE_URL", "https://www.example.com/")
PUSHGW = os.getenv("PUSHGW", "http://pushgateway.monitor.svc.cluster.local:9091")
JOB = "nginx_homepage_probe"

registry = CollectorRegistry()
ttfb = Gauge(
    "nginx_homepage_ttfb_seconds",
    "Time to first byte of homepage",
    labelnames=["cluster", "idc", "uri"],
    registry=registry,
)

def probe():
    start = time.perf_counter()
    try:
        resp = requests.get(URL, timeout=5, stream=True)
        _ = resp.raw.read(1)          # 只读首字节
        ttfb_val = time.perf_counter() - start
    except Exception as e:
        ttfb_val = -1                  # 失败时赋负值,便于告警区分
    return ttfb_val

if __name__ == "__main__":
    value = probe()
    ttfb.labels(cluster="prod", idc="sh-aliyun", uri=URL).set(value)
    push_to_gateway(PUSHGW, job=JOB, registry=registry)

打包成 Docker 镜像,放到 K8s CronJob,每 15s 执行一次即可。

  1. Prometheus 告警规则(可直接 kubectl apply)
groups:
- name: nginx_homepage
  interval: 15s
  rules:
  - alert: 首页TTFB超过500ms
    expr: nginx_homepage_ttfb_seconds{uri="https://www.example.com/"} > 0.5
    for: 30s
    labels:
      severity: page
      team: sre
    annotations:
      summary: "Nginx 首页 TTFB 超过 500ms"
      description: "当前值 {{ $value }}s,持续 30s,请检查 upstream 回源或 Nginx 节点负载"
  1. Grafana 侧
  • 导入 Prometheus 数据源,新建 Alert Rule 把上面 PromQL 粘进去;
  • 通知通道选“飞书群机器人”,把 annotations.description 作为卡片内容;
  • 配置恢复通知,避免“只报不消”。

拓展思考

  1. 如果公司已经在用 Blackbox Exporter,不想新增脚本,可直接用 probe_http_duration_seconds{phase=”got_first_byte”},但要把“URI 固定为首页”写成单独的 module,否则所有探测任务混在一起无法精准告警。
  2. 为了区分“网络慢”还是“Nginx 本身慢”,可以再上报一个 probe_dns_lookup_time 与 probe_tls_handshake_time,用 Recording Rule 做减法:nginx_processing = nginx_homepage_ttfb_seconds – probe_dns_lookup_time – probe_tls_handshake_time,当 nginx_processing > 200ms 时再告警,减少公网抖动误报。
  3. 灰度发布场景:Nginx 自带 split_clients 模块做流量染色,可在 header 中注入 x-canary=1,脚本再带该 header 发两次请求,分别采集 stable & canary 的 TTFB,用 Grafana 的“对比告警”功能,若 canary 比 stable 高出 20% 直接阻断发布。
  4. 高并发压测期:TTFB 会随并发度非线性上涨,可引入“当前 QPS”作为外部标签,用 PromQL 的 nginx_homepage_ttfb_seconds > on() (0.0005 * nginx_qps_current) 做动态阈值,避免“固定 500ms”在压测场景下频繁轰炸告警通道。