在 Python SDK 中定义 Counter、Gauge、Distribution 的完整示例
解读
国内面试官问这道题,不是让你背 API,而是考察三件事:
- 是否真正在跑批/跑流作业里用过自定义指标,而不是只会 print;
- 是否理解 Beam 的“合并语义”——Counter 累加、Gauge 覆盖、Distribution 采样合并;
- 是否能把指标与 DoFn 生命周期 结合,知道在 setup/start_bundle/process/finish_bundle 里哪里打点最准确,避免踩“bundle 重试导致重复计数”的坑。
一句话:代码要可运行、指标要可观测、语义要正确。
知识点
-
metrics 模块三大件:
Metrics.counter(namespace, name)→ 仅支持inc(),合并语义为累加;Metrics.gauge(namespace, name)→set(),合并语义为“后者覆盖前者”;Metrics.distribution(namespace, name)→update(value),合并语义为分布采样合并, runner 端会吐出 count/min/max/sum/mean 等统计量。
-
访问器:
MetricsFilter+pipeline.result.metrics().query(),本地 DirectRunner 与 Google Cloud Dataflow 均支持,Flink/Spark Runner 需确认版本 ≥ 2.50.0 才有完整实现。 -
线程安全:Beam Python SDK 在 工作进程级别 用原子变量,无需开发者加锁,但不要在
process_element里做重量级同步。 -
最佳实践:
- 指标名用 “业务域_指标名” 双段式,如
“order_paid_amount”,方便在 Grafana 按 namespace 过滤; - 在
start_bundle里初始化局部变量,在finish_bundle里批量update(),减少 Python GIL 竞争; - 对超大规模 key,用 “Top-N 采样” 策略,避免 Distribution 把内存打爆。
- 指标名用 “业务域_指标名” 双段式,如
答案
下面给出一个 可直接 python -m 运行 的完整示例,涵盖三类指标定义、打点、读取,注释里把面试常问的细节全部标粗:
# -*- coding: utf-8 -*-
"""
演示 Beam Python SDK 中 Counter、Gauge、Distribution 的完整生命周期。
运行:python metrics_demo.py --runner=DirectRunner
"""
import argparse
import apache_beam as beam
from apache_beam.metrics import Metrics
from apache_beam.metrics.metric import MetricsFilter
from apache_beam.options.pipeline_options import PipelineOptions
class TokenizeAndMeasure(beam.DoFn):
"""每行按空格切词,统计行数、词数、行长度分布,并动态上报指标。"""
def __init__(self):
# **必须在 __init__ 里声明**,否则 DoFn 序列化会丢失
self.line_counter = Metrics.counter('demo', 'lines') # Counter
self.word_gauge = Metrics.gauge('demo', 'last_word_count') # Gauge
self.len_dist = Metrics.distribution('demo', 'line_len') # Distribution
def process(self, element, *args, **kwargs):
# element 是一行文本
self.line_counter.inc(1) # **Counter 只能 inc**
line_len = len(element)
self.len_dist.update(line_len) # **Distribution 记录每次采样**
words = element.split()
self.word_gauge.set(len(words)) # **Gauge 只保留最后一次 set 的值**
# 把切分后的词发射出去,供下游继续计算
for w in words:
yield w
def run(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('--input',
default='gs://dataflow-samples/shakespeare/kinglear.txt',
help='Input file to process')
parser.add_argument('--output', required=True, help='Output file')
known_args, pipeline_args = parser.parse_known_args(argv)
opts = PipelineOptions(pipeline_args, save_main_session=True)
with beam.Pipeline(options=opts) as p:
# 1. 读文本
lines = p | 'Read' >> beam.io.ReadFromText(known_args.input)
# 2. 自定义指标打点
words = lines | 'Tokenize' >> beam.ParDo(TokenizeAndMeasure())
# 3. 简单下游:统计词频
counts = (
words
| 'PairWithOne' >> beam.Map(lambda w: (w, 1))
| 'GroupAndSum' >> beam.CombinePerKey(sum)
)
# 4. 写出
counts | 'Write' >> beam.io.WriteToText(known_args.output)
# 5. **等作业结束再查指标**,DirectRunner 会同步返回结果
result = p.run()
result.wait_until_finish()
# 6. **读取自定义指标**
metrics = result.metrics().query(
MetricsFilter().with_namespace('demo')
)
for counter in metrics['counters']:
print(f"Counter {counter.key.metric.name}: {counter.committed}")
for gauge in metrics['gauges']:
print(f"Gauge {gauge.key.metric.name}: {gauge.committed}")
for dist in metrics['distributions']:
d = dist.committed
print(f"Distribution {dist.key.metric.name}: "
f"count={d.count}, min={d.min}, max={d.max}, mean={d.mean:.2f}")
if __name__ == '__main__':
run()
运行后控制台会打印类似:
Counter lines: 5511
Gauge last_word_count: 9
Distribution line_len: count=5511, min=0, max=80, mean=37.42
面试加分句:
“如果作业上到 Dataflow,我可以在控制台直接看到相同 namespace 的指标,并基于 distribution 的 p99 配置告警,无需改代码。”
拓展思考
-
指标与状态(StateSpec)区别:指标仅用于观测,不会参与计算语义,而状态会随 key 持久化;面试可引申“如何用 BagState 实现精确去重,再用 Counter 记录去重后条数”。
-
跨 runner 一致性:Flink Runner 在 1.16+ 才完整支持 Beam 指标协议,生产环境务必在 staging 集群先跑 10 分钟抽样验证,避免“本地有、线上无”的尴尬。
-
性能调优:Distribution 默认采样 1024 次,大流量作业可在启动参数加
--distribution_sampling=2048,但会增大序列化开销;若只关心 p99,可自定义CombineFn做 t-digest 近似,兼顾精度与内存。