Notizen / 09
A 429 backoff for a fixed one-minute window
Rate limits on token APIs are counted in requests, not tokens, and most of them reset on a fixed one-minute boundary rather than a rolling window. That single fact breaks the textbook retry loop: three clients that back off in lockstep wake together, hit the fresh window together, and produce a second 429 wave with your own retries as the cause. This article builds a client that paces requests before they are sent, honours Retry-After when it is returned, jitters every retry, and refuses to retry the failures that cannot succeed. It includes the concurrency arithmetic that predicts an overload before you ship, and the three errors that turn a rate limit into an outage.
The arithmetic you should do before writing the loop
Keep CONCURRENCY × average latency (s) × 60 below your plan's requests per minute. Ten concurrent requests at three seconds each is roughly 200 RPM-equivalent; on a 60 RPM key that is a guaranteed 429 storm, and the retries will make it worse. This number is the whole capacity plan. If you need more throughput than the formula allows, the answer is fewer concurrent workers, a queue, or a higher plan — not a smarter retry.
The client
#!/usr/bin/env python3
"""backoff.py — pace first, retry second, jitter always."""
import asyncio, os, random, sys
from openai import AsyncOpenAI, APIStatusError
RPM = int(os.environ.get("RPM", "60"))
CONCURRENCY = int(os.environ.get("CONCURRENCY", "6"))
TOTAL = int(os.environ.get("TOTAL", "40"))
MODEL = os.environ.get("MODEL", "deepseek-chat")
client = AsyncOpenAI(
api_key=os.environ["MODELRY_API_KEY"],
base_url=os.environ.get("BASE_URL", "https://api.tokenaimodels.com/v1"),
timeout=120.0,
max_retries=0, # this module owns retries; the SDK must not double them
)
class Pacer:
"""Spreads requests evenly instead of letting a burst collide with the window."""
def __init__(self, rpm: int) -> None:
self.interval = 60.0 / max(rpm, 1)
self._lock = asyncio.Lock()
self._next = 0.0
async def wait(self) -> None:
async with self._lock:
now = asyncio.get_running_loop().time()
self._next = max(self._next, now)
delay = self._next - now
self._next += self.interval
if delay > 0:
await asyncio.sleep(delay)
pacer = Pacer(RPM)
sem = asyncio.Semaphore(CONCURRENCY)
RETRYABLE = {429, 502, 503}
async def ask(prompt: str, attempts: int = 4) -> str:
last: Exception | None = None
for attempt in range(attempts):
await pacer.wait()
async with sem:
try:
resp = await client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
max_tokens=200,
)
return resp.choices[0].message.content or ""
except APIStatusError as exc:
last = exc
if exc.status_code not in RETRYABLE or attempt == attempts - 1:
raise
header = exc.response.headers.get("retry-after")
base = float(header) if header else 0.5 * (2 ** attempt)
base = min(base, 30.0)
delay = base + random.uniform(0, base * 0.5) # jitter, per task
print(f" {exc.status_code} -> sleep {delay:.2f}s "
f"(attempt {attempt + 1}/{attempts})", file=sys.stderr)
await asyncio.sleep(delay)
raise last # pragma: no cover
async def main() -> None:
prompts = [f"Name one cause of packet loss, item {i}." for i in range(TOTAL)]
out = await asyncio.gather(*(ask(p) for p in prompts), return_exceptions=True)
ok = sum(1 for r in out if isinstance(r, str))
bad = [r for r in out if isinstance(r, Exception)]
print(f"success={ok} failed={len(bad)}")
for exc in bad[:3]:
print(" ", type(exc).__name__, exc)
if __name__ == "__main__":
asyncio.run(main())
Note what the loop does *not* do: it does not retry inside the concurrency slot. The await pacer.wait() sits outside the semaphore, so a sleeping client is not occupying a worker slot while it waits — otherwise your effective concurrency drops to the number of clients currently failing, which is the opposite of recovery.
Failure 1: every client retries at the same instant
Classic exponential backoff without jitter makes the herd *more* synchronised as it grows: all clients fail together, sleep the same 1 second, and retry together into the same window. The fix is per-attempt randomness — base * (1 + uniform(0, 0.5)) is enough — and a ceiling so a long outage does not produce a five-minute sleep. A full jitter implementation (uniform(0, base)) is better when the fleet is large and latency is not precious.
Failure 2: counting the wrong thing
Two counting errors, both fatal. Retrying without pacing assumes the limit resets per request, when in fact the counter resets on a fixed one-minute boundary: retrying 200 times in ten seconds does not "use up" anything, it just guarantees 200 rejections. And counting tokens when the limiter counts requests means a burst of *small* requests still trips the limit — the limiter does not know or care that your tokens are small. Measure requests per minute, including retries, and include retries in the budget you compare against the limit.
Failure 3: retrying what cannot succeed
400, 401, 402, 403, 404 and 451 are terminal. A 402 on a prepaid gateway means the balance cannot cover the pre-authorisation — retrying it five times with backoff spends thirty seconds to produce the same error, and on a healthy account it usually means max_tokens is set absurdly high, not that the balance is wrong. 451 means the region is not served and no amount of waiting changes it. And the one that costs money: never retry after the first token of a stream. Output has begun, the response is committed, and a retry duplicates text you already paid for.
What to watch when you speak to a gateway instead of OpenAI
Three gateway properties change the shape of this loop. Retry-After: a well-behaved gateway returns it in seconds as the remainder of the current window, and honouring it is strictly better than exponential guesswork — but jitter on top of it, because every client that receives the same header value will wake at the same instant. Limit scope: limits are per key, so five services sharing one key share one budget; issue a key per service and set its own request limit, which also isolates a runaway client from everything else. No token-per-minute ceiling: throughput is bounded by upstream capacity instead, so a burst of very large requests can return 502 even while you are inside the request limit — treat 502 as a queueing signal and shrink concurrency, rather than as a transient to hammer.
Queue first, retry second
A retry loop is a load amplifier: every failure becomes extra requests against a limiter that is already saturated. A queue with a token bucket is the opposite — it makes the send rate a property of your configuration rather than of the server's mood, and 429s become a signal that the configuration is wrong instead of a state to survive. The practical shape is a producer that enqueues work, CONCURRENCY workers that pull from it, and one pacer shared by all workers so the aggregate rate is capped regardless of how many workers you run. Retries then live inside a worker, where they cost one slot rather than the whole fleet.
Log the Retry-After values you receive. A rising sequence across an hour is the clearest early warning that your steady-state rate is above the limit, and it appears well before the failures become user-visible.
Take a key from https://tokenaimodels.com and run backoff.py with RPM set deliberately too high once — watching the retries behave is worth more than reading about them, and the logs will tell you exactly where your real concurrency ceiling sits.
Modelry betreibt eine Plattform, die DeepSeek-Modelle hinter einem HTTP-Endpoint bereitstellt; vorausbezahlte Credits und Steuern werden beim Kauf vom Merchant of Record abgewickelt, und die Datenaufbewahrung ist dokumentiert. Starten Sie mit $0.50 Testguthaben: Schlüssel erstellen.