在OpenFaaS中通过Prometheus监控函数并发度并自动扩容的示例
解读
面试官抛出这道题,核心想验证三件事:
- 你是否真正在生产级 OpenFaaS 环境里做过容量治理,而不是只跑过 hello-world;
- 能否把 Prometheus 的“指标→告警→扩容”闭环讲清楚,并落地到 Kubernetes 的 HPA 或 OpenFaaS 自带的 Auto-scaling API;
- 对国内云原生落地痛点(镜像拉取慢、HPA 冷启动、指标漂移、配额治理)有没有可落地的兜底方案。
答题时必须给出“可复制的最小生产示例”,包括:采集哪条指标、PromQL 怎么写、告警规则怎么配、扩容对象是谁、灰度节奏如何控制。只讲“把 concurrency 指标打到 Prometheus”只能拿 60 分,必须补全“阈值怎么定、冷启动怎么防、扩完怎么缩”才能到 90 分。
知识点
- OpenFaaS 网关暴露的 Prometheus 原生指标
gateway_function_invocation_in_flight{function_name="xxx"}:当前正在处理的请求数,即实时并发度。gateway_function_invocation_total:累计调用次数,用于计算 QPS。
- Prometheus 告警规则模板(带中文注释,方便国内运维交接)
- KEDA ScaledObject 或 Kubernetes HPA 的“external”类型,把 Prometheus 查询结果作为扩缩容信号。
- 国内镜像加速:给 KEDA 的 metrics-server 和 OpenFaaS 网关都配阿里云 ACR 镜像缓存,避免扩容时镜像拉取超时。
- 冷启动保护:通过
initialDelaySeconds和scaleDownDelay把缩容窗口拉到 120s 以上,防止毛刺。 - 配额兜底:在 Namespace 级设置 ResourceQuota,防止 HPA 把集群打爆;同时给函数配 LimitRange,保证扩容副本的 CPU 请求一致,避免调度倾斜。
答案
下面给出一条可直接落地到阿里云 ACK 的完整链路,假设函数名是 order-svc,目标并发度阈值为 10,最大副本 30。
步骤 1:确认指标已采集
OpenFaaS 网关自带 /metrics,Prometheus 通过 serviceMonitor 抓取即可。验证 PromQL:
gateway_function_invocation_in_flight{function_name="order-svc"} 能返回即时向量。
步骤 2:写 Prometheus 告警规则(prometheus-rule.yaml)
groups:
- name: openfaas-concurrency
interval: 15s
rules:
- alert: OpenFaaSHighConcurrency
expr: |
(
gateway_function_invocation_in_flight{function_name="order-svc"}
> 10
)
for: 30s
labels:
severity: critical
scaling: "true"
annotations:
summary: "函数 {{ $labels.function_name }} 并发度 {{ $value }} 超过阈值 10"
description: "建议立即扩容至 {{ $value | humanizePercentage }} 倍"
步骤 3:用 KEDA 做弹性(keda-scaledobject.yaml)
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: order-svc-concurrency
namespace: openfaas-fn
spec:
scaleTargetRef:
name: order-svc # 对应 Deployment 名
pollingInterval: 15
cooldownPeriod: 120
maxReplicaCount: 30
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus.monitoring.svc.cluster.local:9090
metricName: gateway_function_invocation_in_flight
threshold: "10"
query: |
gateway_function_invocation_in_flight{function_name="order-svc"}
步骤 4:灰度与兜底
- 在 Staging 环境先把 threshold 调到 5,压测 20 min,观察副本曲线与冷启动时间(P99 是否 < 2s)。
- 生产上线前,把 HPA 的
behavior.scaleDown.stabilizationWindowSeconds设为 300,防止晚高峰后瞬间缩容导致抖动。 - 给
openfaas-fn命名空间加 ResourceQuota:
requests.cpu: "20"/requests.memory: 40Gi/count/pods: "100",避免 KEDA 失控。
步骤 5:验收
kubectl get hpa -n openfaas-fn 能看到 EXTERNAL 指标来源为 prometheus,TARGETS 列实时显示当前并发度;用 hey -z 60s -c 50 打流量,副本数应在 30s 内从 1 升到 5 以上,停止压测后 5 min 内逐步回缩到 1,即判定通过。
拓展思考
-
如果函数冷启动要 8s,而业务要求 99th 延迟 < 500ms,该如何调整?
思路:把 KEDA 的pollingInterval降到 5s,并给函数加 2 个最小副本(minReplicaCount: 2),同时用 OpenFaaS Pro 的预热池,把冷启动降到 300ms 以内。 -
国内混合云场景下,Prometheus 与 KEDA 跨网络域,查询延迟高,导致扩容滞后怎么办?
思路:在边缘机房单独部署 Thanos Receive,做指标就近存储;KEDA 的 prometheus trigger 指向边缘 Query,而不是中心 Prometheus,保证 15s 内完成采样→判断→扩容。 -
函数并发度瞬间冲到 200,但后端 RDS 最大连接只有 100,如何防止“扩容成功却拖垮数据库”?
思路:在 KEDA 之上再包一层“业务限流”闸门:用 Prometheus 的sql_connection_usage指标写一条记录规则,当 RDS 连接率 > 80% 时,通过 Argo Rollouts 立即把函数副本数锁死,不再接受扩容信号,同时触发钉钉告警,让 DBA 手动升配或开启只读实例。