Skip to content

Commit 92404c0

Browse files
committed
fix(api): retry a 503 only with Retry-After, and honor Retry-After
A 503 means the server is shedding load, so blind retries add to the overload. Retry it only when the server says when via Retry-After. Any retried response that carries Retry-After waits that long instead of the jittered backoff.
1 parent d812086 commit 92404c0

4 files changed

Lines changed: 77 additions & 8 deletions

File tree

‎livekit-api/livekit/api/_failover.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414

1515
"""Region failover for the Twirp API clients.
1616
17-
On a retryable failure (any transport error or HTTP 5xx) the client discovers
17+
On a retryable failure (any transport error, or an HTTP 5xx other than a 503
18+
without Retry-After) the client discovers
1819
alternative LiveKit Cloud regions via ``/settings/regions`` and replays the
1920
request against the next region, with jittered exponential backoff. 4xx responses are
2021
returned immediately.
@@ -24,6 +25,7 @@
2425

2526
import random
2627
import time
28+
from email.utils import parsedate_to_datetime
2729
from dataclasses import dataclass
2830
from typing import Dict, List, Optional
2931
from urllib.parse import urlparse
@@ -73,6 +75,20 @@ def backoff(attempt: int, base: float) -> float:
7375
return random.random() * base * (2**attempt)
7476

7577

78+
def parse_retry_after(header: Optional[str]) -> Optional[float]:
79+
"""Parses a Retry-After header (delay-seconds or an HTTP-date) to seconds."""
80+
value = (header or "").strip()
81+
if not value:
82+
return None
83+
if value.isdigit():
84+
return float(value)
85+
try:
86+
date = parsedate_to_datetime(value)
87+
except (TypeError, ValueError):
88+
return None
89+
return max(0.0, date.timestamp() - time.time())
90+
91+
7692
def to_http(url: str) -> str:
7793
"""Normalizes a region URL to an http(s) scheme (ws -> http, wss -> https)."""
7894
if url.startswith("ws"):

‎livekit-api/livekit/api/twirp_client.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
host_key,
3030
is_cloud_api,
3131
origin_of,
32+
parse_retry_after,
3233
pick_next,
3334
)
3435
from .version import __version__
@@ -226,7 +227,8 @@ async def request(
226227
timeout: Optional[aiohttp.ClientTimeout] = None,
227228
) -> T:
228229
"""Issues a Twirp request, failing over to alternative regions on
229-
retryable errors. On any transport error or HTTP 5xx it discovers
230+
retryable errors. On any transport error or HTTP 5xx (a 503 only with
231+
Retry-After, which then sets the delay) it discovers
230232
regions via ``/settings/regions`` and replays the request — body and
231233
headers intact — against the next untried region, with jittered
232234
exponential backoff. A 4xx is returned immediately."""
@@ -261,6 +263,7 @@ async def request(
261263

262264
transport_exc: Optional[BaseException] = None
263265
retryable_status: Optional[int] = None
266+
retry_after: Optional[float] = None
264267
error_data: Dict = {}
265268
try:
266269
async with self._session.post(
@@ -273,8 +276,10 @@ async def request(
273276
error_data = await resp.json()
274277
except Exception:
275278
error_data = {}
276-
if resp.status < 500:
277-
# 4xx is terminal.
279+
retry_after = parse_retry_after(resp.headers.get("Retry-After"))
280+
# A 4xx is terminal. A 503 is the server shedding load, so
281+
# it is retried only when Retry-After says when.
282+
if resp.status < 500 or (resp.status == 503 and retry_after is None):
278283
raise self._server_error(error_data, resp.status)
279284
retryable_status = resp.status
280285
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
@@ -304,7 +309,9 @@ async def request(
304309
reason,
305310
next_origin,
306311
)
307-
await asyncio.sleep(backoff(attempt, self._failover_backoff))
312+
await asyncio.sleep(
313+
retry_after if retry_after is not None else backoff(attempt, self._failover_backoff)
314+
)
308315
attempted.add(host_key(next_origin))
309316
current_origin = next_origin
310317
current_base = next_origin

‎tests/api/test_failover.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,8 @@ async def _call(
7474
headers = {
7575
"authorization": "Bearer test-token",
7676
# These tests exercise failover, not authz; skip the mock's permission check.
77-
"X-Lk-Mock": json.dumps({"skipAuth": True, **mock}),
77+
# The mock fails with a 503 by default, which is retried only with Retry-After.
78+
"X-Lk-Mock": json.dumps({"skipAuth": True, "failStatus": 502, **mock}),
7879
**(extra_headers or {}),
7980
}
8081
return await client.request("RoomService", "CreateRoom", CreateRoomRequest(), headers, Room)

‎tests/api/test_failover_unit.py‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,13 @@
2626
from aiohttp.test_utils import TestServer
2727

2828
from livekit.api import CreateRoomRequest, Room
29-
from livekit.api._failover import FAILOVER_MAX_ATTEMPTS, backoff, failover_attempts
30-
from livekit.api.twirp_client import TwirpClient
29+
from livekit.api._failover import (
30+
FAILOVER_MAX_ATTEMPTS,
31+
backoff,
32+
failover_attempts,
33+
parse_retry_after,
34+
)
35+
from livekit.api.twirp_client import ServerError, TwirpClient
3136

3237
Handler = Callable[[int, web.Request], "web.StreamResponse | None"]
3338

@@ -142,6 +147,46 @@ def behave(attempt: int, request: web.Request):
142147
assert len(attempts) == 2
143148

144149

150+
def test_503_without_retry_after_not_retried():
151+
"""A 503 without Retry-After is the server shedding load, so it is terminal."""
152+
153+
def behave(attempt: int, request: web.Request):
154+
return web.json_response({"code": "unavailable", "msg": "busy"}, status=503)
155+
156+
attempts: List[int] = []
157+
with pytest.raises(ServerError):
158+
asyncio.run(_call_single_host(behave, attempts))
159+
assert len(attempts) == 1
160+
161+
162+
def test_503_with_retry_after_retried():
163+
"""A 503 with Retry-After is retried."""
164+
165+
def behave(attempt: int, request: web.Request):
166+
if attempt == 0:
167+
return web.json_response(
168+
{"code": "unavailable", "msg": "busy"}, status=503, headers={"Retry-After": "0"}
169+
)
170+
return _ok(request)
171+
172+
attempts: List[int] = []
173+
room = asyncio.run(_call_single_host(behave, attempts))
174+
assert room.name == "r"
175+
assert len(attempts) == 2
176+
177+
178+
def test_parse_retry_after(monkeypatch: pytest.MonkeyPatch):
179+
"""Retry-After is delay-seconds or an HTTP-date; anything else is ignored."""
180+
assert parse_retry_after(None) is None
181+
assert parse_retry_after("") is None
182+
assert parse_retry_after("soon") is None
183+
assert parse_retry_after("0") == 0.0
184+
assert parse_retry_after(" 2 ") == 2.0
185+
monkeypatch.setattr("time.time", lambda: 1792567680.0) # Wed, 21 Oct 2026 07:28:00 GMT
186+
assert parse_retry_after("Wed, 21 Oct 2026 07:28:03 GMT") == pytest.approx(3.0)
187+
assert parse_retry_after("Wed, 21 Oct 2026 07:27:00 GMT") == 0.0
188+
189+
145190
@pytest.mark.parametrize(
146191
"host, expected",
147192
[

0 commit comments

Comments
 (0)