为 Perl 应用实现 HPA 基于 QPS 的自定义指标
解读
在国内云原生落地场景中,Perl 服务多以 Sidecar 容器或独立 Pod 形式跑在 K8s 上。HPA(HorizontalPodAutoscaler)默认只认 CPU/内存,而线上流量高峰往往由 QPS 触发,因此必须把 Perl 进程实时处理的“当前 QPS”暴露成 K8s 可识别的自定义指标(Custom Metric)。面试问这道题,不是让你写几行 Perl 脚本,而是考察你能否把“Perl 指标采集 → 指标聚合 → 注册到 K8s 自定义指标 API → HPA 消费”整条链路打通,并兼顾高可用、可灰度、可回滚、可观测四大落地要点。
知识点
-
Perl 指标采集:
a. 在 Plack/PSGI 层埋点,每收到一个请求就在内存哈希$env->{'qps.count'}原子加 1;
b. 用Time::HiRes按 1 s 滑动窗口计算rate(qps),避免计数器回绕;
c. 通过Prometheus::Tiny::Shared或本地 StatsD UDP 端口把指标推出去,保证采集逻辑对业务零侵入。 -
指标暴露与格式:
a. 走/metrics端点返回 Prometheus 文本格式,key 为perl_app_qps_per_second,标签含app、pod、namespace;
b. 端口统一用 8081,与业务 8080 隔离,方便 ServiceMonitor 抓取。 -
自定义指标注册:
a. 部署 Prometheus Adapter(国内阿里云 ACK、腾讯云 TKE 均提供镜像加速源),配置seriesQuery: perl_app_qps_per_second{namespace!=""};
b. 在 Adapter 的metricsQuery里写 PromQL:sum(rate(perl_app_qps_per_second{<<.LabelMatchers>>}[30s])) by (<<.GroupBy>>),把结果映射成pods/perl_app_qps_per_second资源指标;
c. 验证kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1/namespaces/default/pods/*/perl_app_qps_per_second能返回正确 JSON。 -
HPA 策略:
a. 定义autoscaling/v2版本 HPA,指标类型Pods,目标值设 500(即单 Pod 平均 QPS 500 时扩容);
b. 扩容步长用periodSeconds: 15、scaleUp.stabilizationWindowSeconds: 60,防止毛刺;
c. 同时保留 CPU 指标作为兜底,避免 QPS 指标断流时无法缩容。 -
可观测与灰度:
a. 在 HPA 上打annotations: "hpa.example.com/metrics-source=prometheus-adapter",方便值班定位;
b. 通过kubectl top pod --custom-metrics实时查看;
c. 灰度阶段先让 10% Pod 带新指标,确认 Adapter 无 5xx 再全量。
答案
- Perl 端埋点(Plack::Middleware 片段)
package Plack::Middleware::QpsCounter;
use parent qw(Plack::Middleware);
use Time::HiRes qw(time);
use POSIX qw(ceil);
sub call {
my($self, $env) = @_;
my $start = time;
my $res = $self->app->($env);
# 原子计数
$self->{counter}++;
my $elapsed = time - $self->{window_start};
if ($elapsed >= 1) {
my $qps = ceil($self->{counter} / $elapsed);
$self->{counter} = 0;
$self->{window_start} = time;
# 写共享内存或 UDP
$self->record_qps($qps);
}
return $res;
}
sub record_qps {
my($self, $qps) = @_;
# 本地 UDP 到 statsd_exporter 9125 端口
IO::Socket::INET->new(PeerPort => 9125, Proto => 'udp')
->send("perl_app_qps_per_second:$qps|g");
}
1;
业务 app.psgi 里 enable "QpsCounter"; 即可。
- Prometheus Adapter 配置(config-map.yaml)
rules:
- seriesQuery: 'perl_app_qps_per_second{namespace!="",pod!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
name:
matches: "perl_app_qps_per_second"
as: "perl_app_qps_per_second"
metricsQuery: |
sum(rate(perl_app_qps_per_seconds{<<.LabelMatchers>>}[30s])) by (<<.GroupBy>>)
- HPA 对象(hpa.yaml)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: perl-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: perl-app
minReplicas: 2
maxReplicas: 20
metrics:
- type: Pods
pods:
metric:
name: perl_app_qps_per_second
target:
type: AverageValue
averageValue: "500"
behavior:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Pods
value: 2
periodSeconds: 15
- 验证
# 压测 2k QPS
kubectl exec -it siege-pod -- siege -c 50 -t 60s http://perl-app.default.svc.cluster.local
# 查看 HPA
kubectl get hpa perl-app-hpa -w
# 期望 REPLICAS 从 2 → 6,平均 QPS 降到 500 左右
拓展思考
- 多语言混布:如果同一 Pod 里还有 OpenResty,需把
perl_app_qps_per_second与nginx_vts_server_requests_per_second做加权汇总,避免单语言指标失真。 - 指标断流兜底:Adapter 到 Prometheus 网络抖动时,可给 HPA 加
fallback: 80%策略,让系统按历史 80% 水位保守扩容。 - 成本优化:国内云厂商对“自定义指标调用次数”单独计费,需把 Adapter 的
discoveryInterval调到 30s 以上,并开启metricsRelistInterval缓存,减少 List 调用。 - Serverless 场景:Perl 冷启动慢,可结合 KEDA 把 QPS 指标转成 Kafka 事件,提前扩容到“预热副本”,再交给 HPA 细调,实现“秒级弹升、分钟级缩容”。