基于查询 QPS 实现 HPA,给出 Prometheus Adapter 配置
解读
在国内云原生面试中,“用 Prometheus Adapter 把 InfluxDB 的查询 QPS 转成 HPA 可用指标” 是高频追问。
核心诉求有三点:
- 指标必须来自 InfluxDB 自身,而不是业务埋点;
- 指标要能 秒级刷新,否则 HPA 延迟大;
- 配置必须 可灰度、可回滚,符合生产审计要求。
面试官常通过“QPS 口径怎么算”“adapter 重启会不会丢指标”“多集群怎么隔离”来深挖候选人对 Prometheus relabel、adapter rules、HPA external metrics 全链路的掌握程度。
知识点
- InfluxDB 自带
_internal库:
httpd::writeReq与queryReq分别记录写与查询请求,按database标签区分实例。 - Prometheus 拉取 InfluxDB 的
/metrics端点:
该端点使用 InfluxDB 1.x 的 Prometheus exposition format,可直接被 Prometheus scrape。 - Prometheus Adapter 的
seriesQuery与metricsQuery语法:
通过 Go template 把 Prometheus 的influxdb_httpd_requests_total聚合成 QPS。 - HPA 的
external.metrics.k8s.io版本:
必须 v1beta1 及以上,且指标名称符合 DNS-1123 规范。 - 国内云厂商限制:
阿里云 ACK、腾讯云 TKE 默认 不开 external metrics,需手动开白名单并授权 RBAC。
答案
步骤一:确认 InfluxDB 暴露指标
InfluxDB 1.8+ 默认在 0.0.0.0:8086/metrics 提供 Prometheus 格式数据,核心指标:
influxdb_httpd_requests_total{database="telegraf",method="GET",path="/query",status="2xx"}
步骤二:Prometheus 抓取任务(prometheus.yml 片段)
scrape_configs:
- job_name: 'influxdb'
static_configs:
- targets: ['influxdb.monitoring.svc.cluster.local:8086']
metric_relabel_configs:
# 只保留查询路径
- source_labels: [__name__, path]
regex: 'influxdb_httpd_requests_total;/query'
action: keep
# 把 database 标签重命名为 workload,供 adapter 使用
- source_labels: [database]
target_label: workload
action: replace
步骤三:Prometheus Adapter 配置(config-map.yaml)
apiVersion: v1
kind: ConfigMap
metadata:
name: adapter-config
namespace: monitoring
data:
config.yaml: |
rules:
- seriesQuery: 'influxdb_httpd_requests_total{workload!=""}'
seriesFilters: []
resources:
overrides:
workload: {resource: "deployment"}
name:
matches: "influxdb_httpd_requests_total"
as: "influxdb_query_qps"
metricsQuery: |
sum(rate(influxdb_httpd_requests_total{workload=~".+",path="/query"}[1m])) by (workload)
步骤四:HPA 对象(hpa.yaml)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: influxdb-query-hpa
namespace: default
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: influxdb
minReplicas: 2
maxReplicas: 20
metrics:
- type: External
external:
metric:
name: influxdb_query_qps
selector:
matchLabels:
workload: telegraf
target:
type: Value
value: "1000"
behavior:
scaleDown:
stabilizationWindowSeconds: 60
policies:
- type: Percent
value: 10
periodSeconds: 15
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 50
periodSeconds: 15
关键注意:
- metric 名称必须与 adapter 的
as字段完全一致,否则 HPA 报 “metric not found”。 - adapter 需挂载上述 ConfigMap 并加启动参数
--prometheus-url=http://prometheus:9090 --metrics-relist-interval=30s。 - 国内集群需提前在 kube-system 下创建 ClusterRoleBinding 让 adapter 有权限写 external.metrics.k8s.io。
拓展思考
- 多数据库实例隔离:
若同一集群跑多个 InfluxDB,可在 adapter 规则里再加一级标签namespace,并在 HPA 的selector中同时匹配workload与namespace,实现 软多租。 - 精度与开销权衡:
把[1m]改成[30s]能提高 HPA 灵敏度,但会增加 Prometheus 查询负载;国内大厂通常 白天 30s、夜间 2m 动态调整。 - 灰度发布:
利用 Argo Rollouts 的 canary 策略,把新版本的 adapter 规则先挂在v1beta2API,通过 HPA 的behavior.scaleDown.selectPolicy=Disabled禁止缩容,观察 30 分钟无异常再全量切换。