说明如何自定义transducer在pipeline中实现批量写入数据库

解读

国内 Clojure 岗位集中在高并发数据平台、风控、支付清结算等对吞吐与一致性要求极高的场景。面试官抛出此题,想验证三件事:

  1. 是否真正理解 transducer 的“零中间集合”本质,而非把 comp 当管道拼接;
  2. 能否把“批”这个副作用边界清晰地隔离开,做到纯函数与副作用分离;
  3. 对背压、失败重试、事务补偿有没有工程级思考,而不是写个 toy demo。

因此,回答必须给出:

  • 一个纯函数式、无中间集合的 batching transducer;
  • 一个与具体 JDBC/DataSource 解耦的副作用函数;
  • 一套可观测、可灰度、可回滚的运维策略。

知识点

  1. transducer 三要素:初始函数、完成函数、step 函数;reduced 短路机制。
  2. 状态持有:在 transducer 内部用 volatile! 或 atom 保存当前批次,必须保证线程安全(pipeline 会在多个线程上并发 reduce)。
  3. 副作用边界:只在完成函数或 reduced 触发时落库;批次未满而上游结束时也必须落库,防止丢数据。
  4. 背压与重试:batch 大小与超时双重触发;失败时把整批抛给重试队列,避免部分写入。
  5. Clojure 与 Java 互操作:使用 next.jdbc 的 with-transaction 与 insert-multi!,手动控制批大小与事务边界,避免 MySQL 死锁。
  6. 观测性:通过 tap> 把批指标打到 core.async 的 mult,供日志、Prometheus、阿里云 SLS 消费。

答案

(ns bulk-xd
  (:require [next.jdbc :as jdbc]
            [next.jdbc.sql :as sql]
            [clojure.core.async :as async]
            [clojure.tools.logging :as log]))

;; 1. 纯函数 batching transducer,线程安全
(defn x-batch
  "返回一个 transducer,收集大小为 n 的批次,超时 t-ms 也触发落库。
   批次未满而上游结束时,自动落库剩余数据。"
  [n t-ms flush-fn!]
  (fn [rf]
    (let [batch (volatile! [])  ; 当前批次
          timer (volatile! nil) ; 超时句柄
          ;; 真正落库并清空状态
          (do-flush! []
            (when-some [b (seq @batch)]
              (try
                (flush-fn! b)
                (catch Exception e
                  (log/error e "batch flush failed, will retry whole batch")
                  (throw e))) ; 让上游感知失败
              (vreset! batch [])
              (when-some [t @timer] (future-cancel t))
              (vreset! timer nil)))]
      ((fn [rf]
         (fn
           ([] (rf)) ; 初始化
           ([result]
            (do-flush!) ; 上游结束,强制落库
            (rf result))
           ([result input]
            (let [new-batch (vswap! batch conj input)]
              (when (== (count new-batch) 1)
                ;; 第一个元素,启动超时
                (vreset! timer (future
                                 (Thread/sleep t-ms)
                                 (locking batch (do-flush!)))))
              (if (>= (count new-batch) n)
                (do
                  (locking batch (do-flush!))
                  (if (reduced? result)
                    result
                    (unreduced result)))
                result)))))
       rf))))

;; 2. 副作用函数,与数据源解耦
(defn jdbc-flush!
  "使用 HikariCP 数据源,整批一个事务写入,失败抛异常触发重试。"
  [ds table cols]
  (fn [rows]
    (jdbc/with-transaction [tx ds]
      (sql/insert-multi! tx table cols rows {:batch-size (count rows)}))))

;; 3. 组装 pipeline(以 core.async 为例,国内常用)
(defn start-pipeline!
  "返回一个关闭函数 (fn [])。"
  [ds table cols batch-size batch-timeout-ms input-chan]
  (let [flush! (jdbc-flush! ds table cols)
        out-chan (async/chan 1000 (x-batch batch-size batch-timeout-ms flush!))]
    (async/pipe input-chan out-chan)
    ;; 观测指标
    (async/tap (async/mult (async/chan 1 (map (fn [rows]
                                                 {:metric "bulk_insert"
                                                  :count  (count rows)
                                                  :ts     (System/currentTimeMillis)}))))
               (async/chan (async/sliding-buffer 1024)))
    ;; 返回关闭函数
    #(do (async/close! input-chan)
         (async/close! out-chan))))

;; 4. 使用示例(REPL 驱动开发)
(comment
  (def ds (jdbc/get-datasource {:jdbcUrl "jdbc:mysql://localhost:3306/demo?useSSL=false"
                                :username "root"
                                :password "root"
                                :maximumPoolSize 8}))
  (def in (async/chan 10000))
  (def stop! (start-pipeline! ds :order [:user_id :amount] 500 2000 in))

  ;; 生产数据
  (async/onto-chan! in (map #(hash-map :user_id % :amount (rand-int 100)) (range 10000)))

  ;; 优雅关闭
  (stop!)
  )

要点回顾

  • x-batch 完全无中间集合,满足 transducer 的“可复用、零分配”承诺;
  • 只在完成函数或批次满/超时两个出口落库,保证 at-least-once;
  • 异常向上抛,由上游重试或进入死信队列,符合国内金融系统“可审计、可补偿”规范;
  • 通过 core.async 的 tap> 把指标打到日志与监控系统,满足国内等保 2.0 的审计要求。

拓展思考

  1. 如果下游是 TiDB 或 OceanBase,批量太大容易打爆 Raft 日志,如何动态调整 batch-size?
    答:在 flush-fn! 里记录单次耗时,用 PID 控制器实时反馈调整 n,实现“自适应批大小”。

  2. 当实例数横向扩展到 32 个 Pod,批次跨 Pod 幂等如何保障?
    答:批次内生成全局唯一 batch_id(雪花算法),写入时带着 ON DUPLICATE KEY UPDATE 或 PostgreSQL 的 ON CONFLICT DO NOTHING,实现幂等。

  3. 需要“恰好一次”语义怎么办?
    答:把批次的 offset 与业务数据放在同一个本地事务表,用 Kafka 的 transactional producer,在事务提交后再提交 offset;失败时利用 Kafka 的 transactional.id 回滚。

  4. 如果面试官追问“为什么不用 partition-all + map”?
    答:partition-all 会生成中间向量,内存随并发度线性膨胀;而 transducer 把状态收敛在单个 volatile 里,无论多少线程同时 reduce,内存占用只与 batch-size 成正比,更适合国内大促 30 万 QPS 的场景。