解释如何结合clojure.core.cache与熔断器实现指数退避

解读

国内高并发面试常把“缓存、熔断、退避”三件事一起问,本质是想确认候选人能否用 Clojure 的不可变数据结构把“失败状态”和“重试节奏”同时管起来。
clojure.core.cache 只提供 TTL、LRU 等纯内存缓存策略,本身不带熔断语义;熔断器需要记录连续失败次数、上次失败时间、当前半开/关闭状态;指数退避则要求每次重试前按 2^n·base 计算等待时间。
三者结合的思路是:把“熔断器状态对象”当作 value 放进 core.cache,key 用“服务名+接口签名”;缓存的 TTL 充当“静默期”,TTL 到期自动淘汰,天然触发半开探测;退避时长不 sleep 线程,而是预计算下一次可重试的绝对时间戳,也写进状态对象。
这样即利用 core.cache 的线程安全、惰性失效机制,又避免引入 Hystrix-Resilience4j 等重量级库,符合国内金融、电商场景“轻量、可控、可审计”的硬性要求。

知识点

  1. clojure.core.cache 的 TTLCache 实现:clojure.core.cache/ttl-cache-factory,依赖 System/currentTimeMillis 判断过期,淘汰是惰性触发(lookup 时才检查)。
  2. 熔断器三态机:Closed(正常)、Open(熔断)、Half-Open(探测);状态字段至少包含:failCount、lastFailTime、nextRetryAt、state。
  3. 指数退避公式:nextRetryAt = now + base·2^min(failCount, maxExponent) + jitter,其中 jitter 防止惊群,maxExponent 防止无限指数爆炸。
  4. 原子托管:用 Atom 持有 Cache 实例,所有更新通过 (swap! cache-atom clojure.core.cache/through-cache key (fnil construct-state nil)) 保证并发安全。
  5. 业务侧唯一需要感知的函数:invoke-with-breaker,内部先查缓存拿状态,若 nextRetryAt 未到直接抛快速失败异常;否则代理调用真实服务,根据结果更新状态并写回缓存。

答案

(ns breaker.core
  (:require [clojure.core.cache :as cache]))

;; ==========================
;; 熔断器状态定义
;; ==========================
(defrecord BreakerState
  [failCount               ; 连续失败次数
   lastFailTime            ; 上次失败时间戳 ms
   nextRetryAt             ; 下次允许探测的时间戳 ms
   state])                 ; :closed :open :half-open

(def base-sleep-ms 100)
(def max-exponent 6)
(def jitter-ms (fn [] (rand-int 50)))

(defn- now [] (System/currentTimeMillis))

(defn- compute-backoff
  "指数退避 + 抖动"
  [failCount]
  (+ base-sleep-ms
     (* (bit-shift-left 1 (min failCount max-exponent)) base-sleep-ms)
     (jitter-ms)))

(defn- open->half-open?
  "判断是否可以进入半开探测"
  [state]
  (and (= (:state state) :open)
       (>= (now) (:nextRetryAt state))))

(defn- new-state
  "构造初始 Closed 状态"
  []
  (->BreakerState 0 0 0 :closed))

;; ==========================
;; 缓存容器:TTL 30s,惰性淘汰
;; ==========================
(def ^:private cache-atom
  (atom (cache/ttl-cache-factory {} :ttl 30000)))

(defn- get-state
  "线程安全地拿到最新状态;若 key 过期则重建"
  [key]
  (swap! cache-atom
         #(cache/through-cache % key
                               (fn [_] (new-state)))))

(defn- put-state
  "把更新后的状态写回缓存"
  [key state]
  (swap! cache-atom
         #(cache/through-cache % key (constantly state))))

;; ==========================
;; 熔断 + 退避 入口
;; ==========================
(defn invoke-with-breaker
  "对 f 做熔断保护,返回 f 的结果或抛快速失败异常"
  [key f]
  (let [st (get-state key)]
    (cond
      ;; 1. 熔断器开着且时间未到,快速失败
      (and (= (:state st) :open)
           (< (now) (:nextRetryAt st)))
      (throw (ex-info "CircuitBreaker OPEN" {:key key :type :circuit-open}))

      ;; 2. 可以进入半开,允许一次探测
      (open->half-open? st)
      (try
        (let [result (f)]
          ;; 探测成功,关闭熔断器
          (put-state key (new-state))
          result)
        (catch Exception e
          ;; 探测仍然失败,重新打开
          (let [failCount (inc (:failCount st))
                nextRetry (+ (now) (compute-backoff failCount))]
            (put-state key
                       (->BreakerState failCount (now) nextRetry :open))
          (throw e)))

      ;; 3. 关闭状态,正常调用
      :else
      (try
        (let [result (f)]
          ;; 成功则重置
          (put-state key (new-state))
          result)
        (catch Exception e
          ;; 失败则累加
          (let [failCount (inc (:failCount st))
                nextRetry (+ (now) (compute-backoff failCount))]
            (put-state key
                       (->BreakerState failCount (now) nextRetry
                                      (if (>= failCount 5) :open :closed)))
          (throw e))))))

;; ==========================
;; 使用示例
;; ==========================
(comment
  ;; 假设支付服务
  (defn pay [order-id]
    (if (< (rand) 0.7)
      (throw (ex-info "Random fail" {}))
      {:status :ok :order-id order-id}))

  ;; 带熔断的调用
  (invoke-with-breaker ::pay-service #(pay 123)))

核心要点:

  1. core.cache 的 TTL 只负责“到期淘汰”,不介入熔断逻辑,但帮我们省了手写清理线程。
  2. 所有状态变更通过 swap! + through-cache 完成,保证多线程下原子性。
  3. 指数退避值只决定 nextRetryAt,不阻塞线程,符合 Clojure 异步哲学,也便于与 core.async 或 manifold 结合。
  4. 业务方只感知 invoke-with-breaker,其余细节对调用者透明,满足国内架构组“可插拔”审查要求。

拓展思考

  1. 多节点部署时,core.cache 是 JVM 本地内存,熔断状态无法共享;可改为把状态写入 Redis 并仍用 TTL 当静默期,或用 etcd 做轻量级共识,面试可主动提及“本地缓存+分布式状态”两层方案。
  2. 若调用方使用 core.async,可把 invoke-with-breaker 封装成 go-block,失败时把异常通道返回,退避用 timeout 通道,实现完全非阻塞。
  3. 对于批量调用,可把 key 设计为“服务+分片号”,实现分片级熔断,避免单接口故障拖垮整个服务。
  4. 审计需求:在 update-state 阶段把每次状态变迁写入 Kafka,下游 Flink 作业实时计算“熔断次数/恢复耗时”SLA,国内金融公司常以此作为 nightly 报表依据。