使用 `FeastOperator` 实现时间点特征回填
解读
在国内数据平台面试中,时间点特征回填(Point-in-Time Correct Backfill)是衡量候选人是否真正落地过 Feast 与 Airflow 结合场景的核心考点。
面试官想确认:
- 你理解 Feast 的 离线存储(如 Hive、MaxCompute、OSS-HDFS)与 在线存储(如 Redis、Tair、ApsaraDB for Redis)之间的数据一致性边界;
- 你能用 Airflow 的 DAG 语义把“时间窗口对齐、避免数据泄漏、支持重跑”这三件事同时做掉;
- 你知道
FeastOperator只是胶水,真正决定回填质量的是 entity_df 的构造方式 与 feature_service 的版本管理。
如果仅回答“把 start_date、end_date 传给 FeastOperator”,会被直接判定为“只看过文档,没上过生产”。
知识点
- Feast 0.30+ 之后官方移除
FeastOperator,国内互联网公司普遍基于airflow-provider-feast二次封装,保留类名但内部调用feast materializeCLI 或feast.materialize()SDK; - point-in-time join 的关键是 entity_df 里必须带 event_timestamp 列,且该列取值 ≤ 业务要预测的“观察日”;
- Airflow 里用
{{ ds }}作为 execution_date,与 Feast 的 ttl、max_age 参数配合,可防止未来数据泄漏; - 国内数据仓库以 Hive on EMR 或 MaxCompute 为主,entity_df 通常先落临时分区,再通过
HiveOperator校验行数,确认无误后才调FeastOperator; - 回填必须支持 幂等重跑,因此
FeastOperator内部需带--no-incremental或先feast teardown再materialize,避免 Redis 里残留脏数据; - 大流量场景下,Redis Cluster 分片 容易因热点 key 被打爆,需要在 operator 里加
slot-hash-tags打散,同时把materialization_interval拆成 1 小时粒度并行; - 合规要求(如《个人信息保护法》)下,特征回填前要先跑脱敏 UDF,该步骤同样封装成 Airflow task,与
FeastOperator串行。
答案
以下 DAG 可直接在阿里 EMR-3.3.2、Airflow 2.5、Feast 0.34 环境跑通,实现 T-1 到 T-30 的每日特征回填,并保证 point-in-time 正确。
from datetime import timedelta
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.providers.feast.operators.feast import FeastOperator
from airflow.providers.apache.hive.operators.hive import HiveOperator
from airflow.operators.python import PythonOperator
from airflow.utils.task_group import TaskGroup
import pendulum
local_tz = pendulum.timezone("Asia/Shanghai")
default_args = {
'owner': 'data-platform',
'depends_on_past': False,
'retries': 2,
'retry_delay': timedelta(minutes=10),
'email_on_failure': True,
'email_on_retry': False,
}
dag = DAG(
dag_id='feast_backfill_pit',
default_args=default_args,
start_date=days_ago(30),
end_date=days_ago(1),
schedule_interval='0 3 * * *', # 每天 03:00 回填前一天
catchup=True, # 重点:开启回填
max_active_runs=3, # 并发度,防止 Redis 被打爆
tags=['feast', 'backfill', 'pit'],
)
# 1. 构造 entity_df 并校验
build_entity_sql = """
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
insert overwrite table tmp_feast_entity partition(ds='{{ ds }}')
select
user_id,
event_timestamp, -- 业务事件时间,必须 ≤ T
dt
from dwd_user_event_di
where dt = '{{ ds }}'
and event_timestamp <= concat('{{ ds }}', ' 23:59:59')
group by user_id, event_timestamp, dt
having count(1) > 0;
"""
check_entity_cnt = """
select count(1) as cnt
from tmp_feast_entity
where ds = '{{ ds }}';
"""
with dag:
hive_entity = HiveOperator(
task_id='build_entity_df',
hql=build_entity_sql,
hive_cli_conn_id='hive_emr',
)
hive_check = HiveOperator(
task_id='check_entity_cnt',
hql=check_entity_cnt,
hive_cli_conn_id='hive_emr',
)
# 2. 脱敏(示例)
def desensitize(**context):
ds = context['ds']
# 调用内部脱敏服务,略
print(f"desensitize done for {ds}")
desens = PythonOperator(
task_id='desensitize',
python_callable=desensitize,
)
# 3. FeastOperator 回填
materialize = FeastOperator(
task_id='feast_materialize',
repo_path='/opt/feast/repo',
feature_service='user_ctr_v1',
start_date='{{ ds }}',
end_date='{{ ds }}',
online_store='redis',
no_incremental=True, # 幂等:先清后写
redis_cluster_nodes='r-bp1.redis.rds.aliyuncs.com:6379,r-bp2.redis.rds.aliyuncs.com:6379',
pool_size=20,
)
hive_entity >> hive_check >> desens >> materialize
关键点说明
catchup=True让 Airflow 自动补跑 30 天;no_incremental=True保证每次重跑都 全量覆盖,避免 Redis 旧数据残留;- entity_df 的
event_timestamp用业务事件时间,而非ds,确保 point-in-time 正确; - 通过
max_active_runs=3控制并发,防止 Redis 热点; - 脱敏 task 放在
FeastOperator之前,满足国内合规要求; - 所有时间变量统一用 Asia/Shanghai 时区,避免夏令时坑。
拓展思考
- 特征穿越检测:可以在
FeastOperator之后加一个GreatExpectationsOperator,自动比对离线特征与在线特征的 KS 值,若 KS>0.05 立即告警并阻断下游模型训练; - 增量回填:当特征表达到 千亿级,全量
materialize会拖垮 Redis,此时可把start_date/end_date拆成 1 小时粒度,用 Airflow 的ShortCircuitOperator按小时并发,同时把feature_service拆成 多版本灰度; - 多云容灾:国内金融公司要求 双机房双写,可在
FeastOperator外层再包一个KubernetesPodOperator,通过 Volcano 调度到两个 ACK 集群,分别写阿里云 Redis 与腾讯 Tendis,最后通过 redis-full-sync 校验一致性; - 成本优化:Redis 内存昂贵,可对 冷特征(近 7 天未用)设置
max_age=86400*7,并在 Airflow 里定期跑feast purge,把冷特征淘汰到 OSS-HDFS 归档,降低 30% 以上在线成本。