在 Rails 7 中如何自定义指标并推送到 Prometheus
解读
国内一线互联网公司在面试中常把“可观测性”作为必考项,Prometheus 又是云原生监控的事实标准。面试官问这道题,不是让你背 gem 名字,而是考察:
- 是否理解 Rails 7 的异步执行模型(Zeitwerk、Fiber、Hotwire 等带来的新线程特征);
- 能否在不污染业务代码的前提下,优雅注入指标埋点;
- 是否掌握线程安全、性能损耗、标签维度设计三大落地细节;
- 是否知道国内合规要求(如金融、医疗场景下指标脱敏、采样率上报审批流程)。
一句话:要你给出“能直接上生产”的方案,而不是跑通 hello world。
知识点
- Prometheus 数据模型:Counter、Gauge、Histogram、Summary 四类,必须线程安全。
- Rails 7 官方推荐的进程模型:Puma 单进程多线程 +
load_async+Fiber.schedule,指标收集器必须Per-Thread + Per-Fiber 隔离或原子操作。 - Yabeda 生态:
yabeda-rails:自动暴露 Rails 基础指标;yabeda-prometheus:提供/metrics端点;yabeda-sidekiq:Sidekiq 深度埋点;- 支持自定义标签分组与零依赖启动,符合国内“可审计、可灰度”要求。
- Mmap 高性能埋点:对高并发网关,国内大厂(如美团、B 站)会改用
prometheus-client-mmap,避免 Ruby Global VM Lock 竞争。 - 指标治理:
- 标签维度≤5,防止 cardinality 爆炸;
- 命名规范:
namespace_subsystem_metric_unit(例:mall_order_created_total); - 采样率与脱敏必须可配置,满足《个人信息保护法》。
答案
生产级落地分五步,可直接写进简历:
- Gemfile 引入
gem 'yabeda-rails'
gem 'yabeda-prometheus'
gem 'prometheus-client', '~> 4.0' # 指定大版本,避免 3.x 线程安全问题
- 初始化收集器(
config/initializers/prometheus.rb)
Yabeda.configure do
group :mall do
counter :order_created_total, comment: '已创建订单', tags: %i[source city]
histogram :checkout_duration_seconds, buckets: [0.1, 0.3, 0.5, 1, 2], tags: %i[payment_method]
end
end
Yabeda::Prometheus::Exporter.start
- 业务代码零侵入埋点(用 ActiveSupport::Notifications 代理)
# app/models/order.rb
class Order < ApplicationRecord
after_create_commit do
Yabeda.mall.order_created_total.increment({ source: user.source, city: delivery_city }, by: 1)
end
end
# app/controllers/checkout_controller.rb
def create
Yabeda.mall.checkout_duration_seconds.measure({ payment_method: params[:pay_by] }) do
# 核心业务
end
end
- 暴露指标端点(
config/routes.rb)
require 'yabeda/prometheus/exporter'
mount Yabeda::Prometheus::Exporter => '/metrics'
- K8s 采集配置(国内阿里云 ACK、腾讯云 TKE 通用)
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "3000"
prometheus.io/path: "/metrics"
注意:如果集群版本 ≥1.24,需显式给 ServiceAccount 绑定 monitoring:prometheus-k8s ClusterRole,否则 403。
灰度验证:
- 本地
curl localhost:3000/metrics | grep mall能看到自定义指标; - 上线后通过 Grafana 大盘模板 12856(Ruby on Rails)直接导入,5 分钟级告警接入飞书/钉钉。
拓展思考
-
高并发场景(万级 RPS)下,Yabeda 的原子操作仍可能触发 Ruby GVL,如何再降 30% CPU? → 改用
prometheus-client-mmap,指标写入内存映射文件,完全无锁;配合Ractors(Ruby 3.2+)做分片聚合,单实例可扛 4 万 RPS(B 站 2023 年压测数据)。 -
多租户 SaaS要按“企业 ID”做标签,但企业数量上万,Cardinality 爆炸怎么办? → 采用预聚合 + 记录规则:
- 应用层只上报按大区+套餐的聚合指标;
- Prometheus 侧用
recording rule再按企业维度二次聚合; - 这样既满足租户隔离查询,又避免内存爆炸,符合国内金融云合规审计。
-
Rails 7 引入 Hotwire Turbo 后,页面走 WebSocket,传统 HTTP 指标失效,如何衡量“用户真实首屏时间”? → 自定义
turbo:frame-load与turbo:render事件,在 Stimulus 控制器里埋点:document.addEventListener('turbo:frame-load', () => { window.performance.mark('turbo_frame_done'); fetch('/metrics/browser', {method: 'POST', body: JSON.stringify({frame_time: performance.now()})}); });后端再封装
Yabeda.browser.turbo_frame_load_duration_seconds.measure(...),打通前后端全链路。
掌握以上三点,面试时可主动反问:“贵司当前 cardinality 上限是多少?是否已接入 mmap?” 瞬间把面试官拉到对等交流层面,加分项直接拉满。