基于QPS指标,如何编写PrometheusRule驱动HPA?
解读
在国内 ClickHouse 生产环境,QPS(Queries Per Second) 是最直观反映业务压力的指标。面试官想确认两点:
- 你能否把 ClickHouse 自带的 query_start 事件转化为 Prometheus 可消费的 QPS 指标;
- 你能否用 PrometheusRule 把 QPS 包装成 HPA 可用的自定义指标,并给出可直接落地的 YAML 片段。
回答必须体现“指标定义 → 规则录制 → HPA 绑定”三步闭环,且符合国内主流云原生栈(Prometheus-Operator + Kube-Metrics-Adapter/Custom-Metrics-API)。
知识点
- ClickHouse 暴露指标方式:
- 系统表 system.events 中的
QueryStart事件,或 - 通过 clickhouse-exporter(社区版或阿里云 ACK 集成版)把事件转成 Prometheus 格式。
- 系统表 system.events 中的
- PrometheusRule:CRD 由 Prometheus-Operator 提供,用于生成 Recording Rule 或 Alerting Rule;Recording Rule 可以把瞬时向量聚合成新的指标,供 HPA 查询。
- HPA 消费路径:
HPA v2 → External Metrics API(kube-metrics-adapter 实现)→ Prometheus 录制指标(非原始指标,避免高基数)。 - 国内常见坑:
- 标签必须带 clickhouse_cluster、shard、replica 等,否则多集群混用会互相干扰;
- 录制规则必须 rate() 后再 sum(),否则是总量而非 QPS;
- 最终指标名需符合 DNS-1123 规范(小写、下划线转驼峰),否则 External Metrics API 会 404。
答案
下面给出可直接拷贝到生产环境的 三步 YAML,假设集群名为 ch-olap,命名空间为 clickhouse,exporter 端口 9363。
第一步:确认 exporter 已把 QueryStart 事件转成
clickhouse_event_query_start_total{cluster="ch-olap",instance=~"clickhouse-.*"}
(阿里云 ACK 的 clickhouse-exporter 已内置,自建环境可用 grafana/clickhouse-exporter 镜像)。
第二步:编写 PrometheusRule,生成 ch_olap_qps_5m 录制指标
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: clickhouse-qps-recording
namespace: clickhouse
spec:
groups:
- name: clickhouse.qps
interval: 15s
rules:
- record: ch_olap_qps_5m
expr: |
sum by (cluster, namespace, statefulset_kubernetes_io_pod_name) (
rate(clickhouse_event_query_start_total{cluster="ch-olap"}[5m])
)
关键点:
- rate[5m] 消除突发尖刺,符合国内 4~9 点明显波峰波谷的业务节奏;
- 按 statefulset_kubernetes_io_pod_name 分组,保证 HPA 能精准定位到 Pod 级指标。
第三步:HPA 引用 External Metrics
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: clickhouse-shard
namespace: clickhouse
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: StatefulSet
name: clickhouse-shard0
minReplicas: 3
maxReplicas: 30
metrics:
- type: External
external:
metric:
name: ch_olap_qps_5m
selector:
matchLabels:
cluster: ch-olap
statefulset_kubernetes_io_pod_name: clickhouse-shard0
target:
type: AverageValue
averageValue: "50" # 单 Pod 50 QPS 即扩容
behavior:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Pods
value: 5
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Pods
value: 1
periodSeconds: 300
部署后,通过 kubectl get --raw /apis/external.metrics.k8s.io/v1beta1/namespaces/clickhouse/ch_olap_qps_5m 可验证指标已注册;HPA 会在 单 Pod QPS > 50 时 60 秒内扩容 5 个 Pod,低于阈值 5 分钟 后优雅缩容,避免国内晚高峰抖动误判。
拓展思考
- 多 shard 场景:
每个 shard 是独立 StatefulSet,需给每个 shard 建一条 PrometheusRule 录制规则,并在 HPA 的 selector 里带上 shard 标签;否则聚合后 QPS 会被平均,导致热点 shard 无法及时扩容。 - 读写分离:
国内大厂常把 写节点 与 只读副本 分开部署,QPS 规则应 排除 INSERT 语句,可在 exporter 侧加event!="QueryStart" or query_kind!="Insert"过滤,或录制规则里rate({query_kind!~"Insert|InsertSelect"}[5m])。 - 成本兜底:
结合 CronHPA 或 KEDA,在工作日 0~6 点强制缩容到 minReplicas,避免 PrometheusRule 误触发夜间批处理流量;同时给 HPA 加 externalMetric 的 maxValue 限制,防止因 exporter 挂掉导致 QPS=0 后瞬间扩容到 maxReplicas。