用 TSVB 实现“95 分位响应时间”并叠加“周同比”曲线,写出完整 JSON 导出

解读

  1. 场景定位:国内一线/准一线互联网公司在面试 SRE、可观测性、日志平台方向时,常把「TSVB 高阶用法」作为分水岭题。
  2. 考点拆分:
    • 能否在 0 代码的前提下用 TSVB 完成「Percentile 95」聚合;
    • 能否利用「Series Agg + Offset」在单图内完成「本周 vs 上周」的同比;
    • 能否正确设置时间范围、间隔、索引模式、字段映射,保证线上大索引也能秒级返回;
    • 能否导出可移植的 JSON(包括 Kibana 7.x/8.x 的 schema),方便面试官一键导入验证。
  3. 易踩坑:
    • 直接选 “Percentiles” 后忘记把 “Percentile 95” 填进去,导致默认返回 1/5/25/50/75/95/99 全量,拖慢渲染;
    • Offset 用 “-1w” 后,时间范围仍选 “Last 7 days”,结果上周曲线只剩 1 天数据;
    • 忘记关闭 “Drop last bucket”,导致最右侧空点把同比线拉成 0;
    • JSON 里带了绝对索引名 “log-2024.05.10”,面试官导入后索引找不到,直接 0 分。

知识点

  • TSVB = Time Series Visual Builder,Kibana 原生可视化,基于 Elasticsearch 聚合,支持 Pipeline、Math、Series Agg;
  • Percentile 95:对响应时间长尾敏感,比平均值更能反映用户真实体验;
  • Offset:在 “Options” 面板填写 “-1w” 即可把整条时间轴平移一周,实现同比;
  • Series Agg:如果要把「本周 P95」与「上周 P95」做 Ratio,可再加一条 “Series Agg” 选 “Overall Max” 后接 “Math” 做 (current - offset) / offset;
  • Export:Kibana 8.x 的 TSVB 已并入 “Lens” 底层,但可视化对象仍存为 “type: visualization” + “visState: { type: metrics … }”;通过 “Stack Management → Saved Objects → Export” 可生成 NDJSON,也可手工拼装 POST /api/saved_objects/_export;
  • 兼容性:7.10 之后 visState 结构基本稳定;6.x 缺少 “use_kibana_indexes” 字段,需手动删除;
  • RBAC:导出 JSON 时若带 “references” 中的 index-pattern-id,需要面试官侧存在同名索引模式,否则需附送 index-pattern JSON 或注明 “请替换 uuid”。

答案

以下 JSON 可直接通过 “Stack Management → Saved Objects → Import” 导入 Kibana 8.11+(7.x 亦兼容)。
假设:

  • 索引模式:logstash-apigateway-*
  • 时间字段:@timestamp
  • 响应时间字段:request_time(double,单位 ms)
  • 周同比:本周 vs 上周
  • 图表类型:Time Series,双 Y 轴关闭,统一 0-2000 ms 坐标
{
  "version": "8.11.0",
  "objects": [
    {
      "id": "tsvb-p95-response-week-on-week",
      "type": "visualization",
      "namespaces": ["default"],
      "updated_at": "2024-05-10T12:00:00.000Z",
      "version": "WzE2ODksMl0=",
      "attributes": {
        "title": "【面试题】P95响应时间周同比",
        "description": "TSVB 实现 95 分位响应时间并叠加周同比,供面试官一键导入验证",
        "visState": {
          "type": "metrics",
          "params": {
            "axis_formatter": "number",
            "axis_position": "left",
            "id": "61ca57f0-469d-11e7-af02-69e470af7417",
            "index_pattern": "logstash-apigateway-*",
            "interval": "auto",
            "series": [
              {
                "id": "61ca57f1-469d-11e7-af02-69e470af7417",
                "color": "#54B399",
                "split_mode": "everything",
                "metrics": [
                  {
                    "id": "61ca57f2-469d-11e7-af02-69e470af7417",
                    "type": "percentile",
                    "field": "request_time",
                    "percentiles": [95]
                  }
                ],
                "separate_axis": 0,
                "axis_position": "left",
                "formatter": "ms,0",
                "value_template": "{{value}} ms",
                "line_width": 2,
                "point_size": 0,
                "fill": 0.3,
                "stacked": "none",
                "label": "本周 P95",
                "type": "timeseries"
              },
              {
                "id": "61ca57f3-469d-11e7-af02-69e470af7417",
                "color": "#E7664C",
                "split_mode": "everything",
                "metrics": [
                  {
                    "id": "61ca57f4-469d-11e7-af02-69e470af7417",
                    "type": "percentile",
                    "field": "request_time",
                    "percentiles": [95]
                  }
                ],
                "separate_axis": 0,
                "axis_position": "left",
                "formatter": "ms,0",
                "value_template": "{{value}} ms",
                "line_width": 1,
                "point_size": 0,
                "fill": 0,
                "stacked": "none",
                "label": "上周 P95",
                "offset_time": "-1w",
                "type": "timeseries",
                "override_index_pattern": 0
              }
            ],
            "time_field": "@timestamp",
            "use_kibana_indexes": false,
            "interval": "auto",
            "drop_last_bucket": 1,
            "background_color_rules": [
              {
                "id": "background-61ca57f5-469d-11e7-af02-69e470af7417"
              }
            ],
            "show_grid": 1,
            "show_legend": 1,
            "legend_position": "bottom",
            "annotations": [],
            "palette": {
              "type": "palette",
              "name": "default"
            }
          },
          "aggs": []
        },
        "uiStateJSON": "{}",
        "kibanaSavedObjectMeta": {
          "searchSourceJSON": "{}"
        }
      },
      "references": [
        {
          "id": "logstash-apigateway-*",
          "name": "kibanaSavedObjectMeta.searchSourceJSON.index",
          "type": "index-pattern"
        }
      ]
    }
  ]
}

使用说明(写给面试官):

  1. 在 Kibana 创建索引模式 logstash-apigateway-*,时间字段选 @timestamp;
  2. 导入上述 NDJSON;
  3. 打开可视化,时间范围选 “Last 7 days”,即可看到绿色实线为本周 P95,红色虚线为上周 P95;
  4. 若数据量大于 10 TB/日,可把 TSVB 的 “Interval” 强制设为 ≥5m,并在 Elasticsearch 端开启 “index.routing.allocation.include.box_type: hot” 保证走热节点。

拓展思考

  1. 如何升级为 “动态基线”:
    用 Machine Learning 的 “Single-metric job” 先学习 4 周 P95,生成 “model_upper” 与 “model_lower”,再在 TSVB 里用 “Calculation” 指标拉取 ml- 索引的 forecast 结果,实现「本周曲线 vs 动态基线」而非简单周同比。
  2. 如何下沉到 SLO:
    把 P95 ≤ 1000 ms 定义为 “Good”,用 TSVB 的 “Math” 写 if(gte(params.p95,1000),0,1),再套 “Cumulative Sum” 得到合规事件数,最后与总事件数相除即可在仪表盘透出 “Latency SLO 99.9%”。
  3. 如何与告警联动:
    在 Kibana 8 的 “Rule & Connectors” 里新建 “Index threshold” 规则,聚合选 “percentile:request_time:95”,条件 “greater than 1200 ms” 持续 3 个周期,即可 5 分钟内发出飞书/钉钉/企微卡片,无需 watcher 脚本。
  4. 性能调优:
    • 提前在 Elasticsearch 侧把 request_time 设为 “index:true, doc_values:true” 并关闭 “norms” 节省磁盘;
    • 若索引按天滚动,可在 TSVB 开启 “Ignore global filters” 并自建 “Query” 过滤 “status:200”,减少 30% 扫描量;
    • 集群端开启 “pre_filter_shard_size:128” 避免跨月查询时打开过多 shard。