使用Prometheus统计GraphQL字段解析耗时并按复杂度加权

解读

在国内 Clojure 岗位面试中,这道题同时考察三项硬实力:

  1. 对 GraphQL 执行链路(parse→validate→execute)的侵入式埋点能力;
  2. 用 Prometheus Java Client(io.prometheus/simpleclient)在 JVM 上暴露 Histogram 指标,并正确设置 label 维度;
  3. 用“复杂度加权”体现对 GraphQL 成本分析(cost analysis)的理解,避免只统计 wall time 而忽略字段对系统资源的实际压力。

面试官常追问:

  • 如何防止高基数(cardinality)拖垮 Prometheus?
  • 如何在 REPL 热加载时动态调整桶边界?
  • 如何与 Lacinia(国内 Clojure 圈最常用 GraphQL 库)的异步解析器(Resolver)配合,不阻塞业务线程?

知识点

  1. Lacinia 执行模型
    com.walmartlabs.lacinia/execute 接受 :field-resolver 钩子,可包装成 metrics-middleware。

  2. Prometheus Histogram
    必须预定义桶(bucket),建议按国内接口 99th 线分布设置:0.001 0.005 0.01 0.05 0.1 0.25 0.5 1 2.5 5 10(秒)。
    标签至少保留:
    :field(截断后哈希防高基数)、:complexity(离散化后区间)、:status(ok/error)。

  3. 复杂度加权算法
    国内大厂普遍采用“静态+动态”双因子:

    • 静态:schema 声明的 cost(默认 1,列表乘以 pageSize 系数)。
    • 动态:实际返回数组长度。
      最终权重 = 静态 cost × 动态倍数。
      把权重离散化成低/中/高三档,作为 label 值,避免无限递增。
  4. 异步不阻塞
    Clojure 的 Resolver 返回 CompletableFuture 时,用 prometheus/simpleclient 的 Timer.start() 返回的 Timer$Context 必须在 whenComplete 里统一 close(),否则采样失真。

  5. 高基数治理
    字段名做“语义哈希”——取前 32 位 CRC32 转十六进制,既保留排障能力,又把 label 值域压到 2³² 以内。

答案

(ns app.graphql.metrics
  (:require [clojure.core.async :as async])
  (:import [io.prometheus.client Histogram Histogram$Timer]
           [java.util.concurrent CompletableFuture]
           [java.util.zip CRC32]))

;; 1. 定义 Histogram,桶按国内线上经验值
(def graphql-hist
  (Histogram/build)
  (.name "graphql_field_weighted_duration_seconds")
  (.labelNames (into-array String ["field" "complexity" "status"]))
  (.buckets (double-array [0.001 0.005 0.01 0.05 0.1 0.25 0.5 1 2.5 5 10]))
  (.register))

;; 2. 字段名哈希,防止高基数
(defn- field-key [field-name]
  (let [crc (CRC32.)]
    (.update crc (.getBytes field-name "UTF-8"))
    (format "%08x" (.getValue crc))))

;; 3. 复杂度离散化
(defn- bucketize [cost]
  (cond
    (<= cost 10)  "low"
    (<= cost 100) "mid"
    :else         "high"))

;; 4. 包装 resolver,支持同步与 CompletableFuture
(defn metrics-middleware [resolver-fn static-cost]
  (fn [context args parent]
    (let [timer  (.labels graphql-hist
                          (field-key (:field-name context))
                          (bucketize static-cost)
                          "ok")  ; 先默认成功
          ^Histogram$Timer ctx (.startTimer timer)]
      (try
        (let [raw (resolver-fn context args parent)]
          (if (instance? CompletableFuture raw)
            (.whenComplete raw
              (fn [_ err]
                (.close ctx)
                (when err
                  ;; 把状态改回 error
                  (.labels graphql-hist
                           (field-key (:field-name context))
                           (bucketize static-cost)
                           "error")
                  (.observe (.labels graphql-hist
                                     (field-key (:field-name context))
                                     (bucketize static-cost)
                                     "error")
                            (.elapsed (.startTimer timer))))))
            (do (.close ctx) raw)))
        (catch Exception e
          (.close ctx)
          (.observe (.labels graphql-hist
                             (field-key (:field-name context))
                             (bucketize static-cost)
                             "error")
                    (.elapsed (.startTimer timer)))
          (throw e))))))

;; 5. 在 schema 编译期注入
(defn attach-metrics [compiled-schema]
  (clojure.walk/postwalk
    (fn [node]
      (if-let [cost (-> node :resolve meta ::cost)]
        (update node :resolve metrics-middleware cost)
        node))
    compiled-schema))

使用示例(REPL 热加载友好):

(-> my-schema
    lacinia.schema/compile
    attach-metrics)

Prometheus 端点暴露:

(io.prometheus.client.exporter.HTTPServer. 8080)

查询示例(Grafana 面板):

histogram_quantile(0.99,
  sum(rate(graphql_field_weighted_duration_seconds_bucket[5m])) by (field, complexity, le)
)

可横向对比低/中/高三档复杂度在 99 线耗时,直接指导限流阈值与缓存策略。

拓展思考

  1. 动态 cost 调整
    如果列表字段实际返回 1000 条,而静态 cost 只给了 10,可把真实长度回写日志,离线训练线性回归,次日自动校正 schema 里的 ::cost 元数据,实现“自适应复杂度”。

  2. 与 Sentinel 流控联动
    国内阿里 Sentinel 已支持 Prometheus 数据源,可把加权 99 线耗时作为“慢调用比例”指标,触发热点参数限流,直接把高 cost 查询降级到兜底接口。

  3. 全链路追踪补充
    仅用 Prometheus 只能看到总量,排查单跳慢查询仍需 trace。可在 metrics-middleware 里把同一个 OpenTelemetry SpanContext 注入到 resolver 上下文,实现“指标+trace”双轨,面试时提到这一点可体现全栈视野。

  4. REPL 调优
    国内线上环境常开 24×7 REPL,调桶边界时直接
    (.. graphql-hast clear)
    再重新定义 Histogram,无需重启,展示 Clojure 运维优势。

  5. 多租户安全
    如果 SaaS 平台字段名包含租户 ID,一定先做哈希再当 label,否则容易被恶意租户刷爆 Prometheus。面试时主动提到“label 值域治理”会大幅加分。