如何为第三方 SDK 封装异步接口并暴露统一重试策略?

解读

国内生产环境普遍要求“高可用 + 可观测 + 可灰度”。第三方 SDK 往往是同步阻塞实现,直接用在 FastAPI 的异步 Worker(uvicorn + gunicorn)里会耗尽线程池,导致吞吐骤降。面试官想确认三件事:

  1. 能否把“阻塞”变“异步”,不拖垮事件循环;
  2. 能否把“重试”做成策略化、可配置、对业务代码零侵入;
  3. 能否给出可落地的代码骨架,而不是空谈“用 tenacity 就行”。

因此,回答必须体现:线程池/进程池隔离、异步包装、策略抽象、异常标准化、日志追踪、与 FastAPI 依赖注入体系的结合。

知识点

  1. asyncio.get_event_loop().run_in_executor:将同步 SDK 调用丢到线程池,防止阻塞主循环。
  2. tenacity.AsyncRetrying:官方异步重试引擎,支持条件退避、Jitter、熔断统计。
  3. FastAPI 依赖注入:把重试策略做成可替换的依赖,方便单元测试与动态配置。
  4. 结构化日志:使用 structlog 或 loguru,把 trace_id、重试次数、耗时一次性带上,方便 SLS/ELK 检索。
  5. 异常映射:第三方抛的“RequestError”统一转译为业务域的“ExternalServiceException”,避免下游感知实现细节。
  6. 配置中心:通过 pydantic.BaseSettings 对接 Nacos/Apollo,实现热更新重试次数与退避策略,无需重启 Pod。
  7. 单元测试:用 pytest-asyncio + respx/aioresponses 模拟外部超时,验证重试次数与退避曲线。

答案

以下示例把“某短信 SDK”封装成异步接口,暴露统一重试策略,可直接放入 FastAPI 项目。

# settings.py
from pydantic import BaseSettings, Field
class Settings(BaseSettings):
    sms_max_retry: int = 3
    sms_base_backoff: float = 0.6
    sms_max_backoff: float = 6.0
    sms_jitter: bool = True
    sms_timeout: int = 5          # 秒
settings = Settings()

# exceptions.py
class ExternalServiceException(Exception):
    """第三方服务异常,业务层只捕获它即可"""
    pass

# retry_policy.py
import asyncio
from typing import Callable, Any
from tenacity import AsyncRetrying, stop_after_attempt, wait_exponential_jitter, retry_if_exception_type
from functools import wraps

def async_retry(fn: Callable) -> Callable:
    """装饰器:把任意异步函数包装成带统一重试策略"""
    r = AsyncRetrying(
        stop=stop_after_attempt(settings.sms_max_retry),
        wait=wait_exponential_jitter(
            initial=settings.sms_base_backoff,
            max=settings.sms_max_backoff,
            jitter=settings.sms_jitter
        ),
        retry=retry_if_exception_type((ExternalServiceException,)),
        reraise=True
    )

    @wraps(fn)
    async def wrapper(*args, **kwargs) -> Any:
        async for attempt in r:
            with attempt:
                return await fn(*args, **kwargs)
    return wrapper

# client.py
import asyncio
from concurrent.futures import ThreadPoolExecutor
import thirdparty_sms_sdk   # 官方同步 SDK
from retry_policy import async_retry
from exceptions import ExternalServiceException
import structlog

logger = structlog.get_logger()
executor = ThreadPoolExecutor(max_workers=40)

class AsyncSmsClient:
    def __init__(self):
        self.client = thirdparty_sms_sdk.Client(timeout=settings.sms_timeout)

    @async_retry
    async def send_sms(self, phone: str, content: str) -> str:
        loop = asyncio.get_event_loop()
        try:
            # 阻塞调用丢到线程池
            msg_id = await loop.run_in_executor(
                executor,
                self.client.send,
                phone,
                content
            )
            logger.info("sms_sent", phone=phone, msg_id=msg_id)
            return msg_id
        except thirdparty_sms_sdk.TimeoutError as e:
            logger.warning("sms_timeout", phone=phone, exc_info=True)
            raise ExternalServiceException("sms timeout") from e
        except thirdparty_sms_sdk.RequestError as e:
            logger.warning("sms_request_error", phone=phone, exc_info=True)
            raise ExternalServiceException("sms request error") from e

# deps.py
from functools import lru_cache
from client import AsyncSmsClient

@lru_cache
def get_sms_client() -> AsyncSmsClient:
    return AsyncSmsClient()

# main.py
from fastapi import FastAPI, Depends
from deps import get_sms_client
from client import AsyncSmsClient

app = FastAPI(title="SMS 服务")

@app.post("/sms")
async def send_sms(phone: str, content: str,
                   client: AsyncSmsClient = Depends(get_sms_client)):
    msg_id = await client.send_sms(phone, content)
    return {"msg_id": msg_id}

要点回顾

  1. 线程池隔离:executor 大小与 uvicorn worker 数量联动,K8s 侧通过环境变量注入。
  2. 重试策略完全配置化,上线后可在配置中心动态调大“sms_max_retry”做临时容错。
  3. 所有异常收敛到 ExternalServiceException,业务层只需捕获它即可,符合“整洁架构”思想。
  4. 日志带上 trace_id(通过 FastAPI middleware 注入),方便在灰度发布时对比重试曲线。

拓展思考

  1. 如果第三方 SDK 提供异步版本,但协议是私有二进制,TCP 长连接,如何与 tenacity 结合做“连接级”重试而不是“请求级”重试?
  2. 当重试仍然失败时,如何在不写文件的情况下把原始请求入队到 Redis Stream,实现“异步兜底”?
  3. 在 ServiceMesh 场景下,重试策略是放在 Sidecar(Envoy)还是业务层?各自的观测性与事务一致性如何保证?
  4. 若 SDK 返回“限流”错误码,如何与 tenacity 的“retry_if_result”结合,实现“只针对特定错误码退避”?
  5. 单元测试时,如何 mock ThreadPoolExecutor 的真实耗时,确保重试间隔符合预期,而不引入 sleep 导致测试变慢?