如何基于 QPS 自动扩容 Knative 上的模型推理 Pod?

解读

在国内云原生面试中,这道题考察的是“把 Node.js 推理服务真正搬到生产”的最后一公里能力。
Knative 已经提供了基于“并发请求数”或“每秒请求数(RPS/QPS)”的自动扩缩容(KPA),但模型推理场景有三大特殊点:

  1. 单次推理 P99 latency 高,且 GPU/CPU 混部,资源单价高,不能简单按“并发数”线性换算;
  2. 流量存在突发峰值(短视频上传、直播连麦),需要秒级弹升、缓慢缩容;
  3. 国内公有云(阿里云 ACK、腾讯云 TKE、华为云 CCE)对 Knative 的默认安装做了裁剪,指标管道(metrics.k8s.io 或 custom.metrics.k8s.io)不一定开箱即用,必须自己打通。

因此,面试官想听到的是:

  • 你能否把“QPS”准确、实时地采集到 Knative Autoscaler;
  • 你能否针对模型推理的代价,给出“扩容快、缩容慢”的曲线;
  • 你能否用 Node.js 代码暴露一个最轻量的 metrics endpoint,而不引入 Java 系的 Sidecar。

知识点

  1. Knative Serving 架构:Revision → Deployment → Pod,Autoscaler 通过 Activator 收集流量指标。
  2. Knative PodAutoscaler 支持的度量维度:
    • concurrency:默认,单 Pod 并发请求数;
    • rps:单 Pod 每秒请求数;
    • cpu/memory:需要安装 custom.metrics.k8s.io,依赖 prometheus-adapter 或 alibaba-cloud-metrics-adapter。
  3. 国内云厂商的 Custom Metrics 打通路径:
    • 阿里云:arms-prometheus → alibaba-cloud-metrics-adapter → custom.metrics.k8s.io;
    • 腾讯云:tke-prometheus → tke-custom-metrics-api;
    • 华为云:AOM → aom-metrics-adapter。
  4. Node.js 暴露 Prometheus 格式指标:使用 prom-client 库,在业务端口 /metrics 返回文本格式,避免额外端口。
  5. Autoscaler 的窗口参数:
    • stable-window:计算稳定流量的时间窗,默认 60 s,推理场景建议 30 s 以缩短弹升时间;
    • scale-to-zero-grace-period:缩容到 0 的宽限期,GPU 场景建议设为 5 m 以上,防止频繁冷启动;
    • target-utilization-percentage:目标利用率,默认 70%,GPU 推理可降到 50%,留足显存余量。
  6. 冷启动优化:
    • 使用 Node.js 的 worker_threads 把模型加载阶段放到后台线程,避免阻塞事件循环;
    • 把模型文件(.onnx、.pt)提前拉取到节点本地盘,通过 DaemonSet + hostPath 共享,减少镜像体积与拉取时间;
    • Revision 设置 autoscaling.knative.dev/targetBurstCapacity: "0",让第一波请求直接打到 Pod,而不是 Activator,降低 30~50 ms 网络回环。

答案

第一步:在 Node.js 推理服务里埋点 QPS

// src/metrics.js
const client = require('prom-client');
const http = require('http');

const qps = new client.Counter({
  name: 'model_inference_qps_total',
  help: 'Total number of inference requests',
  labelNames: ['model', 'version']
});

// 每收到一次请求就 inc()
module.exports.recordQPS = (model, version) => qps.inc({ model, version });

// 把 /metrics 挂在主应用里,不新增端口
module.exports.injectMetricsEndpoint = (app) => {
  app.get('/metrics', async (req, res) => {
    res.set('Content-Type', client.register.contentType);
    res.end(await client.register.metrics());
  });
};

第二步:安装 prometheus-adapter(以阿里云 ACK 为例,其他云换对应 adapter)

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prom prometheus-community/kube-prometheus-stack \
  -n monitoring --set prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false

kubectl apply -f https://aliacs-knative.oss-cn-hangzhou.aliyuncs.com/adapter/alibaba-cloud-metrics-adapter.yaml

第三步:确认 custom.metrics.k8s.io 已注册

kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1 \
  | jq '.resources[] | select(.name | contains("model_inference_qps"))'

若能返回 services/model_inference_qps,说明指标已上报。

第四步:创建 KPA 策略,以 QPS 为度量

apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: nodejs-model
  namespace: inference
spec:
  template:
    metadata:
      annotations:
        autoscaling.knative.dev/metric: rps
        autoscaling.knative.dev/target: "30"          # 单 Pod 目标 30 QPS
        autoscaling.knative.dev/class: kpa.autoscaling.knative.dev
        autoscaling.knative.dev/minScale: "1"
        autoscaling.knative.dev/maxScale: "50"
        autoscaling.knative.dev/window: "30s"
        autoscaling.knative.dev/panic-window: "10s"
        autoscaling.knative.dev/scale-to-zero-grace-period: "5m"
    spec:
      containers:
      - image: registry.cn-hangzhou.aliyuncs.com/yourrepo/nodejs-model:v1.2.3
        ports:
        - containerPort: 8080
        env:
        - name: MODEL_NAME
          value: "resnet50"
        resources:
          requests:
            cpu: 500m
            memory: 1Gi
            nvidia.com/gpu: "1"   # 若有 GPU
          limits:
            nvidia.com/gpu: "1"

第五步:压测验证
使用阿里云 PTS 或本地 wrk2,以阶梯 QPS 50→100→200 压测,观察:

kubectl get pod -n inference -l app=nodejs-model -w

Pod 数量应在 30 s 内从 1 弹升到 7(200/30≈6.6),停止压测后 5 min 缓慢缩回 1,即符合预期。

第六步:灰度与回滚
利用 Knative 的 Revision 机制,先灰度 10% 流量到新版本,对比 P99 latency 与 GPU 利用率,若无异常再全量。回滚只需 kubectl patch 把 traffic 重新指向旧 revision,秒级生效。

拓展思考

  1. 如果模型需要批量 GPU 推理(动态 batch=8),QPS 与 GPU 利用率不再线性,如何设计指标?
    可在 Node.js 里再暴露 gpu_utilization gauge,autoscaler 使用 custom.metrics.k8s.io 的复合规则:
    if qps > 100 || gpu_utilization > 80% then scale up。
    这需要给 KPA 写一个小型 composite-metrics-adapter,把两个指标聚合成一个虚拟指标,展示你对 extend-k8s 的能力。

  2. 国内部分金融客户要求“0 冷启动”,禁止缩到 0,但夜间 QPS 极低,如何节省成本?
    可用 Knative + 虚拟节点(VK)方案:夜间把 Pod 弹到阿里云的 ECI 按量实例,白天弹回普通节点,通过 nodeSelector 和 toleration 自动漂移,实现“ Serverless 但不零实例”。

  3. 多模型混布场景,一个 Pod 里加载 3 个模型,如何分别按模型的 QPS 维度扩缩?
    把每个模型拆成独立的 Container(sidecar 模式),各自暴露 /metrics,然后用 Kubernetes 的 containerMetric 字段给每个容器单独设置 HPA,Knative 目前不支持容器级指标,需要降级到标准 Deployment + KEDA,展示你对社区局限性的认知与折中方案。