Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

遇到速率限制,怎样平滑处理?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

先判断是速率或并发触顶,还是配额、余额等需要不同处理的错误。上游有限额时用有界队列和并发控制让请求更均匀。对暂态限流安排有界退避。

讲清原理

若响应给了 Retry-After,把它作为下次尝试的时间约束。对齐 SDK 和业务自己的重试层,避免一层重试好几次再被外层重复。用报错和剩余额度信息调整速率。

例子与易错点

下面模拟一次 429 和一次成功,核对在本次预算内只安排一次重试。

from email.utils import parsedate_to_datetime
from datetime import datetime, timezone
import httpx

replies = iter([429, 200])
planned = []

def serve(request):
    status = next(replies)
    return httpx.Response(status, headers={"Retry-After": "2"} if status == 429 else {})

def server_delay(value, now):
    if value.isdecimal():
        return int(value)
    try:
        return max(0.0, (parsedate_to_datetime(value) - now).total_seconds())
    except (TypeError, ValueError):
        return None

now = datetime(2030, 1, 1, tzinfo=timezone.utc)
with httpx.Client(transport=httpx.MockTransport(serve)) as client:
    reply = client.get("https://example.com/result")
    assert reply.status_code == 429
    pause = server_delay(reply.headers["Retry-After"], now)
    if pause is not None and pause <= 3:
        planned.append(pause)  # The fixture records the wait instead of sleeping.
        reply = client.get("https://example.com/result")
    reply.raise_for_status()
assert planned == [2]
print("one retry was scheduled after the specified delay")

相关题:第 50 题、第 52 题、第 53 题、第 54 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。