A call to a model provider fails in ordinary ways: a 429 for a rate limit, a 500 or 503 when the provider is overloaded, an answer that never arrives, a dropped connection. A client that does nothing hands these to the user. A client that retries without limits adds load to a provider that is already down.
I built a client that copes, in Python 3.12 with the standard library only, and sent the same 96 calls through four versions of it. Provider A fails at random and has an outage of 2.5 seconds. Provider B is healthy. Both are local stubs, so every failure and latency below is simulated:
| Scenario | Calls that succeeded | p95 latency | Requests at A during the outage |
|---|---|---|---|
| 1. No protection | 51 of 96 | 4,011 ms | 40 |
| 2. Retries, no jitter | 76 of 96 | 2,656 ms | 117 |
| 3. Jitter, Retry-After, retry budget, deadline | 52 of 96 | 873 ms | 56 |
| 4. All of that, plus circuit breaker and fallback | 94 of 96 | 878 ms | 9 |
The two failures in scenario 4 are invalid requests, sent on purpose. No retry fixes those.
What goes wrong, and why naive retries make it worse#
The failures a client sees:
- 429 Too Many Requests. A rate limit. RFC 6585 says the response may carry
Retry-After, the time to wait. - 500, 502, 503, 504. The provider or a proxy failed. RFC 9110 defines 503 as temporary overload or maintenance, also with an optional
Retry-After. - A slow answer or a dropped connection. Only a timeout turns a missing answer into something you can act on.
- 400, 401, 403. The request or the credentials are wrong. The same request fails again.
Retries help with the first three. During an outage, though, every failing call sends up to four requests instead of one, when the provider has the least capacity. Fixed delays add spikes: calls that failed together retry together. In scenario 2, provider A received 117 requests during its outage instead of 40, and up to 11 retries arrived within 20 ms.
How the client works#
Six measures, with the settings of the run. The time scale is compressed so a scenario takes seconds.
- Timeouts. 0.6 s per attempt, 3 s per call, waits included.
- What to retry. 408, 429, 500, 502, 503, 504, timeouts and dropped connections. Nothing else.
- Backoff. Full jitter: a random wait between zero and
min(1.0, 0.2 * 2**attempt)seconds. WithRetry-After, that value plus up to 0.2 s. - Retry budget per provider. Each first attempt adds 0.2 tokens, each retry costs one, with 5 at the start and 10 at most. Retries stay near 20 percent of the traffic.
- Circuit breaker per provider. Opens after 5 unhealthy results in a row, stays open for 1 s, then lets one probe through.
- Fallback. The next provider takes the call when the breaker is open, attempts or budget run out, or the deadline leaves no room for another wait and attempt.
The animation follows one call through these rules: a 429, a wait, a 503 that opens the breaker, and the fallback to provider B.
One call through the resilient client
A call hits a 429 at provider A, waits for Retry-After, then gets a 503 that opens the breaker of A, and falls back to provider B, which answers. Explanatory, not telemetry.
Not started10 steps, listed below.
- 1Your service calls the client. The deadline of 3 s starts now and covers every attempt and every wait.
- 2Breaker A is closed, so attempt 1 goes to provider A with a timeout of 0.6 s.
- 3A answers 429 with Retry-After: 1. A rate limit is worth a retry, and the breaker counts it as healthy.
- 4The client takes one token from the retry budget of A and waits the Retry-After second plus a little jitter.
- 5Attempt 2 goes to provider A.
- 6This time A answers 503. A server error counts as unhealthy.
- 7It is the fifth unhealthy result in a row at A, counting other calls, so breaker A opens for 1 s.
- 8With breaker A open, the client falls back: attempt 1 at provider B, within the same deadline.
- 9Provider B answers 200. The breaker of B records a healthy result.
- 10The client returns the answer of B to your service. The caller never saw the 429 or the 503.
Conceptual illustration of the order of execution. It is not measured telemetry, and the animation speed does not represent real latency.
Read the breaker figure from the closed state; the bottom strip is breaker A in scenario 4.
The breaker counts 429 and other 4xx answers as healthy: the provider answered, so it is up. Backoff and budget handle the 429.
Two things to settle before you add a retry layer#
The SDK may already retry. The official OpenAI Python library, for example, as of 28 November 2026, retries certain errors 2 times by default with a short exponential backoff: connection errors, 408, 409, 429 and 5xx. Its default timeout is 10 minutes, and timed-out requests are retried too. Its source (opens in a new tab) also honours Retry-After up to two minutes. Put this client on top of it unchanged and one call can become 4 times 3 requests per provider. Set max_retries=0 on the SDK, or count its retries in your budget.
A timed-out request may still have run. A model call is a POST, which RFC 9110 does not count as idempotent. It says a client should not retry such a request automatically unless it knows the request is safe to repeat or was never applied. When your client gives up after 0.6 s, the provider may still finish and charge for the work, and the retry runs it again. For text generation that is mostly cost. When the call has effects outside the answer, make those effects idempotent on your side.
Streaming is out of scope: after the first tokens, a retry restarts the answer.
Where it helps, and where it does not#
It fits a service or a batch job that calls one or two providers directly, and pays off most when a second deployment with a compatible model gives fallback somewhere to go. Mind the limits:
- Behind a gateway that already retries, the layers multiply. Let one layer retry.
- Fallback to another model changes the answer. Quality, prompt format, context window, price and data residency can differ. Choose the fallback target deliberately.
- Each process keeps its own breaker and budget.
- Tool calls inside an agent loop and server-side limits need their own handling.
The build#
The whole client is the three blocks below, 184 lines. The first holds the error type, the policy and the Retry-After parser, which accepts both forms RFC 9110 allows: a number of seconds or an HTTP date.
"""A resilient client for model provider calls. Python 3.12, standard library only."""
import email.utils
import http.client
import json
import random
import threading
import time
from dataclasses import dataclass
from datetime import timezone
RETRYABLE = {408, 429, 500, 502, 503, 504} # plus timeouts and dropped connections
class ProviderError(Exception):
def __init__(self, provider, status, retry_after=None):
super().__init__(f"{provider}: {status}")
self.status, self.retry_after = status, retry_after
self.retryable = status in RETRYABLE or not isinstance(status, int)
self.unhealthy = not isinstance(status, int) or status >= 500
@dataclass
class Policy:
attempt_timeout: float = 0.6 # seconds per attempt
deadline: float = 3.0 # seconds per call, all attempts and waits included
max_attempts: int = 4 # per provider
base_delay: float = 0.2
max_delay: float = 1.0
jitter: bool = True
retry_after: bool = True # honour Retry-After
budget: bool = True
breaker: bool = True
fallback: bool = True
def parse_retry_after(value):
"""RFC 9110: delay-seconds or an HTTP-date. Returns seconds, or None."""
if value is None:
return None
value = value.strip()
if value.isascii() and value.isdigit():
return float(value)
try:
when = email.utils.parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
if when.tzinfo is None:
when = when.replace(tzinfo=timezone.utc) # asctime dates are UTC
return max(0.0, when.timestamp() - time.time())The retry budget and the breaker each hold a lock, because many calls share them. The breaker ignores results while it is open: those are late answers to requests sent before it opened. That holds as long as open_for is longer than the attempt timeout.
class RetryBudget:
"""Retries may add at most `ratio` of the first attempts, plus a small reserve."""
def __init__(self, ratio=0.2, reserve=5.0, cap=10.0):
self.ratio, self.cap, self.tokens = ratio, cap, reserve
self.lock = threading.Lock()
def on_first_attempt(self):
with self.lock:
self.tokens = min(self.cap, self.tokens + self.ratio)
def try_spend(self):
with self.lock:
if self.tokens >= 1:
self.tokens -= 1
return True
return False
class CircuitBreaker:
"""Opens after `threshold` unhealthy results in a row, probes after `open_for` seconds."""
def __init__(self, threshold=5, open_for=1.0):
self.threshold, self.open_for = threshold, open_for
self.state, self.failures, self.opened_at, self.probing = "closed", 0, 0.0, False
self.lock, self.changes = threading.Lock(), [] # (monotonic time, new state)
def _set(self, state):
if state != self.state:
self.changes.append((time.monotonic(), state))
self.state = state
def is_open(self):
with self.lock:
return self.state == "open"
def allow(self):
with self.lock:
if self.state == "open" and time.monotonic() - self.opened_at >= self.open_for:
self._set("half-open")
self.probing = False
if self.state == "closed":
return True
if self.state == "half-open" and not self.probing:
self.probing = True # exactly one probe request
return True
return False
def record(self, healthy):
with self.lock:
if self.state == "open":
return # late results of earlier requests
if healthy:
self._set("closed")
self.failures, self.probing = 0, False
return
self.failures += 1
if self.state == "half-open" or self.failures >= self.threshold:
self._set("open")
self.opened_at, self.probing = time.monotonic(), FalseThe call loop walks the providers in order. Every break moves the call to the next provider, and every exit path is one of the rules from the list above. A failure that opens the breaker moves the call on at once, without spending a token or waiting.
class Provider:
def __init__(self, name, port):
self.name, self.port = name, port
self.breaker, self.budget = CircuitBreaker(), RetryBudget()
def send(self, body, timeout):
conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=timeout)
try:
conn.request("POST", "/v1/chat", json.dumps(body),
{"Content-Type": "application/json"})
resp = conn.getresponse()
data = resp.read()
except TimeoutError as exc:
raise ProviderError(self.name, "timeout") from exc
except (OSError, http.client.HTTPException) as exc:
raise ProviderError(self.name, "dropped") from exc
finally:
conn.close()
if resp.status == 200:
try:
return json.loads(data)
except ValueError as exc:
raise ProviderError(self.name, "bad body") from exc
raise ProviderError(self.name, resp.status, parse_retry_after(resp.getheader("Retry-After")))
class ResilientClient:
def __init__(self, providers, policy, seed=0):
self.providers, self.policy, self.seed = providers, policy, seed
def backoff(self, attempt, err, rng):
p = self.policy
if p.retry_after and err.retry_after is not None:
return err.retry_after + (rng.uniform(0, p.base_delay) if p.jitter else 0.0)
ceiling = min(p.max_delay, p.base_delay * 2 ** attempt)
return rng.uniform(0, ceiling) if p.jitter else ceiling # full jitter
def call(self, body):
p, rng = self.policy, random.Random(f"{self.seed}:{body['id']}")
end = time.monotonic() + p.deadline
last = None
for provider in self.providers if p.fallback else self.providers[:1]:
for attempt in range(p.max_attempts):
remaining = end - time.monotonic()
if remaining <= 0:
raise last or ProviderError(provider.name, "deadline")
if p.breaker and not provider.breaker.allow():
break # breaker open: next provider
if attempt == 0:
provider.budget.on_first_attempt()
try:
result = provider.send({**body, "attempt": attempt},
min(p.attempt_timeout, remaining))
provider.breaker.record(healthy=True)
return provider.name, result
except ProviderError as err:
last = err
provider.breaker.record(healthy=not err.unhealthy)
if not err.retryable:
raise # 400, 401: a retry cannot help
if p.breaker and provider.breaker.is_open():
break # it just opened: next provider
wait = self.backoff(attempt, err, rng)
if attempt + 1 == p.max_attempts:
break
if time.monotonic() + wait + p.attempt_timeout > end:
break # deadline near: next provider
if p.budget and not provider.budget.try_spend():
break # budget empty: next provider
time.sleep(wait)
raise last or ProviderError("all", "unavailable") # every breaker openThe generator is seeded per call so runs repeat. A real client would not seed it.
The run#
Each stub is a ThreadingHTTPServer of about 95 lines. The outcome of a request depends only on the seed, the call id, the attempt number and the outage window, so every scenario meets the same failures:
- Provider A, normally: 12 percent 429 with
Retry-After: 1, 4 percent 500, 4 percent slow answers of 2 s, 3 percent dropped connections, the rest 200 in 50 to 120 ms. - Provider A from 1.0 to 3.5 s: 70 percent 503 at once, the rest hang for 4 s and then drop the connection.
- Provider B: 2 percent 500, the rest 200 in 150 to 300 ms.
A runner of about 120 lines starts both stubs as child processes and sends 12 bursts of 8 calls, one burst every 0.5 s, through each policy. Calls 3 and 70 are invalid. The four policies:
OFF = dict(jitter=False, retry_after=False, budget=False, breaker=False, fallback=False)
SCENARIOS = {
"1 no protection": Policy(attempt_timeout=30, deadline=60, max_attempts=1, **OFF),
"2 retries, no jitter": Policy(deadline=60, **OFF),
"3 + jitter, budget": Policy(breaker=False, fallback=False), # and Retry-After, deadline
"4 + breaker, fallback": Policy(),
}The output of a run on 28 November 2026, latencies in milliseconds over all 96 calls, failed ones included. A and B count the requests each stub received, outage those at A during its outage, retries the retries at A, and cluster the most retries that reached A within 20 ms:
$ python3.12 run_scenarios.py --port-a 8471 --port-b 8472
scenario ok p50 p95 A B outage retries cluster
1 no protection 51/96 82 4011 96 0 40 0 0
2 retries, no jitter 76/96 119 2656 211 0 117 115 11
3 + jitter, budget 52/96 94 873 119 0 56 23 2
4 + breaker, fallback 94/96 222 878 44 66 9 2 1
(outcome lines of scenarios 1 to 3 trimmed)
4 + breaker, fallback: {'failed: 400': 2, 'ok via A': 30, 'ok via B': 64}
breaker A in scenario 4:
1.03 s open
2.50 s half-open
3.11 s open
4.50 s half-open
4.59 s closedSeven other runs, five before two small fixes to the client, gave the same counts except 53 successes in scenario 3 twice. The p95 of scenario 3 ranged from 806 to 873 ms; other times moved by a few milliseconds.
What the numbers show:
- Retries alone buy success with load. Scenario 2 rescues 25 calls, mostly those that started late in the outage and outlived it, but sends nearly three times the normal load to A while A is down.
- The budget caps the load, not the failures. Scenario 3 sends 23 retries, within the budget of 5 plus 0.2 per call. With nowhere else to go, calls in the outage still fail, but fast: p95 is 873 ms instead of 4 s.
- The breaker and the fallback fix both. Breaker A opened at 1.03 s. A then saw 9 requests during the outage: the 8 calls of the burst at 1.0 s, whose failures opened the breaker, and one probe at 2.50 s. That probe hung and timed out, so the breaker reopened. The probe at 4.50 s succeeded.
- Fallback has a price. A recovered at 3.5 s, but got traffic again only at 4.50 s. The median rises to 222 ms because stub B is slower.
The figure shows the 8 calls that started at 1.0 s, as stub A saw them.
Pros, cons and limits#
| Measure | Gives | Costs |
|---|---|---|
| Timeout and deadline | A bounded wait | Slow valid answers are cut off |
| Retries on retryable errors | Rescues transient failures | More requests, duplicate work after a timeout |
Jitter and Retry-After | Spread retries, follow the provider | Somewhat longer waits |
| Retry budget | Near-normal load in an outage | Calls fail sooner when it is empty |
| Circuit breaker | No traffic to a provider that is down | Recovery waits for the next probe |
| Fallback | Calls succeed during an outage | A second provider, maybe another answer |
Limits of this demo:
- State in one process, stubs instead of providers. Real error rates, latencies and outages differ.
- Thresholds tuned for a run of seconds. Derive the timeouts, the breaker window and the budget ratio from your own traffic.
- The deadline is checked between attempts.
http.clientapplies its timeout per socket operation, so an answer that trickles in can overrun the deadline. Production needs a total timeout per request.
When to add each measure#
Start with timeouts, a deadline and retries on retryable errors only, in one layer. Add jitter and Retry-After as soon as you retry. Add a retry budget when many calls share a provider. Add the breaker and the fallback when a second deployment exists and an outage costs more than a slower or different answer.
Next step: read the Retry-After and idempotency sections of RFC 9110, then the retry section of your SDK, and decide which layer owns the retries.

