遇到 429 时,怎样设计重试才不会越重越堵?
查看完整题解
参考回答
直接回答
先降发出请求的并发。若服务器给了 Retry-After,用它作为最早重试时间。该头可给秒数或 HTTP 日期。没给时,按指数退避加一点随机扰动,且设总时间和次数上限。
讲清原理
账号并发未释放时,多个客户端立即重试只会加重拥堵。用有界队列和共享并发预算控制。流式已交付部分内容或工具已执行时,恢复要考虑重复结果或副作用。
例子与易错点
下面用模拟响应测试一次限流和一次成功。示例只演练秒数格式,直接核对等多久。生产实现还要解析日期格式,并把每次请求耗时一起算进总预算。
import httpx
statuses = iter([429, 200])
delays = []
def serve(request):
code = next(statuses)
headers = {"Retry-After": "2"} if code == 429 else {}
return httpx.Response(code, headers=headers)
with httpx.Client(transport=httpx.MockTransport(serve)) as client:
budget = 5.0
for attempt in range(2):
reply = client.post("https://api.deepseek.com/chat/completions",
json={"model": "deepseek-flash",
"messages": [{"role": "user", "content": "你好"}]})
if reply.status_code != 429 or attempt == 1:
reply.raise_for_status()
break
header = reply.headers.get("Retry-After", "")
delay = float(header) if header.isdecimal() else 0.25 * (2 ** attempt)
if delay > budget:
raise TimeoutError("retry would exceed the time budget")
budget -= delay
delays.append(delay) # Tests record the wait without sleeping.
assert delays == [2.0] and reply.status_code == 200
print("one bounded retry scheduled after the promised 2-second wait")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。