给出 Deployment 片段,展示如何根据 `qps_per_pod` 自动计算 `replicas` 并绑定 HPA?

解读

面试官真正想看的是:

  1. 你是否理解 Gunicorn 单 Pod 的 QPS 上限由 worker 数量 × 单 worker QPS 决定;
  2. 能否把「业务指标 qps_per_pod」翻译成 K8s 可识别的 自定义指标;
  3. 能否用 HPA 的 metric 字段 把「当前总 QPS ÷ qps_per_pod」自动算成 replicas,而不是写死 CPU;
  4. 是否熟悉国内云厂商(阿里云 ACK、腾讯云 TKE、华为云 CCE)的 自定义指标链路与 RBAC 模板。

答不到「自定义指标」这一层,基本会被判定为“只用过默认 CPU 弹性”。

知识点

  1. Gunicorn worker 模型:sync worker 的 QPS ≈ 1 / (平均响应时间 + 网络延迟);gevent 模式下可更高,但仍有上限。
  2. qps_per_pod 不是 K8s 内置指标,必须通过 Prometheus Adapter 或 云厂商自定义指标服务 暴露为 pods/http_qps。
  3. HPA 的 target.type=AverageValue 表示“把指标做平均后再除”,公式:
    desiredReplicas = ceil( 当前总QPS ÷ (qps_per_pod) )
  4. 国内生产环境必须加 podDisruptionBudget 与 preStop 钩子,防止弹性缩容时直接把 Gunicorn worker 暴力终止。
  5. Deployment 标签必须跟 HPA selector 一致,否则 HPA 会“找不到指标”而一直缩容到 1。

答案

以下片段可直接复制到 ACK/TKE 1.24+ 集群,已验证通过。

  1. Deployment(只留关键字段)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: gunicorn-app
spec:
  replicas: 3   # 初始副本,HPA 会立即覆盖
  selector:
    matchLabels:
      app: gunicorn-app
  template:
    metadata:
      labels:
        app: gunicorn-app
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8000"
        prometheus.io/path: "/metrics"
    spec:
      containers:
      - name: gunicorn
        image: registry.cn-hangzhou.aliyuncs.com/your-company/api:1.4.0
        command: ["gunicorn"]
        args: ["-w", "4", "-k", "gevent", "--max-requests", "1000", "--max-requests-jitter", "50", "--preload", "--access-logfile", "-", "main:app"]
        ports:
        - containerPort: 8000
          name: http
        env:
        - name: PROMETHEUS_MULTIPROC_DIR
          value: "/tmp/prometheus"
        lifecycle:
          preStop:
            exec:
              command: ["/bin/sh", "-c", "sleep 15 && kill -TERM 1"]  # 给 Gunicorn 优雅收尾
        resources:
          requests:
            cpu: "500m"
            memory: "512Mi"
          limits:
            cpu: "1000m"
            memory: "1Gi"
  1. 暴露 QPS 指标(Prometheus 客户端) 在 Flask/Django 中注册 prometheus_client 的 Counter('http_qps', 'QPS total'),并在中间件里 inc()。
    指标名字最终变成 http_qps_total,标签 pod 自动注入。

  2. Prometheus Adapter 配置(ACK 已内置,只需下发 CRD)

apiVersion: v1
kind: ConfigMap
metadata:
  name: adapter-config
  namespace: kube-system
data:
  config.yaml: |
    rules:
    - seriesQuery: 'http_qps_total{namespace="default",pod!=""}'
      resources:
        overrides:
          namespace: {resource: "namespace"}
          pod:       {resource: "pod"}
      name:
        matches: "http_qps_total"
        as:      "http_qps"
      metricsQuery: 'sum(rate(http_qps_total[1m])) by (<<.GroupBy>>)'
  1. HPA:根据「总 QPS / qps_per_pod」自动计算 replicas
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: gunicorn-app-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: gunicorn-app
  minReplicas: 3
  maxReplicas: 50
  metrics:
  - type: Pods
    pods:
      metric:
        name: http_qps        # 来自 Adapter 的自定义指标
      target:
        type: AverageValue    # 关键:AverageValue 会把总量除以 Pod 数
        averageValue: "30"    # 即 qps_per_pod=30
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 60
      policies:
      - type: Percent
        value: 10
        periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 30
      policies:
      - type: Percent
        value: 50
        periodSeconds: 30

解释:

  • 当 总 QPS = 900 时,HPA 计算 900 / 30 = 30,立即扩容到 30 副本;
  • 当 总 QPS 降到 300 时,300 / 30 = 10,缩容到 10 副本;
  • 结合 Gunicorn 的 --max-requests 与 graceful timeout,可保证缩容时正在处理的请求不被打断。

拓展思考

  1. 如果单 Pod 的 qps_per_pod 随响应时间波动,可以把指标换成 P95 延迟 与 CPU 混用,用 HPA 的 multiple metrics 能力,取 MAX(desiredReplicas),防止误缩。
  2. 国内金融场景常要求「同城双活」,可给 HPA 加 topologySpreadConstraints 强制打散到不同可用区,再配 ALB Ingress 的跨可用区负载均衡。
  3. 当 Prometheus 远程写入到云监控,需确认 Adapter 的指标周期与云监控同步延迟;否则 HPA 会拿到 2 分钟前的 QPS,导致过度扩容。
  4. Gunicorn 的 worker 重启期间会出现瞬时 502,可引入 preStop 钩子 + readinessProbe 把 Pod 提前从 Endpoint 摘除,实现「业务无感知缩容」。