Retry Policy
解释远程调用何时值得重试,以及如何用错误分类、时间预算、Backoff + Jitter 与幂等性避免重试放大故障;Agent、模型与工具调用是重点应用场景。
#concept
#growing
#backend
#ai
#reliability
[!info] related notes
Retry Policy
[!abstract] 一句话定义 Retry Policy 决定哪些失败值得再次尝试、由哪一层重试、最多付出多少时间和流量,以及重复执行是否安全。Retry 不是错误处理的默认动作,而是一项会放大负载和副作用的受预算策略。
先分类,再重试
| 错误类型 | 示例 | 常见动作 |
|---|---|---|
| Transient | 连接重置、部分 5xx、短暂 429 | 有限重试 + Backoff |
| Permanent Configuration | 401、无效 Endpoint、缺少模型 | 修配置,不原样重试 |
| Validation | 400、Schema 不合法 | 修参数或拒绝 |
| Authorization | 403、Tenant 越权 | Fail Closed / Audit |
| Business Conflict | 状态已变化、版本冲突 | 重新读取状态再决策 |
| Semantic Failure | 无证据、工具选错、答案不合格 | Repair、换策略、Abstain |
| Unknown Outcome | 写请求超时、响应丢失 | Reconcile / Idempotent Retry |
HTTP Status 只是线索;最终还要看 API 契约和操作语义。
一个完整 Retry Decision
Did the operation fail?
→ Is the error retryable?
→ Is the operation safe to repeat?
→ Is this layer the retry owner?
→ Is deadline / retry budget remaining?
→ Is downstream currently healthy enough?
→ Wait with backoff + jitter
→ Retry or fallback / fail
缺少其中任何一步,都可能把小故障放大成事故。
Retry Budget
至少限制:
- Max Attempts;
- Total Elapsed Time;
- Remaining Deadline;
- Per-request Retry Cost;
- System-wide Retry Traffic;
- Provider / Tenant / Tool Quota。
original traffic 1000 rps
× 3 retries at every layer
→ can become many times larger
Retry Amplification
如果 Client、Gateway、Service 和 SDK 都重试:
每层最多 3 次尝试(含首次):3 × 3 × 3 × 3 = 81 次底层调用
若每层是首次 + 3 次重试:4 × 4 × 4 × 4 = 256 次底层调用
应指定一个主要 Retry Owner,其他层只在自己能确定语义、且不会叠加时重试。
幂等与未知结果
安全重试的核心不是“POST 不能重试”,而是操作是否具备稳定请求身份和业务去重:
Idempotency-Key
+ unique constraint / state machine
+ persisted result
→ repeated request returns same logical outcome
写请求超时后,先查询已有结果或用同一 Key 重试,不能生成新 Key 再创建一次。
Backoff、Jitter 与 Retry-After
Retry 之间应使用 指数退避 和 Jitter。服务端返回 Retry-After 时优先遵守,但不能超过总 Deadline。
立即、固定间隔或无限重试都会增加同步冲击和尾延迟。
Agent 场景中的两类失败
Execution Failure
- Provider 429 / 5xx;
- Tool Timeout;
- 网络断开;
- 临时数据库错误。
可根据幂等和预算重试。
Semantic Failure
- Tool 参数虽然合法但选错对象;
- Evidence 不足;
- Structured Output 不满足业务约束;
- Judge 判定不合格。
这类问题通常需要 Context Repair、重新规划、换工具、Ask User 或 Abstain;原样重放同一 Prompt 可能没有价值。
Retry 与 Fallback
没有固定“永远先重试三次再 Fallback”的规则。决策取决于:
- Error Type;
- Latency Budget;
- Fallback Capability;
- Cost;
- Provider Health;
- Quality / Safety Contract。
例如 401 应按已定义的凭证刷新协议恢复或失败,不能随意换身份绕过权限;短暂 503 可以先一次快速重试;高延迟交互可能直接切低延迟兼容模型。
观测重点
attempt count / retry rate
success after retry
retry traffic amplification
backoff duration
error class
remaining deadline
fallback after retry
unknown outcome / reconciliation
设计检查表
- 错误分类来自契约,不只看 Status Code。
- 写操作具有幂等或 Reconciliation 路径。
- Max Attempts、Total Time 和系统级 Retry Budget 明确。
- 只有一个主要 Retry Owner。
- 使用 Backoff + Jitter,并尊重
Retry-After。 - Circuit Breaker 打开时不会继续排队重试。
- Semantic Failure 不被误当网络瞬时错误。
- Trace 记录每次 Attempt 与最终决策。