将曝光流与点击流在 10s 内关联,如何设置侧输出流收集超时未匹配样本?

解读

国内实时推荐、广告计费等场景,需要把“曝光”与“点击”在事件时间维度做双流关联(双流 Join)。
10 秒是业务对“有效点击”的归因窗口;超过 10 秒未点击的曝光,需要单独收集,用于反作弊、样本负采样、计费补差等后续链路。
Flink 的 DataStream API 提供了 Interval Join(仅支持处理时间/事件时间区间连接)和 CoProcessFunction(最灵活,可自定义状态 TTL、侧输出、定时器)。
面试中,Interval Join 无法直接输出“未匹配”数据,因此必须采用 KeyedCoProcessFunction + 状态 + 注册事件时间定时器 + 侧输出流 的方案,才能精确收集超时未匹配样本,并保证 Exactly-Once 语义。

知识点

  1. 事件时间语义:必须指定 env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) 并在两条流上分配 Watermark(国内 Kafka 源通常用 BoundedOutOfOrdernessTimestampExtractor 或 WatermarkStrategy)。
  2. 状态类型:
    • MapState<Long, Exposure>:以曝光 ID 为 key,缓存曝光事件;
    • ValueState<Long>:点击流侧保存已匹配曝光 ID,防止重复下发。
  3. 定时器:在曝光到达时,注册 事件时间定时器 ctx.timerService().registerEventTimeTimer(exposureTimestamp + 10 000);定时器触发即表示 10 秒窗口结束。
  4. 侧输出流:通过 OutputTag<Exposure> 定义,调用 ctx.output(unmatchedTag, exposure) 将超时未匹配样本下沉。
  5. 状态清理:定时器触发后,必须显式 exposureState.clear() 并 matchedFlag.clear(),避免 状态无限膨胀 导致 OOM;同时开启 增量 Checkpoint 和 RocksDB State TTL 做双重保护。
  6. 幂等与乱序:曝光或点击可能重复或乱序,需在状态中做 去重 keyBy(如曝光 ID + 设备 ID),并在点击侧使用 matchedFlag 防止重复关联。
  7. 并行度与热点:国内大促场景 QPS 高,需 预聚合分桶 key(如 曝光_id % 512)打散热点,避免单 sub-task 状态过大。

答案

完整代码骨架(Scala,Java 同理):

// 侧输出 Tag
val unmatchedTag = OutputTag[Exposure]("unmatched-exposure")

// 主处理函数
class ExposureClickJoinFunc extends KeyedCoProcessFunction[String, Exposure, Click, (Exposure, Click)] {
  // 曝光状态:Map<曝光ID, Exposure>
  lazy val exposureState = getRuntimeContext.getMapState(
    new MapStateDescriptor[Long, Exposure]("exposure-state", classOf[Long], classOf[Exposure]))
  // 已匹配标记:Map<曝光ID, Boolean>
  lazy val matchedFlag = getRuntimeContext.getMapState(
    new MapStateDescriptor[Long, Boolean]("matched-flag", classOf[Long], classOf[Boolean]))

  override def processElement1(exp: Exposure,
                               ctx: KeyedCoProcessFunction[String, Exposure, Click, (Exposure, Click)]#Context,
                               out: Collector[(Exposure, Click)]): Unit = {
    exposureState.put(exp.expId, exp)
    // 注册 10s 后触发的定时器
    val timer = exp.eventTime + 10000
    ctx.timerService.registerEventTimeTimer(timer)
  }

  override def processElement2(clk: Click,
                               ctx: KeyedCoProcessFunction[String, Exposure, Click, (Exposure, Click)]#Context,
                               out: Collector[(Exposure, Click)]): Unit = {
    val exp = exposureState.get(clk.expId)
    if (exp != null && !matchedFlag.contains(clk.expId)) {
      matchedFlag.put(clk.expId, true)
      out.collect((exp, clk))
    }
  }

  override def onTimer(timestamp: Long,
                       ctx: KeyedCoProcessFunction[String, Exposure, Click, (Exposure, Click)]#OnTimerContext,
                       out: Collector[(Exposure, Click)]): Unit = {
    val iter = exposureState.entries().iterator()
    while (iter.hasNext) {
      val entry = iter.next()
      val expId = entry.getKey
      if (!matchedFlag.contains(expId)) {
        ctx.output(unmatchedTag, entry.getValue)
      }
      // 清理状态
      iter.remove()
      matchedFlag.remove(expId)
    }
  }
}

// 主流程
val exposureStream = env
  .addSource(new FlinkKafkaConsumer[Exposure]("exposure", schema, props))
  .assignTimestampsAndWatermarks(WatermarkStrategy
    .forBoundedOutOfOrderness[Exposure](Duration.ofSeconds(2))
    .withTimestampAssigner(_.eventTime))

val clickStream = env
  .addSource(new FlinkKafkaConsumer[Click]("click", schema, props))
  .assignTimestampsAndWatermarks(WatermarkStrategy
    .forBoundedOutOfOrderness[Click](Duration.ofSeconds(2))
    .withTimestampAssigner(_.eventTime))

val joined = exposureStream
  .keyBy(_.userId)   // 假设按用户 keyBy,也可按曝光 ID 分桶
  .connect(clickStream.keyBy(_.userId))
  .process(new ExposureClickJoinFunc)

// 正常匹配流
joined.print()

// 侧输出流:超时未匹配曝光
val unmatched = joined.getSideOutput(unmatchedTag)
unmatched.addSink(new FlinkKafkaProducer[Exposure]("unmatched-exposure", schema, props))

核心要点:

  • 定时器时间 = 曝光事件时间 + 10 000 ms,保证窗口长度严格 10 秒;
  • 状态清理在 onTimer 内完成,防止状态泄漏;
  • 侧输出流 unmatchedTag 独立下沉 Kafka,下游可实时消费做负样本或补差。

拓展思考

  1. 如果业务窗口改为 10~30 秒动态可配,可将窗口长度作为广播状态下发,定时器注册时读取广播变量即可;
  2. 若曝光量巨大,可采用 RocksDB + 增量 Checkpoint + 本地 SSD 磁盘,并开启 状态压缩;
  3. 需要支持端到端 Exactly-Once 输出,在 Kafka Sink 端开启 两阶段提交(FlinkKafkaProducer.Semantic.EXACTLY_ONCE),并配置 事务超时 > Checkpoint 间隔 + 最大乱序;
  4. 若允许点击晚于 10 秒但不超过 30 秒,可再注册一个 30 秒定时器,在第二次定时器触发时才彻底清理状态,实现 多级超时策略;
  5. SQL 方案:Flink 1.16+ 的 Interval Join SQL 仍无法直接输出未匹配数据,但可通过 LEFT JOIN + Deduplicate 方式近似实现,不过状态放大 2 倍,生产环境不推荐;
  6. 监控与报警:在 onTimer 内增加 Metric counter(unmatchedCounter.inc()),接入 Prometheus + Grafana,实时观测未匹配率,超过 5% 即触发企业微信/飞书报警,保障国内大促期间广告计费准确性。