在 Redis Pub/Sub 中实现水平扩展订阅服务,并保证消息不丢失

解读

国内高并发业务(秒杀、直播弹幕、实时风控)普遍把 Redis Pub/Sub 当“轻量总线”用,但面试官真正想挖的是“Redis 原生 Pub/Sub 的坑”:

  1. 无持久化:消息既不在 AOF 也不在 RDB,主从切换即丢。
  2. 无 ACK:消费者崩溃即丢。
  3. 无队列模型:广播给所有在线客户端,离线客户端直接错过。
  4. 水平扩展=多实例,但 Redis 会把每条消息复制到所有已订阅连接,重复消费、顺序乱、扩容难。

因此“水平扩展+不丢”必须跳出“纯 Pub/Sub”,用“Redis 数据结构 + 外部机制”补位,并给出可落地的 Node.js 代码骨架。

知识点

  1. Redis 原生 Pub/Sub 语义与缺陷
  2. Stream(RadixTree + 消息 ID)的持久化、ACK、消费者组
  3. Node.js 侧 ioredis 对 Cluster 的订阅重定向与 Stream API
  4. 背压控制:Node.js Transform + highWaterMark
  5. 幂等键设计:业务主键 + 雪花 ID
  6. 故障恢复:Pending Entries List(PEL)重新认领
  7. 监控指标:Redis 延迟、Stream 长度、消费滞后(lag)
  8. 国内云厂商 Redis 版差异:腾讯云 CKV 不支持 Stream 需自建,阿里云 Tair 支持但需开启“企业版”

答案

核心思路:放弃 Pub/Sub,用 Redis Stream + 消费者组;Node.js 侧按“分片消费”做水平扩展,保证“至少一次”并借助幂等做到“实际不丢”。

  1. Redis 侧预建 Stream
XGROUP CREATE mq.order paid_cons_group $ MKSTREAM
  1. Node.js 消费实例模板(ioredis,Cluster 模式)
import Redis from 'ioredis';
import { once } from 'events';

const redis = new Redis.Cluster([
  { host: '192.168.0.11', port: 7000 },
  { host: '192.168.0.12', port: 7000 }
], { enableOfflineQueue: false });

const group = 'paid_cons_group';
const consumer = `node-${process.pid}-${Date.now() % 10000}`;
const streamKey = 'mq.order';
const BLOCK = 5000;          // 5s 阻塞读
const COUNT = 50;            // 每批拉 50 条,控制内存
const IDEMPOTENT_TTL = 3600; // 幂等窗口 1h

async function processBatch(messages) {
  const pipe = redis.pipeline();
  messages.forEach(([id, fields]) => {
    const bizId = fields.orderId;
    // 幂等键:stream:order:{orderId}
    pipe.set(`stream:order:${bizId}`, '1', 'PX', IDEMPOTENT_TTL, 'NX');
  });
  const flags = await pipe.exec();
  const toAck = [];
  messages.forEach(([id, fields], idx) => {
    if (flags[idx][1] === 'OK') {          // 首次处理
      toAck.push(id);
      // 业务逻辑:写 DB、发消息、调接口
      handleBusiness(fields);
    }
  });
  if (toAck.length) {
    await redis.xack(streamKey, group, ...toAck);
  }
}

async function claimStale() {
  // 每 30s 把超过 60s 未 ACK 的消息抢回来
  const stale = await redis.xpending(streamKey, group, '-', '+', 100);
  if (!stale.length) return;
  const toClaim = stale.map(e => e.messageId);
  const claimed = await redis.xclaim(streamKey, group, consumer, 60000, ...toClaim);
  if (claimed.length) await processBatch(claimed);
}

(async () => {
  // 主循环
  for (;;) {
    try {
      const reply = await redis.xreadgroup(
        'GROUP', group, consumer,
        'COUNT', COUNT,
        'BLOCK', BLOCK,
        'STREAMS', streamKey, '>'
      );
      if (reply && reply[0][1].length) {
        await processBatch(reply[0][1]);
      }
      // 定期抢滞留
      if (Math.random() < 0.05) await claimStale();
    } catch (e) {
      console.error('消费异常', e);
      await once(redis, 'ready'); // 等待重连
    }
  }
})();

function handleBusiness(fields) {
  // 落库、写缓存、发 MQ 等
}
  1. 水平扩展
  • 启动 N 个容器/Pod,K8s HPA 按 CPU>60% 或 lag>2000 条扩容。
  • 每个实例用唯一 consumer name,Redis 自动均分。
  • 缩容时实例优雅退出:先 redis.quit() 触发 TCP 断开,PEL 由其他实例 60s 后自动认领。
  1. 不丢消息保障
  • 生产方:业务事务提交后 XADD,失败抛异常触发回滚。
  • 消费方:先 SET NX 幂等再 ACK;崩溃重启后重复消费但因幂等键不会重复写库。
  • 监控:Prometheus exporter 采集 stream_length、consumer_lag,lag>5000 告警。
  1. 若公司版本低于 5.0 用 List + BRPOPLPUSH 模拟,消费完 LREM 备份列表;或直接用 RocketMQ/RabbitMQ,答“技术选型”时主动说出权衡,体现全面性。

拓展思考

  1. 顺序性 vs 并行度:Stream 保证分区内顺序,但单分区热点仍可能瓶颈;可按业务 key 做“逻辑分片”建多个 Stream,Node.js 侧用 Round-Robin 写入。
  2. 灰度升级:利用 consumer group 的“空闲实例”策略,先起新版本 consumer,旧版本流量自然降到 0 后下线,实现零停机。
  3. 跨国多活:国内主写、海外只读,Stream 通过 DTS/XDP 同步到海外 Redis,海外消费者组读本地副本,降低 200ms 跨境延迟。
  4. 成本优化:消息带 TTL,XTRIM MAXLEN ~ 100000 定期裁剪;冷数据转存到 S3 供离线分析,Redis 只保留热数据,内存节省 60%。