An Outage Is a Design Problem, Not a Surprise
Every AI API provider goes down. Not "might" — does. The only thing worth designing for is what your application does in the ninety seconds after the first timeout, when you still don't know whether you're looking at a blip, a rate limit, or a regional outage.
Most teams discover they have no answer at the worst possible moment: a user is staring at a spinner, someone is refreshing a status page, and an engineer is about to add a retry loop straight to production. What follows replaces that with four decisions you make once — classify, retry, reroute, degrade — plus code you can ship today.
Step 1: Classify the Failure Before You React
The biggest mistake during an outage is treating every error identically. A 429 is a conversation about pacing. A 503 is a conversation about routing. A 400 is a conversation about your own payload. Retrying the wrong one burns your entire error budget while the provider is already struggling.
| Symptom | What it usually means | Correct response |
|---|---|---|
| 429 / rate limited | You're over your concurrency budget, or capacity is tight | Back off with jitter and retry; don't fail the user request yet |
| Timeout / connection reset | Network path or provider edge trouble | One retry with a longer timeout, then move down the ladder |
| 500 / 502 / 503 / 504 | Provider-side fault | Jittered exponential backoff, then trip the breaker |
| 400 / 401 / 422 | Your payload, schema, or key | Fail fast — retries just burn wall-clock time |
| Success, but very slow | Load or a genuinely long generation | Stream tokens or lower max_tokens; retrying makes it worse |
Step 2: Retry Correctly (Most People Get This Wrong)
Use a wall-clock budget, not just an attempt count. Three retries that each wait a minute is an outage your user experiences as a hang.
Always add jitter. Synchronized retries from thousands of clients turn a small blip into a self-inflicted thundering herd.
Never retry a 4xx. If the request is malformed, the second attempt is identically malformed.
Disable the SDK's built-in retries (max_retries=0) while you're tuning your policy, so you can see and log every attempt yourself.
Log the exception class and request ID on each attempt. "It failed" is not a debuggable signal at 3 a.m.
Keep retried operations idempotent — pass your own idempotency key if anything downstream has side effects.
Run a linter over the result. AiCredits' code linting tools flag blocking retry loops and missing timeouts before they turn into a 90-second hang in production.
import os, random, time, logging
from openai import (
OpenAI,
APIConnectionError,
APITimeoutError,
RateLimitError,
APIStatusError,
)
log = logging.getLogger("llm")
client = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=os.environ["AICREDITS_API_KEY"],
timeout=20.0, # per-attempt wall clock
max_retries=0, # SDK retries off: we retry ourselves and log every attempt
)
RETRYABLE_STATUS = {408, 409, 429, 500, 502, 503, 504}
def complete(prompt: str, attempts: int = 4, budget_s: float = 45.0) -> str:
"""Call deepseek-v4-flash, retrying only failures that deserve a retry."""
deadline = time.monotonic() + budget_s
last = None
for attempt in range(attempts):
try:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": prompt}],
temperature=0.2,
)
return resp.choices[0].message.content or ""
except RateLimitError as e: # 429
last = e
except (APIConnectionError, APITimeoutError) as e:
last = e
except APIStatusError as e: # 4xx/5xx with a response body
if e.status_code not in RETRYABLE_STATUS:
raise # 400/401/422: retrying cannot help
last = e
nap = min(2 ** attempt, 8) * (0.5 + random.random()) # jittered backoff
if attempt == attempts - 1 or time.monotonic() + nap > deadline:
raise last
log.warning("attempt %d failed (%s); retrying in %.1fs",
attempt + 1, type(last).__name__, nap)
time.sleep(nap)
raise last or RuntimeError("no attempts configured")
if __name__ == "__main__":
print(complete("In one sentence: why is jittered backoff important?"))
That budget_s cap is the difference between a retry policy and a hang. When the deadline hits, raise — and let the caller walk down the fallback ladder instead of waiting. The deliberate max_retries=0 matters too: if the SDK retries underneath your retry loop, you get multiplicative attempts you never see in your logs.
Step 3: Build a Fallback Ladder, Not a Fallback Button
A single backup provider is a binary you flip in a panic. A ladder is walked, in order of how much you lose at each rung.
Rung one: same model, next attempt — cheap and invisible. Rung two: a different model tier from the same provider. Here that means deepseek-v4-pro instead of deepseek-v4-flash. Pro is stronger and costs more, so it's a recovery move rather than a default, but if flash specifically is degraded, changing tiers can route around the problem while keeping your auth, SDK and billing identical. Rung three: a second provider on independent infrastructure. Rung four: no model at all — a cached answer, a queued job, or an honest "we're catching up" message.
The other half of the ladder is a circuit breaker. Without one, every request in your fleet keeps paying full timeout cost against a provider that has already said no five times in a row.
import os, time
from openai import OpenAI, APIConnectionError, APITimeoutError, APIStatusError
RETRYABLE_STATUS = {408, 409, 429, 500, 502, 503, 504}
primary = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=os.environ["AICREDITS_API_KEY"],
timeout=20.0,
max_retries=0,
)
# Optional second path. Set SECONDARY_BASE_URL and SECONDARY_API_KEY to enable it.
secondary = None
if os.environ.get("SECONDARY_BASE_URL"):
secondary = OpenAI(
base_url=os.environ["SECONDARY_BASE_URL"],
api_key=os.environ["SECONDARY_API_KEY"],
timeout=20.0,
max_retries=0,
)
class Breaker:
"""Stop hammering a provider that is clearly failing."""
def __init__(self, fail_threshold: int = 5, cooldown_s: float = 60.0):
self.fail_threshold = fail_threshold
self.cooldown_s = cooldown_s
self.fails = 0
self.opened_at = 0.0
@property
def is_open(self) -> bool:
if not self.opened_at:
return False
if time.monotonic() - self.opened_at < self.cooldown_s:
return True
self.opened_at, self.fails = 0.0, 0 # cooldown elapsed: half-open, let one through
return False
def record(self, ok: bool) -> None:
if ok:
self.fails, self.opened_at = 0, 0.0
else:
self.fails += 1
if self.fails >= self.fail_threshold:
self.opened_at = time.monotonic()
primary_breaker, secondary_breaker = Breaker(), Breaker()
def ask(prompt: str, max_tokens: int = 512) -> str:
rungs = []
if not primary_breaker.is_open:
rungs.append(("aicredits/flash", primary, "deepseek-v4-flash", primary_breaker))
rungs.append(("aicredits/pro", primary, "deepseek-v4-pro", primary_breaker))
if secondary is not None and not secondary_breaker.is_open:
rungs.append(("secondary/flash", secondary, "deepseek-v4-flash", secondary_breaker))
if not rungs:
raise RuntimeError("all providers are circuit-broken; serve the degraded path")
last = None
for label, client, model, breaker in rungs:
try:
resp = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=0.2,
max_tokens=max_tokens,
)
breaker.record(True)
return resp.choices[0].message.content or ""
except (APIConnectionError, APITimeoutError) as e:
breaker.record(False)
last = e
except APIStatusError as e:
breaker.record(False)
if e.status_code not in RETRYABLE_STATUS:
raise # 400/401/422: your bug, not theirs
last = e
print(f"[fallback] {label} failed with {type(last).__name__}")
raise RuntimeError(f"every rung failed, last error: {last!r}")
if __name__ == "__main__":
print(ask("In one sentence: what does a circuit breaker protect?"))
Two details make this work. Rungs are tried in order and the first success wins, so your happy path never touches the second provider — and a non-retryable 4xx is re-raised immediately, because a fallback vendor cannot fix your malformed JSON.
Step 4: Degrade Gracefully So Users Never See the Failure
Queue instead of failing: accept the request, return a job ID, and deliver the result when a rung recovers.
Serve a stale-but-useful answer with a visible "last updated" timestamp rather than a blank screen.
Shrink the task. If a long generation is timing out, a short classification or extraction prompt may still succeed on the same provider.
Say what's happening. "Our AI provider is having issues — retrying" converts an outage into a status update.
Never return an empty string on failure. Silent degradation reads as a product bug and destroys trust faster than a visible error.
Step 5: Pick Providers Whose Outages Aren't Yours
The dirty secret of fallback architecture: if both providers run in the same cloud region, or depend on the same upstream serving stack, they fail together. A secondary that shares fate with your primary is theater.
When you choose a second path, check three things: independent infrastructure, an independent signup path, and a way to see current capacity. AiCredits fills that role for international developers — DeepSeek models behind an OpenAI-compatible endpoint at https://api.aicreditsapi.com/v1, payable by card or PayPal with no Chinese phone number or bank account required, so keeping a warm second key never needs a procurement cycle. Pricing is usage-based and qualitative: off-peak requests cost less than peak, cache hits are cheaper than fresh prompts, and deepseek-v4-pro costs more than deepseek-v4-flash. Current rates are at aicreditsapi.com/pricing.
Then exercise it. A fallback you tested once at launch is not a fallback. Route a scheduled synthetic request down the second rung every day, so you find out it's broken on a Tuesday morning instead of during an incident.
A 20-Minute Drill You Can Run Today
Add a /health/llm endpoint that sends one tiny completion and returns the exception class on failure.
Split your alerts: page on a sustained error rate, not on a single failed request.
Tag every call with a provider label and request ID so postmortems take minutes, not hours.
Write the degraded path first — the fallback message, the queue, the cached template — because that's the code you'll actually need.
Re-run the drill monthly and after every key rotation.
The cheapest outage response is the one you wrote before the outage. Everything else is improvisation with a status page open in another tab.
FAQ
Two or three attempts inside a fixed wall-clock budget — typically 20 to 45 seconds for interactive requests. Batch jobs can wait longer; chat UIs cannot. The budget matters more than the count, because it's what stops a provider outage from becoming a user-visible hang.
Switch model tier first when only one deployment looks degraded, since auth, format and billing stay identical. Switch provider first when a status page confirms a platform-wide incident. A good ladder does both, in that order, automatically.
Tell them quickly: what's delayed, what still works, and when the next update lands. A visible status message costs a little polish and saves a support inbox full of duplicate "is it broken?" tickets.
Point the secondary base URL at an unreachable host behind a feature flag, or force 503s with a stub proxy, and run the ladder. If your app doesn't degrade cleanly, you've found the bug at the cheapest possible moment.