AiCredits
Reliability

How to Build Fallback Logic Across Multiple AI API Providers

Build a layered AI API fallback chain across providers: retry, escalate model tier, hop vendors, and degrade gracefully — with runnable Python code today.

Published 2026-10-07 Updated 2026-10-07 8 min

Retries Alone Don't Survive a Provider Outage

Most teams start with a retry decorator and call it resilience. It works fine until the failure stops being transient. When a provider degrades globally — a bad edge rollout, a regional network partition, a capacity crunch — every retry from every one of your requests lands on the same degraded endpoint. You get a slow, expensive version of the same outage, plus a support thread full of timeouts.

A fallback chain is a different shape of solution. Instead of asking 'how do I make this one call succeed?', you ask 'what is my ordered list of ways to answer this request, and which one actually caught it?' That ordering question is where most implementations go wrong, because they jump straight from primary provider to a second vendor and skip two cheaper, faster layers in between.

The Four Layers of a Fallback Chain

  • Layer 1 — Retry the same target. One or two attempts with exponential backoff plus jitter. This absorbs the brief blips that cause the majority of failed requests, and it costs nothing extra to add.

  • Layer 2 — Escalate the model tier. Same endpoint, same key, a stronger model such as deepseek-v4-pro. Use this when the cheap model returns something unusable or the task needs more reasoning depth.

  • Layer 3 — Hop to another provider or base URL. A second OpenAI-compatible endpoint run by a different operator, so a platform-wide incident at one vendor cannot take your product down.

  • Layer 4 — Degrade deliberately. Return a cached answer, a deterministic template, or queue the job for later. An honest degradation beats a 30-second hang followed by a 500.

Classify the Error Before You Fall Back

Fallback is not a substitute for input validation. If you fall back on every exception, you will happily send the same malformed prompt to three vendors and pay for three identical rejections. Decide once, in code, which failures are worth another attempt — and make that classifier a unit-tested function, not a bare except clause.

SignalRetry or fall back?What to do
Timeout, connection reset, DNS failureYesRetry the same target once with jittered backoff, then move down the chain
HTTP 429 rate limitYesBack off, then continue to the next target; keep per-target concurrency low
HTTP 5xxYesFall through immediately and let the breaker open after repeated failures
HTTP 400 / 422NoPrompt or schema bug — surface it instead of burning three vendors
HTTP 401 / 403NoKey, quota, or region configuration problem; alert a human, don't loop
HTTP 404 model not foundNoDeactivate that target in configuration; retrying will never help

A Runnable Layered Fallback in Python

This script is a complete chain. It keeps the OpenAI SDK, points the primary target at AiCredits, and treats extra vendors as optional — if ALT_API_KEY is not set, the chain simply runs shorter. Export AICREDITS_API_KEY and run it as-is.

# Layered fallback across OpenAI-compatible providers. Requires: pip install openai
import os, time, random, logging
from dataclasses import dataclass

from openai import OpenAI, APIConnectionError, APITimeoutError, RateLimitError, InternalServerError, APIStatusError

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
log = logging.getLogger('fallback')


@dataclass
class Target:
    name: str
    base_url: str
    api_key: str
    model: str
    timeout: float = 30.0


def build_targets():
    key = os.environ['AICREDITS_API_KEY']
    targets = [
        Target('aicredits/flash', 'https://api.aicreditsapi.com/v1', key, 'deepseek-v4-flash'),
        Target('aicredits/pro', 'https://api.aicreditsapi.com/v1', key, 'deepseek-v4-pro', timeout=60.0),
    ]
    alt_key = os.environ.get('ALT_API_KEY')
    if alt_key:
        targets.append(Target('alt-vendor', os.environ['ALT_BASE_URL'], alt_key,
                              os.environ.get('ALT_MODEL', 'deepseek-v4-flash')))
    return targets


_clients = {}


def client_for(t):
    if t.name not in _clients:
        # max_retries=0: we own retries so we control backoff and failover timing.
        _clients[t.name] = OpenAI(base_url=t.base_url, api_key=t.api_key,
                                  timeout=t.timeout, max_retries=0)
    return _clients[t.name]


class Breaker:
    def __init__(self, threshold=3, cooldown=30.0):
        self.threshold, self.cooldown = threshold, cooldown
        self.failures, self.opened_at = 0, 0.0

    def allow(self):
        if self.failures < self.threshold:
            return True
        if time.monotonic() - self.opened_at > self.cooldown:
            self.failures = self.threshold - 1  # half-open: allow one probe
            return True
        return False

    def record(self, ok):
        if ok:
            self.failures = 0
            return
        self.failures += 1
        if self.failures >= self.threshold:
            self.opened_at = time.monotonic()


_breakers = {}


def breaker_for(name):
    return _breakers.setdefault(name, Breaker())


RETRYABLE_STATUS = {408, 409, 425, 429, 500, 502, 503, 504}


def is_retryable(exc):
    if isinstance(exc, (APIConnectionError, APITimeoutError, RateLimitError, InternalServerError)):
        return True
    if isinstance(exc, APIStatusError):
        return exc.status_code in RETRYABLE_STATUS
    return False  # 400/401/403/404/422: another provider will not fix a bad request


def call(t, messages, max_tokens=512):
    resp = client_for(t).chat.completions.create(
        model=t.model,
        messages=messages,
        max_tokens=max_tokens,
        temperature=0.2,
    )
    return resp.choices[0].message.content or ''


def ask(messages, attempts_per_target=2, max_tokens=512):
    last_err = None
    for target in build_targets():
        breaker = breaker_for(target.name)
        if not breaker.allow():
            log.warning('skip %s (breaker open)', target.name)
            continue
        for attempt in range(1, attempts_per_target + 1):
            try:
                started = time.monotonic()
                text = call(target, messages, max_tokens)
                breaker.record(True)
                log.info('%s served in %.2fs', target.name, time.monotonic() - started)
                return text, target.name
            except Exception as exc:
                last_err = exc
                breaker.record(False)
                log.warning('%s attempt %d failed: %s', target.name, attempt, exc)
                if not is_retryable(exc):
                    break
                if attempt < attempts_per_target:
                    time.sleep(min(2.0, 0.25 * 2 ** attempt) + random.random() * 0.1)
    raise RuntimeError('all targets failed, last error: %r' % (last_err,))


if __name__ == '__main__':
    answer, served_by = ask([{'role': 'user',
                             'content': 'In one sentence: when should a client stop retrying?'}])
    print('[%s] %s' % (served_by, answer))

Two details matter more than they look. First, max_retries=0 on the client: the SDK's built-in retries are fine in isolation, but during an outage they add seconds of delay before your failover even starts, and they hide which target actually failed. Second, the breaker is per target, not global. One flaky vendor should never eject your healthy primary. And because ask() returns the target name alongside the text, every log line tells you which layer caught the request.

The Model-Tier Hop Is the Cheapest Fallback You Own

Plenty of fallback diagrams jump straight from 'primary provider' to 'a completely different vendor'. That means two SDKs, two auth models, two prompt dialects, two sets of rate-limit behaviours — and two ways to be wrong at 3am. Before you take on that surface area, check whether your primary can cover the failure itself by escalating a model tier.

That is the practical reason AiCredits serves deepseek-v4-flash and deepseek-v4-pro from the same OpenAI-compatible endpoint: escalation becomes a one-line change in a config list, not a second integration. It is built for developers outside China who want DeepSeek models without a Chinese phone number or bank account — a card or PayPal is enough.

On cost, keep it qualitative: flash is the cheap default you should use for nearly everything; pro costs more and earns its keep only on requests that failed the cheap path; cache hits on repeated prompt prefixes are cheaper than fresh prompts; and off-peak traffic costs less than peak. Current rates are listed at aicreditsapi.com/pricing.

Guardrails: Fallback Shouldn't Triple Your Spend

  • Cap max_tokens on every hop. A long answer that retries three times is billed three times if the earlier attempts were charged before failing.

  • Never fall back on non-retryable errors. A 400 means your prompt or schema is wrong, and the next vendor will reject it the same way.

  • Set a per-request ceiling, not just a daily one. Per-request budgets stop a single runaway loop from eating the month.

  • Log the target that served every call, and alert on fallback rate. A rising fallback rate is your earliest signal that a vendor is degrading.

  • If a fallback model has different limits or capabilities, send a trimmed prompt instead of assuming it accepts the identical payload.

Prove the Chain Works Before the Outage

  • Unit-test the classifier. Feed it synthetic 400, 429, and timeout exceptions and assert which ones are retryable.

  • Fault-inject with a stub server: point one target at a local HTTP server that returns 503 or sleeps past your timeout. Never validate failover by waiting for a real outage.

  • Test the half-open probe. After the cooldown expires, exactly one request should be allowed through before the breaker decides.

  • Assert on the returned target name in tests, so a careless reordering of the chain fails loudly instead of silently doubling your costs.

If your adapter layer keeps growing, a static pass over it is worth the five minutes — AiCredits bundles code linting tools with its developer account, and multi-provider glue code is exactly the kind of file that accumulates copy-paste mistakes nobody reads twice.

FAQ

How many providers should be in a fallback chain?

Two or three well-tested targets beat five untested ones. Every extra hop adds prompt drift, logging complexity, and the chance of paying for the same rejected request twice. Beyond your primary endpoint and a model-tier escalation, one independent provider is usually enough for outage coverage.

Should I fall back to a different model or a different provider first?

Model tier first, if the same key serves both — it is one integration, one auth model, and easy to reason about under pressure. Keep the provider hop for the case where the whole platform is unreachable, and make sure it is exercised in tests so it is not theoretical.

Does fallback work with streaming and tool calls?

Streaming needs care: decide whether to restart the stream on the next target or surface a short reconnect notice, and never emit partial text from two targets into one response. Tool or function calls need compatible schemas across targets, and any side-effecting tool should be guarded by an idempotency key so a retried call cannot double-write.

How do I keep fallback from costing more than the outage would?

Cap tokens per hop, skip fallback entirely for non-retryable errors, cache deterministic prompts, and reserve the stronger model for the escalation hop only. Fallback should be rare, observable, and cheap in the common case — which is why the classifier and the breaker matter as much as the target list.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×