特征平台:Feature Store、离线在线、训练服务一致性
机器学习工程师最容易遇到的"鬼故事":训练时算特征跑出 AUC 0.85,上线后 AUC 0.65——一查发现训练用 Spark SQL 算的特征,上线用 Java 重写了一遍,计算逻辑漂移。这就是 Training-Serving Skew(训练-服务偏差),特征平台(Feature Store)就是为解决这个问题诞生的。这一篇拆离线 / 在线两层、特征注册中心、Point-in-time 时间正确性、Feast / Tecton / Hopsworks 三家选型。
一句话先记住:特征平台 = 特征定义中心 + 离线存储(训练)+ 在线存储(推理)+ 双写同步管道。核心解决两件事:复用(A 团队算的特征 B 团队也能用)和一致性(训练用什么计算逻辑,服务也用什么)。没特征平台不是不能做 ML,是规模化做 ML 时必然踩坑。
一、没特征平台的世界
1.1 一个真实灾难
模型团队 A:
目标:用户复购预测模型
特征:
- 过去 30 天订单数
- 过去 30 天总金额
- 过去 7 天活跃天数
训练:写 Spark SQL 跑离线特征 → 训练 → AUC 0.85
上线:
模型部署到推理服务(Java/Python)
特征需要实时算:用户每次请求,后端查 DB / Redis / 调多个微服务
后端工程师按理解重写特征逻辑:
- 过去 30 天订单数:SELECT COUNT(*) FROM orders WHERE user_id=? AND created_at > now() - 30day
(但 Spark 用的是 event_time,不是 created_at!)
- 过去 7 天活跃天数:从用户行为表算
(但 Spark 算时排除了"测试账号",上线漏掉这个过滤)
上线后:
AUC 0.65
原因:特征算错了,模型看到的特征值跟训练时分布不一致
= Training-Serving Skew1.2 第二个灾难:重复造轮子
推荐团队算「用户近期偏好」
风控团队算「用户近期偏好」(不同口径)
营销团队算「用户近期偏好」(又不同口径)
每个团队:
- 自己写 Spark
- 自己存特征
- 自己维护更新
结果:三套不一致的"近期偏好",数仓存 3 份,口径不一致,谁也不能信。二、特征平台解决的两件事
2.1 复用
特征中心:
user_recent_orders_30d (复购预测、推荐、风控共用)
user_avg_amount_30d
user_active_days_7d
user_segment
...
各团队来这里"订阅",不重复造2.2 训练-服务一致性
训练时:
特征值从离线存储读(SQL/Spark 算出来,存 Parquet/Iceberg)
推理时:
特征值从在线存储读(Redis/Cassandra,毫秒返回)
关键: 两边的"计算逻辑"是同一份(在特征平台里定义一次)
离线管道和在线管道都跑这一份定义
→ 训练时 user_recent_orders_30d=12,推理时也是 12三、心智:特征平台的三件套
特征注册中心 (Feature Registry)
──────────────────────
特征定义:名字 / 类型 / 计算 SQL / TTL / Owner
│
┌─────────────┼─────────────┐
▼ ▼ ▼
离线存储 特征同步 在线存储
────────── 管道 ──────────
Iceberg / ────── Redis /
Snowflake / Spark / Cassandra /
BigQuery Flink DynamoDB
│ │
▼ ▼
训练时读 推理时读
(Pandas / Spark) (REST / gRPC)3.1 离线存储
- 存历史所有特征值(几个月到几年)
- 训练时用,Point-in-time correctness(后面讲)
- 通常基于 Lakehouse(Iceberg / Snowflake)
3.2 在线存储
- 存当前特征值 + 短期历史(几小时到几天)
- 推理时用,毫秒级延迟
- 通常 Redis / Cassandra / DynamoDB
3.3 同步管道
- 把离线计算结果同步到在线
- 批模式:每天 / 每小时同步
- 流模式:Flink 实时算 + 实时写在线
四、Point-in-Time Correctness:训练样本的时间正确
4.1 什么是 Point-in-time
ML 训练样本:(user_id, event_time, label, features)
样本:
user=1, event_time=2024-06-15, label=1(复购了),features=???
user=2, event_time=2024-08-01, label=0(没复购),features=???
错误做法:
特征用「当前」值(2025-05-11)
→ user=1 训练时拿到的是 2025-05-11 的近 30 天订单数
→ 但样本时间是 2024-06-15,应该拿那时的特征
→ 数据泄漏(Future Leak),模型作弊
正确做法(Point-in-Time):
user=1 → 拿 2024-06-15 之前的 30 天订单数
user=2 → 拿 2024-08-01 之前的 30 天订单数4.2 实现:as-of join
sql
-- 离线存储里特征是带时间的:
feature_table:
user_id, computed_at, recent_orders_30d
1, 2024-06-14, 12
1, 2024-06-15, 12
1, 2024-06-16, 13
2, 2024-07-31, 5
2, 2024-08-01, 5
...
-- 训练样本:
samples:
user_id, event_time, label
1, 2024-06-15, 1
2, 2024-08-01, 0
-- Point-in-time join:
SELECT
s.user_id, s.event_time, s.label,
f.recent_orders_30d
FROM samples s
LEFT JOIN LATERAL (
SELECT recent_orders_30d
FROM feature_table
WHERE user_id = s.user_id
AND computed_at <= s.event_time
ORDER BY computed_at DESC
LIMIT 1
) f ON true;每个样本拿「event_time 之前的最近一次特征值」,避免泄漏。
4.3 Feast / Tecton 都内置这套
python
training_data = store.get_historical_features(
entity_df=samples_df, # 含 user_id, event_time, label
features=["user_features:recent_orders_30d", "user_features:avg_amount_30d"]
).to_df()
# 内部自动 point-in-time join五、三大特征平台
5.1 Feast(2018,开源)
Feast = Feature Store(轻量、开源)
出身:Gojek + Google
定位:把已有数据基础设施"封装"成特征平台
不带计算,只管 Registry + Online Serving + Offline 抽象核心抽象:
- Entity:特征的"主体"(user / product / merchant)
- FeatureView:一组特征 + 计算逻辑 + Source
- DataSource:离线 / 流式数据源
- OnlineStore / OfflineStore:可插拔
python
from feast import FeatureStore, Entity, FeatureView, Field
from feast.types import Float32
user = Entity(name="user_id", join_keys=["user_id"])
user_features = FeatureView(
name="user_features",
entities=[user],
schema=[
Field(name="recent_orders_30d", dtype=Float32),
Field(name="avg_amount_30d", dtype=Float32),
],
online=True,
source=BigQuerySource(...) # 离线源
)
store = FeatureStore(repo_path=".")
store.apply([user, user_features])
# 训练时(离线特征)
training_df = store.get_historical_features(
entity_df=samples,
features=["user_features:recent_orders_30d"]
).to_df()
# 推理时(在线特征)
features = store.get_online_features(
features=["user_features:recent_orders_30d"],
entity_rows=[{"user_id": 1}]
).to_dict()优点:
- 开源、灵活
- 不绑死任何计算 / 存储
- 部署简单(轻量)
缺点:
- 不做特征计算:特征怎么算是你的事,Feast 只管"存和读"
- 需要自己搭离线计算 + 同步管道
- 流式特征 1.0+ 才支持(早期主打批)
5.2 Tecton(2019,商业 SaaS)
Tecton = Uber Michelangelo 团队出来商业化
定位:端到端特征平台,全托管
带计算、带流式、带 Materialization 编排特征定义直接带计算 SQL:
python
@batch_feature_view(
sources=[bq_orders],
entities=[user],
ttl=timedelta(days=30),
schedule=timedelta(hours=1), # Tecton 自动调度
batch_schedule=...
)
def user_recent_orders_30d(orders):
return f"""
SELECT user_id, COUNT(*) AS recent_orders_30d, MAX(event_time) AS computed_at
FROM {orders}
WHERE event_time > NOW() - INTERVAL 30 DAY
GROUP BY user_id
"""
@stream_feature_view(...)
def user_orders_last_5m(orders_stream):
return f"SELECT ... FROM {orders_stream} ..."Tecton 自动:
- 跑批 / 流计算
- 写离线 + 同步在线
- Point-in-time join
- 监控特征质量
优点:
- 真正"端到端",全托管
- 流批一体特征定义
- 企业级 SLA + 治理
缺点:
- 贵
- SaaS,数据出网风险
- 灵活性低于 Feast
5.3 Hopsworks(2018,开源 + 商业)
Hopsworks = 跟 Iceberg / Spark 深度集成
定位:特征平台 + 数据科学平台一体
自带元数据 + 项目隔离特征组(Feature Group) 是核心:
python
fg = fs.create_feature_group(
name="user_features",
version=1,
primary_key=["user_id"],
event_time="computed_at",
online_enabled=True
)
fg.insert(df)
# 训练数据集
td = fs.create_training_dataset(
name="purchase_train",
version=1,
data_format="parquet"
)
td.save(df_with_features)优点:
- 跟 Spark / Iceberg 深度集成
- 强血缘 + 治理
- 项目隔离
缺点:
- 部署较重
- 中国生态略弱
5.4 大厂自研
Uber Michelangelo Palette
LinkedIn Frame / Feathr
阿里 FeatureMart
美团 Feature Platform
字节 Feature Platform
→ 思想都一致:特征定义 + 离线 + 在线 + 一致性
→ 工程实现不同,但概念上 80% 重叠六、流式特征(关键场景)
6.1 为什么需要流式
"用户最近 5 分钟点击数":
批模式:每 1 小时跑一次 → 实时性差(平均 30 分钟延迟)
流模式:Flink 持续算 → 秒级延迟
"用户当日累计金额":
批模式:每天凌晨算 → 不能实时阻止超额消费
流模式:Flink 状态聚合 → 实时风控可用6.2 Flink + 特征平台
python
# Flink 算流式特征
result_stream = (
kafka_orders
.key_by(lambda r: r.user_id)
.window(SlidingEventTimeWindows.of(Time.minutes(5), Time.minutes(1)))
.aggregate(SumAggregator("amount"))
)
# 写在线存储 + 离线存储
result_stream.add_sink(RedisSink(...)) # 在线
result_stream.add_sink(IcebergSink(...)) # 离线特征平台只需注册「这个特征是流式的」+ 提供 SDK 读。
6.3 实时特征的代价
- 状态管理复杂(21 篇)
- 延迟保证 + 一致性挑战
- 成本高(Flink 集群常驻 + RocksDB)
只对真正实时需要的特征上流式,其他批就够。
七、训练-服务一致性的工程手段
7.1 共享同一段计算定义
特征定义在特征平台里只写一次(SQL / Python)
离线管道和在线服务都通过 SDK 调
任何变更走特征平台 PR + Review7.2 影子表对照
python
# 在线服务每次推理:
features_online = feature_store.get_online_features(...)
# 同时写一份到"影子表"(异步)
shadow_log.write({
"request_id": req_id,
"features": features_online,
"timestamp": now
})
# 离线:跑一遍同样请求的特征
features_offline = compute_offline(req_id)
# 对比:
diff = compare(features_online, features_offline)
if diff > threshold:
alert("Training-Serving Skew detected")7.3 CI 跑特征快照
python
def test_feature_consistency():
sample_users = load_test_users()
online_features = [store.get_online(u) for u in sample_users]
offline_features = store.get_offline_pit(sample_users, point_in_time=now)
for o, f in zip(online_features, offline_features):
assert close_enough(o, f), f"Skew: {o} vs {f}"每次特征代码改动,PR 跑这个测试。
八、工程落地:一个最小特征平台
python
# 1. 定义特征(Feast)
# feature_repo/features.py
from feast import FeatureView, Entity, Field, FileSource
from feast.types import Float32, Int32
user = Entity(name="user_id", join_keys=["user_id"])
source = FileSource(
path="s3://bucket/features/user_features.parquet",
timestamp_field="computed_at"
)
user_fv = FeatureView(
name="user_features",
entities=[user],
schema=[
Field(name="recent_orders_30d", dtype=Int32),
Field(name="avg_amount_30d", dtype=Float32),
Field(name="active_days_7d", dtype=Int32),
],
online=True,
source=source
)python
# 2. 离线计算(Spark + dbt model)
# models/marts/user_features.sql
{{ config(materialized='incremental') }}
SELECT
user_id,
CURRENT_TIMESTAMP() AS computed_at,
COUNT(DISTINCT order_id) FILTER (WHERE event_time > CURRENT_DATE - 30) AS recent_orders_30d,
AVG(amount) FILTER (WHERE event_time > CURRENT_DATE - 30) AS avg_amount_30d,
COUNT(DISTINCT DATE(event_time)) FILTER (WHERE event_time > CURRENT_DATE - 7) AS active_days_7d
FROM {{ ref('fct_orders') }}
GROUP BY user_idpython
# 3. 同步到在线(Feast Materialize)
store = FeatureStore(repo_path=".")
store.materialize_incremental(end_date=datetime.now())
# 从离线源 → Redis 在线存储python
# 4. 训练时(离线读)
samples = pd.DataFrame({
"user_id": [1, 2, 3],
"event_time": [...],
"label": [1, 0, 1]
})
training_data = store.get_historical_features(
entity_df=samples,
features=[
"user_features:recent_orders_30d",
"user_features:avg_amount_30d",
"user_features:active_days_7d"
]
).to_df()
# 训练
model.fit(training_data, training_data["label"])python
# 5. 推理时(在线读)
features = store.get_online_features(
features=[
"user_features:recent_orders_30d",
"user_features:avg_amount_30d",
"user_features:active_days_7d"
],
entity_rows=[{"user_id": 1}]
).to_dict()
score = model.predict(features)九、特征平台的几个真实痛点
9.1 命名规范
没规范:
user_orders_count 推荐团队用
user_recent_order_cnt 风控团队用
user_recent_orders 营销团队用
都是「用户最近订单数」,但 30 天还是 7 天?含退款不?
→ 几个月后还是一样混乱
正解:
${entity}_${aggregation}_${time_window}_${context}
user_orders_count_30d_excluding_refund9.2 治理 / Owner
每个特征必须有 owner(团队 + Slack)。没 owner = 半年后没人改 = 烂尾。
9.3 离线 vs 在线偏差
离线:跑 Spark 算的是 event_time 时间窗口
在线:Redis 算的是 processing_time 时间窗口
→ 永远不一致
正解:统一用 event_time + watermark(流处理思想)9.4 流式 + 批的口径对齐
流式特征在 Flink 算:窗口可能未关
批侧补算:窗口已关
两者口径:流式可能少 / 多某些事件
→ 训练时统一用批,推理时用流式 → 漂移9.5 特征值缺失
新用户没有历史,特征是 NULL
→ 模型 input 是 NULL → 失败 / 用默认值
→ 必须在特征平台层面处理 NULL / 默认值规范十、什么时候不需要特征平台
10.1 小团队 / 单模型
1 个模型,几个特征,SQL 直接查 → 不需要特征平台
PG + Redis 手撸即可10.2 RAG / 文本场景
RAG 不需要"特征" → 需要向量库(29 篇)
特征平台主要给结构化 ML10.3 端到端深度学习
神经网络直接吃原始信号(图像 / 文本)
→ 特征工程很弱 / 没有
→ 不需要特征平台十一、看完这一篇,你应该能
- 解释 Training-Serving Skew 是什么,为什么必然
- 在白板上画特征平台三件套(注册中心 / 离线 / 在线 / 同步管道)
- 解释 Point-in-time Correctness 防止数据泄漏
- 区分 Feast / Tecton / Hopsworks 三家定位
- 给团队建议:小规模别上,但规模化做 ML 必备
- 知道流式特征的代价,只对真正实时需求上
下一篇:31 数据质量与可观测 — 没监控的数据管道是定时炸弹。dbt test / Great Expectations / Soda / Monte Carlo 怎么管数据质量。