如何为断线实现指数退避重连?

解读

国内生产环境对“断线”通常指两类场景:

  1. 服务端内部组件断线,如 FastAPI 依赖的 Redis、MySQL、Kafka、etcd 等;
  2. 客户端到 FastAPI 的长连接(WebSocket、SSE)因网络抖动或网关超时被动断开。

面试官问“指数退避重连”,核心想看三点:

  • 是否理解退避算法对雪崩、打满线程/连接池的防护价值;
  • 能否在 FastAPI 的异步生态里用 Python 原生语法写出“不阻塞主事件循环”的实现;
  • 是否具备可观测性意识(日志、指标、告警),方便运维侧快速定位“重连风暴”。

知识点

  1. 指数退避公式
    delay = base * 2 ** attempt + jitter,其中 jitter∈[0, base] 随机扰动,避免“共振重试”。
  2. asyncio 原生工具
    asyncio.sleep() 代替 time.sleep(),保证事件循环零阻塞;
    asyncio.wait_for() 做超时隔离,防止“半开”连接吊死协程。
  3. FastAPI 依赖注入与生命周期
    把“重连器”做成单例依赖,注册到 app.state.*,在 startup 事件里初始化,在 shutdown 事件里优雅关闭。
  4. 回退上限与熔断
    国内互联网普遍要求“失败 5 次或总耗时 30 s”后直接熔断,走降级逻辑,避免用户侧长时间等待。
  5. 可观测性
    使用 structlog 或 loguru 输出带 trace_id 的 JSON 日志;
    通过 prometheus_client 暴露 retry_total{service="redis"} 指标,接入阿里 SLS、腾讯云 CLS 或自建 VictoriaMetrics。

答案

下面给出“FastAPI + Redis 断线指数退避重连”最小可运行示例,覆盖上述知识点,可直接搬进面试白板或笔试机考。

import asyncio
import logging
import random
from typing import Optional

import aioredis
from fastapi import FastAPI, Depends, HTTPException
from fastapi.responses import PlainTextResponse

# 1. 日志格式化为 JSON,方便采集
logging.basicConfig(
    level=logging.INFO,
    format='{"time": "%(asctime)s", "level": "%(levelname)s", "msg": "%(message)s"}'
)
log = logging.getLogger("redis_retry")

# 2. 退避参数
BASE_DELAY = 1          # 秒
MAX_DELAY  = 30         # 秒
MAX_ATTEMPTS = 5        # 熔断阈值
JITTER_RATIO = 0.1      # 10% 扰动


class RedisPool:
    """线程安全的单例连接池,带指数退避重连"""
    _instance: Optional["RedisPool"] = None
    _lock = asyncio.Lock()

    def __init__(self):
        self._pool: Optional[aioredis.Redis] = None

    @classmethod
    async def get(cls) -> "RedisPool":
        if cls._instance is None:
            async with cls._lock:
                if cls._instance is None:
                    cls._instance = cls()
        return cls._instance

    async def ensure_pool(self) -> aioredis.Redis:
        if self._pool is not None:
            # 轻量级心跳探测,失败立即置空
            try:
                await self._pool.ping()
                return self._pool
            except aioredis.ConnectionError:
                log.warning("Redis ping fail, will reconnect")
                self._pool = None

        # 指数退避重连
        for attempt in range(1, MAX_ATTEMPTS + 1):
            delay = min(BASE_DELAY * (2 ** (attempt - 1)), MAX_DELAY)
            jitter = random.uniform(0, delay * JITTER_RATIO)
            await asyncio.sleep(delay + jitter)

            try:
                log.info("Redis connect attempt=%s", attempt)
                self._pool = aioredis.from_url(
                    "redis://localhost:6379/0",
                    encoding="utf-8",
                    decode_responses=True,
                    socket_connect_timeout=3,
                    socket_timeout=3,
                    max_connections=20,
                )
                await self._pool.ping()
                log.info("Redis connected")
                return self._pool
            except Exception as e:
                log.error("Redis connect fail attempt=%s error=%s", attempt, e)

        # 熔断
        log.error("Redis max attempts exceeded, circuit open")
        raise HTTPException(status_code=503, detail="Redis unavailable")

    async def close(self):
        if self._pool:
            await self._pool.close()
            await self._pool.wait_closed()


# 3. FastAPI 生命周期
app = FastAPI()


@app.on_event("startup")
async def startup():
    await RedisPool.get()


@app.on_event("shutdown")
async def shutdown():
    pool = await RedisPool.get()
    await pool.close()


# 4. 依赖注入,业务路由零感知重连逻辑
async def get_redis() -> aioredis.Redis:
    pool = await RedisPool.get()
    return await pool.ensure_pool()


@app.get("/demo", response_class=PlainTextResponse)
async def demo(redis: aioredis.Redis = Depends(get_redis)):
    await redis.incr("visit")
    val = await redis.get("visit")
    return f"visit={val}"

运行说明:

  • 本地先拉起 Redis,访问 http://localhost:8000/demo 可看到计数正常递增;
  • 手动停掉 Redis,连续刷新页面,日志会打印 attempt=1..5,总耗时约 30 s 后返回 503,符合国内“快速失败”规范;
  • 重新拉起 Redis,再次访问,连接自动恢复,无人工干预。

拓展思考

  1. 多节点 Redis Cluster 场景
    退避对象需细化到“节点”粒度,避免一个分片失败导致整池重连;可引入 asyncio.Semaphore 限制并发重试数,防止“重连风暴”打爆 CPU。
  2. WebSocket 客户端重连
    浏览器到 FastAPI 的 WebSocket 断线,需在 JS 侧实现指数退避;服务端通过 ConnectionManager 维护 user_id→WebSocket 映射,断线后清理脏连接,避免内存泄漏。
  3. 与 Service Mesh 配合
    在 Istio/Linkerd 环境,重试策略往往下沉到 Sidecar,FastAPI 只需返回 5xx 或 grpc-status=UNAVAILABLE,由 Envoy 做退避与熔断,减少业务代码复杂度;但本地仍需保留一层“兜底重连”,防止 Sidecar 本身异常。
  4. 可观测性增强
    把重试次数、延迟耗时写入 OpenTelemetry Span,接入 Jaeger/SkyWalking;国内金融场景还需把 trace_id 回写到 HTTP Response Header,方便网关侧一键溯源。