在 KeyBy 之前自定义分区器解决 Union 后大 Key 倾斜的代码模板?

解读

国内实时数仓、风控、推荐等业务场景里,Union 多个 Kafka Topic 或 Hive 维表流后,经常遇到“大 Key 倾斜”——某个用户 ID、商户号或设备号占比 90% 以上,导致下游 KeyBy 后 subtask 之间数据量差异 10 倍以上,Checkpoint 超时、背压、GC 频繁成为面试高频痛点。
面试官真正想考察的是:

  1. 你能否在 KeyBy 之前(即还未形成 KeyedStream 时)用自定义分区器把热 Key 打散;
  2. 打散逻辑必须保留原有 Key 的完整性,保证下游算子仍能正确聚合;
  3. 代码必须可迁移、可复用,能直接塞进现有 Flink SQL/Table 或 DataStream 工程里,不改业务 SQL;
  4. 你清楚什么时候用 rebalance、rescale、partitionCustom,以及**二次聚合(两阶段聚合)**如何配合。

知识点

  1. DataStream.partitionCustom 是 pre-keyby 的唯一入口,运行在并行实例的输出端(output side),在 Netty shuffle 之前完成重分布。
  2. 热 Key 识别:静态白名单(配置表)、动态采样(TTL MapState)、Flink SQL 的 TOPN 结果广播。
  3. 打散策略:
    • 后缀追加“_bucket${0…N}” → 下游聚合时用 GroupConcat + 去后缀 二次汇总;
    • 使用 MurmurHash + 取模 保证同一原始 Key 的桶号 deterministic;
    • 桶数 = 下游并行度 × 2~4,避免桶数过大导致小文件。
  4. 两阶段聚合:
    • 第一阶段:pre-key + bucket → 局部聚合(MiniBatch);
    • 第二阶段:去掉 bucket 后缀,KeyBy 原始 Key 做全局聚合;
    • 第二阶段并行度可降到 1/4,减少状态大小。
  5. Savepoint 兼容:分区器必须幂等,桶号算法不能依赖当前并发,否则扩缩容后 Key 重新分布,状态无法恢复。
  6. 性能陷阱:
    • 自定义分区器里不要访问外部系统(如 HBase 查白名单),用广播变量或异步采样;
    • 避免在分区器里 new 对象,复用 Tuple2/Row 减少 GC。

答案

下面给出国内一线大厂实时数仓可直接落地的代码模板,Flink 1.15+ 通用,兼容 SQL 与 DataStream 混合任务:

// 1. 定义热 Key 白名单读取接口,支持 Apollo/Naocs 动态更新
public interface HotKeyService extends Serializable {
    boolean isHot(String key);
    int bucketNum(String key);   // 返回该热 Key 应该拆成多少桶
}

// 2. 自定义分区器:只在热 Key 上追加桶后缀,冷 Key 保持原值
public class HotKeySpreadPartitioner<T> implements Partitioner<T> {
    private final HotKeyService hotKeyService;
    private final int downstreamParallelism;

    public HotKeySpreadPartitioner(HotKeyService service, int para) {
        this.hotKeyService = service;
        this.downstreamParallelism = para;
    }

    @Override
    public int partition(T key, int numPartitions) {
        String k = key.toString();
        if (!hotKeyService.isHot(k)) {
            // 冷 Key:按原 Key 哈希
            return MathUtils.murmurHash(k) % numPartitions;
        }
        // 热 Key:追加桶号后再哈希,保证打散
        int buckets = hotKeyService.bucketNum(k);
        int bucket = MathUtils.murmurHash(k + "_" + ThreadLocalRandom.current().nextInt(buckets)) % buckets;
        String spreadKey = k + "_bucket" + bucket;
        return MathUtils.murmurHash(spreadKey) % numPartitions;
    }
}

// 3. 两阶段聚合工具类:第一阶段局部聚合,第二阶段全局聚合
public class TwoStageAgg {
    public static SingleOutputStreamOperator<Row> build(
            SingleOutputStreamOperator<Row> source,
            int downstreamPara,
            HotKeyService hotKeyService) {

        // 3.1 在 KeyBy 之前先分区打散
        SingleOutputStreamOperator<Row> spreadStream = source
                .partitionCustom(new HotKeySpreadPartitioner<>(hotKeyService, downstreamPara),
                                 r -> r.getFieldAs<String>("user_id"));

        // 3.2 第一阶段:pre-key + bucket 局部聚合(MiniBatch 开启)
        SingleOutputStreamOperator<Row> partial = spreadStream
                .keyBy(r -> r.getFieldAs<String>("user_id"))
                .window(TumblingProcessingTimeWindows.of(Time.minutes(1)))
                .aggregate(new CountAggFunc())   // 局部聚合函数
                .name("stage1-partial");

        // 3.3 去掉桶后缀,还原原始 Key
        SingleOutputStreamOperator<Row> restored = partial.map(r -> {
            String user = r.getFieldAs<String>("user_id");
            int idx = user.indexOf("_bucket");
            if (idx > 0) user = user.substring(0, idx);
            return Row.of(user, r.getFieldAs<Long>("cnt"));
        }).returns(Types.ROW(Types.STRING, Types.LONG));

        // 3.4 第二阶段:按原始 Key 全局聚合
        return restored
                .keyBy(r -> r.getFieldAs<String>("f0"))
                .window(TumblingProcessingTimeWindows.of(Time.minutes(1)))
                .sum("f1")
                .name("stage2-global");
    }
}

// 4. 主作业入口:Union 多个源后直接使用
public class Job {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.enableCheckpointing(30_000, CheckpointingMode.EXACTLY_ONCE);

        // 4.1 Union 多个 Kafka Topic
        DataStream<Row> a = env.addSource(new FlinkKafkaConsumer<>("topicA", …));
        DataStream<Row> b = env.addSource(new FlinkKafkaConsumer<>("topicB", …));
        SingleOutputStreamOperator<Row> union = a.union(b);

        // 4.2 加载热 Key 配置(示例用本地文件,生产可接 Apollo)
        HotKeyService hotKeyService = new FileHotKeyService("/conf/hotkeys.txt");

        // 4.3 两阶段聚合
        SingleOutputStreamOperator<Row> result = TwoStageAgg.build(union, 48, hotKeyService);

        result.print();
        env.execute("UnionHotKeySpread");
    }
}

使用要点

  • 把 HotKeySpreadPartitioner 插在 union 之后、第一次 KeyBy 之前,即可在 shuffle 阶段把热 Key 拆成 N 份;
  • 桶号算法必须** deterministic**,Savepoint 扩容时桶数不变,只改下游并发;
  • 若作业完全用 SQL,可把第一阶段写成 VIEW + INSERT INTO,第二阶段再 GROUP BY user_id,SQL 层无需改分区器,只需在 table.exec.mini-batch 开启即可。

拓展思考

  1. 动态热 Key 发现:用 Flink CEP 或 SQL 的 TOPN 每 30s 输出最热 100 个 Key,广播到所有并发作为热 Key 白名单,实现零重启调整。
  2. 与 Hive 维表 Join 场景:维表也有大 Key,可先把维表 bucket 化(Hive 表新增 bucket 列),再与主表在 Temporal Table Join 时按 concat(original_key, '_bucket', mod(probe_hash, N)) 关联,避免维表热 Key 拖垮 Flink 并发。
  3. Flink 1.17 的 Adaptive Batch Scheduler 已支持自动倾斜探测,但流任务尚未合并;可提前在批模式调优拿到热 Key 分布,反哺流任务白名单。
  4. 云原生场景:在 K8s 上通过 HorizontalPodAutoscaler + Flink Autoscaler 把第二阶段并发从 48 缩到 12,节省 60% CPU,但前提仍是分区器桶数固定,否则状态漂移。
  5. 面试加分项:提到 “我们生产环境把桶号算法做成 Guava Cache + TTL”,并给出 “大 Key 二次聚合后使用 MapState 存明细,防止 UV 计算误差”,可直接拿到 P7+ 评级。