如何为虚拟服务添加超时与重试策略?
问题
如何为虚拟服务添加超时与重试策略?
知识点
- FastAPI 的异步本质:基于 Starlette 的 asyncio 事件循环,任何阻塞调用必须用 await 包裹,否则超时机制不会生效。
- httpx.AsyncClient:国内主流生产环境均用 httpx 做异步 HTTP 调用,支持 timeout、limits、transport 层参数,可无缝接入 FastAPI 的依赖注入体系。
- 超时粒度:connect、read、write、pool 四类,国内云厂商(阿里云、腾讯云、华为云)内网 SLA 一般 500 ms,公网 3 s,面试时必须给出可配置化方案。
- 重试策略:
- 异常分类:可重试(超时、5xx、429)与不可重试(4xx 除 429)。
- 退避算法:线性、固定、指数退避,国内面试常问“指数退避是否会导致雪崩”,需回答“加 jitter 打散”。
- 重试边界:必须设置 max_attempts 与 max_total_time,防止无限重试。
- 中间件还是依赖:
- 中间件面向全局,粒度粗;
- 依赖注入面向单接口,粒度细,可结合业务做灰度、熔断、限流。
- 观测与告警:Prometheus + Grafana 组合是国内事实标准,必须暴露重试次数、耗时直方图,方便 SRE 复盘。
- 熔断降级:阿里 Sentinel、美团 Hystrix-go 的 Python 版(pybreaker)常被追问,回答“重试与熔断需配合使用,否则重试风暴会把下游打挂”。
答案
生产级落地分五步,代码可直接写进简历项目。
第一步,统一封装异步客户端:
# app/clients.py
import httpx
from functools import lru_cache
from tenacity import (
retry,
stop_after_attempt,
wait_exponential_jitter,
retry_if_exception_type,
before_sleep_log,
)
import logging
log = logging.getLogger(__name__)
class VirutalServiceClient:
def __init__(self, base_url: str, timeout: float, max_attempts: int):
# 国内云厂商建议 keepalive 30 s,连接池 100 足够
limits = httpx.Limits(max_keepalive_connections=100, max_connections=200)
self.client = httpx.AsyncClient(
base_url=base_url,
timeout=httpx.Timeout(timeout, connect=timeout*0.5, read=timeout),
limits=limits,
)
self.max_attempts = max_attempts
@retry(
reraise=True,
stop=stop_after_attempt(max_attempts),
wait=wait_exponential_jitter(initial=0.2, max=2, jitter=True),
retry=retry_if_exception_type((httpx.TimeoutException, httpx.HTTPStatusError))
& (lambda e: getattr(e.response, "status_code", 0) in (429, 500, 502, 503, 504)),
before_sleep=before_sleep_log(log, logging.INFO),
)
async def invoke(self, method: str, path: str, **kwargs):
resp = await self.client.request(method, path, **kwargs)
resp.raise_for_status()
return resp
async def close(self):
await self.client.aclose()
@lru_cache
def get_vs_client() -> VirutalServiceClient:
from app.config import settings
return VirutalServiceClient(
base_url=settings.VS_BASE_URL,
timeout=settings.VS_TIMEOUT,
max_attempts=settings.VS_MAX_RETRY,
)
第二步,注册到 FastAPI 生命周期,防止内存泄漏:
# app/main.py
from fastapi import FastAPI
from app.clients import get_vs_client
app = FastAPI(title="Demo", version="1.0.0")
@app.on_event("startup")
async def startup():
# 预热连接池
get_vs_client()
@app.on_event("shutdown")
async def shutdown():
await get_vs_client().close()
第三步,在依赖中注入,可做灰度:
# app/deps.py
from fastapi import Depends
from app.clients import get_vs_client, VirutalServiceClient
async def vs_client() -> VirutalServiceClient:
return get_vs_client()
第四步,业务接口使用:
# app/routers/order.py
from fastapi import APIRouter, Depends
from app.deps import vs_client
from app.clients import VirutalServiceClient
router = APIRouter()
@router.post("/order")
async def create_order(client: VirutalServiceClient = Depends(vs_client)):
# 超时+重试对业务透明
r = await client.invoke("POST", "/v1/inventory/reserve", json={"sku": 123})
return r.json()
第五步,观测:
# app/metrics.py
from prometheus_client import Counter, Histogram
retry_total = Counter("vs_retry_total", "retry times", ["status"])
latency_hist = Histogram("vs_request_duration_seconds", "latency")
在 invoke 里加埋点即可。
拓展思考
- 如果虚拟服务是 gRPC 而非 HTTP,超时与重试策略怎么做?
答:使用 grpc.aio 原生拦截器,retry_policy 在 service proto 的 method_config 里声明,国内 Istio 环境会覆盖,需要与运维对齐。 - 重试风暴怎么防?
答:- 指数退避 + jitter 打散;
- 单实例并发限流(asyncio.Semaphore);
- 集群维度用 Redis 信号量或 Sentinel 熔断。
- 如何与配置中心(Apollo、Nacos)联动,实现热更新超时与重试参数?
答:把 timeout、max_attempts 放到配置中心,FastAPI 用 watch 接口监听变更,收到事件后重新实例化 VirutalServiceClient 并替换单例缓存。 - 面试陷阱:
- “await 忘记加” 导致超时无效;
- “重试 4xx” 被追问幂等性,必须说明业务层保证或使用幂等键;
- “日志打印敏感 header” 被安全团队挑战,需脱敏。