实现指数退避重连策略,最大延迟 30 秒,支持随机抖动

解读

国内一线/二线互联网公司面试中,这道题出现的频率极高,本质是“高可用网络编程”与“Node.js 事件循环”结合的实操题。
面试官通常会在 5 分钟内要求候选人:

  1. 手写可运行代码(白板或 IDE 共享)
  2. 解释退避公式、抖动目的、最大延迟截断方式
  3. 说明在 Cluster、Docker、Serverless 场景下的注意事项
  4. 给出单元测试思路(常见追问:如何测“刚好 30 s 边界”)

评分点:

  • 公式正确(指数增长 + 随机抖动 + 封顶)
  • 非阻塞(禁止同步 sleep)
  • 可取消/可重置(防止句柄泄漏)
  • 内存泄漏防护(定时器清理)
  • TypeScript 加分,纯 JS 不扣分

知识点

  1. 指数退避:delay = min(cap, base × 2^n),n 为已重试次数
  2. 全抖动/等抖动/去相关抖动:国内面试官最认“全抖动”——在 [0, computedDelay] 内随机,实测对 TCP 重连最友好
  3. 定时器管理:Node.js 中 setTimeout 返回对象,需 clearTimeout;在 Worker 线程里也可用 self.clearTimeout
  4. 事件驱动:退避器必须继承 EventEmitter,暴露 reconnecting、reconnected、fail、backoff 事件,方便上层做日志、告警、熔断
  5. 资源释放:destroy() 方法需同时关闭定时器、移除所有监听器,防止重复回调
  6. 测试技巧:使用 sinon@latest 的 fake timers 把时间拉到 30 s 边界,断言 setTimeout 被调用时 delay 是否 ≤ 30000 且 ≥ 0

答案

以下代码可直接在 Node.js 18+ 运行,满足“最大 30 s、全抖动、可取消、无泄漏”要求,并附带简单用例。

// backoff.js
const EventEmitter = require('events');

class ExponentialBackoff extends EventEmitter {
  /**
   * @param {Object} [opts]
   * @param {number} [opts.base=100]      首次延迟基数,单位 ms
   * @param {number} [opts.max=30000]     最大延迟,单位 ms
   * @param {number} [opts.factor=2]      指数因子
   * @param {boolean}[opts.jitter=true]   是否启用全抖动
   */
  constructor(opts = {}) {
    super();
    this.base   = opts.base   || 100;
    this.max    = opts.max    || 30000;
    this.factor = opts.factor || 2;
    this.jitter = opts.jitter !== false;
    this.attempt = 0;
    this.timer   = null;
  }

  // 计算下一次延迟
  nextDelay() {
    const exponential = this.base * Math.pow(this.factor, this.attempt);
    const capped      = Math.min(exponential, this.max);
    return this.jitter ? Math.floor(Math.random() * (capped + 1)) : capped;
  }

  // 启动一次退避
  backoff() {
    if (this.timer) return;          // 防止重复调度
    const delay = this.nextDelay();
    this.emit('backoff', this.attempt, delay);
    this.timer = setTimeout(() => {
      this.timer = null;
      this.emit('ready', this.attempt);
    }, delay);
    this.attempt++;
  }

  // 成功连接后重置
  reset() {
    this.attempt = 0;
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  }

  // 彻底销毁
  destroy() {
    this.reset();
    this.removeAllListeners();
  }
}

module.exports = ExponentialBackoff;

// 使用示例:模拟 WebSocket 重连
if (require.main === module) {
  const bo = new ExponentialBackoff({ base: 200, max: 30000 });
  bo.on('backoff', (n, d) => console.log(`第${n}次退避,延迟${d}ms`));
  bo.on('ready',  (n) => {
    console.log(`尝试第${n}次重连…`);
    // 模拟 80% 失败
    if (Math.random() < 0.8) {
      bo.backoff();
    } else {
      console.log('重连成功');
      bo.reset();
    }
  });
  bo.backoff();
}

运行 node backoff.js 可观察延迟逐步逼近 30 s 且带随机抖动。
单元测试(Jest + sinon):

const sinon = require('sinon');
const ExponentialBackoff = require('./backoff');

test('delay 不会超过 30s', () => {
  const clock = sinon.useFakeTimers();
  const bo = new ExponentialBackoff({ base: 100, max: 30000 });
  const spy = sinon.spy();
  bo.on('ready', spy);
  for (let i = 0; i < 20; i++) {
    bo.backoff();
    const delay = bo.nextDelay();
    expect(delay).toBeLessThanOrEqual(30000);
    expect(delay).toBeGreaterThanOrEqual(0);
    clock.tick(delay);
  }
  clock.restore();
});

拓展思考

  1. 去相关抖动(decorrelated jitter)在阿里云 SDK 中被采用,公式为 temp = max(base, temp * 3 * Math.random()); delay = min(max, temp); 可进一步降低碰撞概率,面试时可与面试官讨论选型依据
  2. 在 Serverless(阿里云函数计算)场景,退避器不能常驻内存,需把 attempt 次数和上次时间写入 Redis 或 OSS,下次冷启动续接退避序列
  3. 与断路器(Circuit Breaker)结合:当 attempt 超过阈值(如 10 次)直接熔断,走降级逻辑,而不是无限重试
  4. 多进程 Cluster 场景,退避器应放在主进程,由主进程统一重连,再向 Worker 广播连接句柄,避免所有 Worker 同时重试造成“惊群”
  5. 性能压测:使用 0x 或 clinic.js 观察重连风暴时事件循环延迟,确保 95th 延迟 < 100 ms,防止退避器本身成为瓶颈