Skip to content

How to Set Up Automatic Failover Between LLM Providers

Summary

Setting up automatic failover between LLM providers to ensure that requests are redirected to a backup provider without manual intervention when the primary API fails.

Why is Failover Needed

When working with paid LLM APIs, failures can occur: rate limit exceedances, timeouts, 5xx errors, endpoint unavailability. Manual switching between providers slows down development and breaks automation. Failover solves the problem: the system automatically detects the unavailability of the primary provider and sends the request to the backup provider.

Solution Architecture

flowchart LR
    A[Application] --> B[Failover Router]
    B --> C{Provider 1 available?}
    C -- Yes --> D[OpenRouter API]
    C -- No --> E{Provider 2 available?}
    E -- Yes --> F[DeepSeek API]
    E -- No --> G[Local model via Ollama]

Step 1. Define Provider Configuration

Create a config.yaml file with connection parameters:

providers:
  - name: openrouter
    base_url: "https://openrouter.ai/api/v1"
    api_key_env: "OPENROUTER_API_KEY"
    model: "anthropic/claude-3.5-sonnet"
    timeout: 30
    max_retries: 2
  - name: deepseek
    base_url: "https://api.deepseek.com"
    api_key_env: "DEEPSEEK_API_KEY"
    model: "deepseek-chat"
    timeout: 30
    max_retries: 2
  - name: ollama
    base_url: "http://localhost:11434"
    api_key: null
    model: "llama3.1:8b"
    timeout: 60
    max_retries: 1

Step 2. Write the Failover Router Class

import os
import time
import requests
from typing import Any, Dict, List
import yaml

class LLMFallbackRouter:
    def __init__(self, config_path: str):
        with open(config_path, "r") as f:
            self.config = yaml.safe_load(f)
        self.providers = self.config["providers"]

    def _call_provider(self, provider: Dict, messages: List[Dict], **kwargs) -> Dict:
        api_key = os.getenv(provider["api_key_env"]) if provider["api_key_env"] else None
        headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
        payload = {
            "model": provider["model"],
            "messages": messages,
            **kwargs
        }
        response = requests.post(
            f"{provider["base_url"]}/chat/completions",
            headers=headers,
            json=payload,
            timeout=provider["timeout"]
        )
        response.raise_for_status()
        return response.json()

    def chat(self, messages: List[Dict], **kwargs) -> Dict:
        last_error = None
        for provider in self.providers:
            for attempt in range(provider["max_retries"] + 1):
                try:
                    return self._call_provider(provider, messages, **kwargs)
                except requests.exceptions.Timeout as e:
                    last_error = f"Timeout: {e}"
                except requests.exceptions.HTTPError as e:
                    status = e.response.status_code
                    if status in (429, 500, 502, 503, 504):
                        last_error = f"HTTP {status}: {e}"
                    else:
                        raise
                except requests.exceptions.ConnectionError as e:
                    last_error = f"Connection error: {e}"
                time.sleep(2 ** attempt)
        raise RuntimeError(f"All providers failed: {last_error}")

Step 3. Handle Errors and Timeouts

Key points: - Timeout for each request is 30 seconds, for local model - 60 seconds. - Retry with exponential backoff: 1s, 2s, 4s. - Switch to the next provider only after retries are exhausted. - Errors 4xx (except 429) do not trigger failover - these are request errors, not provider errors.

Step 4. Add Monitoring

Log each call:

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class LLMFallbackRouterWithLogging(LLMFallbackRouter):
    def chat(self, messages: List[Dict], **kwargs) -> Dict:
        for provider in self.providers:
            try:
                result = super().chat(messages, **kwargs)
                logger.info(f"Provider {provider['name']} succeeded")
                return result
            except Exception as e:
                logger.warning(f"Provider {provider['name']} failed: {e}")
        raise RuntimeError("All providers failed")

Step 5. Test the Failover

Write a test with simulated failure:

import unittest
from unittest.mock import patch

class TestFallback(unittest.TestCase):
    def test_fallback_on_timeout(self):
        router = LLMFallbackRouter("config.yaml")
        with patch.object(router, "_call_provider", side_effect=[
            requests.exceptions.Timeout(),
            {"choices": [{"message": {"content": "ok"}}]}
        ]):
            result = router.chat([{"role": "user", "content": "test"}])
            self.assertEqual(result["choices"][0]["message"]["content"], "ok")

Conclusion

The failover router enhances the resilience of LLM applications. Configuration through YAML allows changing providers without modifying the code. Monitoring through logs helps identify issues with specific APIs. For more on abuse protection, read the guide. For model selection, see the post.