Skip to content

LLM API Error Handling: Timeouts, Retries, and Degradation

Cover: LLM API Error Handling: Timeouts, Retries, and Degradation Errors are inevitable when integrating LLM APIs into production systems. Network instability, providers introduce limits, and models occasionally return incorrect responses. Without a well-thought-out error handling strategy, even well-written code will fail, and users will experience an unavailable service. In this article, I will explore practical approaches to LLM API error handling: classification, retries, timeouts, and degradation.

Error Classification

Errors when working with LLM APIs can be divided into several categories. Understanding the type of error determines the strategy for handling it. | Category | Examples | Cause | Strategy | |---|---|---|---| | Network | ConnectionError, Timeout | Network issues, server unavailability | Exponential backoff retries | | HTTP 4xx | 400 Bad Request, 401 Unauthorized, 429 Too Many Requests | Incorrect request, invalid key, exceeded limit | Do not retry (except 429), fix the request or key | | HTTP 5xx | 500 Internal Server Error, 503 Service Unavailable | Provider issues | Exponential backoff retries | | Model Errors | InvalidResponse, ContentFilter | Model returned an incorrect or filtered response | Retry with a modified prompt, fallback | | Validation Errors | JSONDecodeError, SchemaValidationError | Response does not match expected schema | Retry with instructions, validation |

Retry Strategy

Retries are the primary mechanism for dealing with transient errors. However, infinite retries only exacerbate the problem: they increase API load and delay for the user. I use the following principles: - Limit the number of attempts: maximum 3–5 retries. - Exponential backoff: the pause between attempts grows: 1s, 2s, 4s, 8s. - Jitter: add a random value to the delay to avoid synchronous spikes. - Retry only for idempotent requests: if the request does not change state (e.g., text generation), retry is safe. Example implementation in Python using tenacity:

from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
import requests

class LLMAPIError(Exception):
    pass

@retry(
    stop=stop_after_attempt(5),
    wait=wait_exponential(multiplier=1, min=1, max=10),
    retry=retry_if_exception_type((requests.ConnectionError, requests.Timeout)),
    reraise=True
)
def call_llm(prompt: str) -> str:
    response = requests.post(
        "https://api.example.com/v1/chat/completions",
        json={"model": "gpt-4", "messages": [{"role": "user", "content": prompt}]},
        timeout=30
    )
    response.raise_for_status()
    return response.json()["choices"][0]["message"]["content"]

Timeout Handling

Timeouts are a common issue when working with LLM APIs, especially with long prompts or streaming generation. I set two levels of timeouts: - Connection timeout (connect timeout): 5–10 seconds. - Read timeout (read timeout): 30–60 seconds, depending on the complexity of the request. For streaming generation, the read timeout should be longer, as there may be pauses between tokens. In requests, this is done as follows:

response = requests.post(url, json=payload, timeout=(5, 60))
If the timeout expires, I do not retry immediately but check if the server has processed the request. For this, I use idempotent request keys or check the status through a separate endpoint.

Service Degradation

When all retries are exhausted, graceful degradation is necessary. Degradation options: 1. Fallback to another model: if the primary model is unavailable, use a backup (e.g., a cheaper or local model). More details on setting up fallbacks are in the fallback guide. 2. Cached response: if the request is repeated, return a previously saved response. Caching strategies are described in the caching guide. 3. Simplified response: for non-critical functions, return a template response or a shortened version. 4. Queue: if the load is high, put the request in a queue and process it later. Example of degradation with fallback:

def generate_with_fallback(prompt: str) -> str:
    try:
        return call_llm(prompt, model="gpt-4")
    except LLMAPIError:
        return call_llm(prompt, model="gpt-3.5-turbo")

Error Monitoring

Without monitoring, it is impossible to understand which errors occur most frequently. I log each LLM API call with metadata: model, status, response time, error type. For this, I use standard observability tools described in the LLM system observability article. Key metrics: - Frequency of errors by type (4xx, 5xx, timeouts). - Response time (p50, p95, p99). - Number of retries per request. - Percentage of successful fallbacks.

Conclusion

Error handling for LLM APIs is an essential part of production integration. Classify errors, set up exponential backoff retries, handle timeouts, and plan for degradation. This will allow you to maintain service stability even during provider outages. Additionally, I recommend studying the guide on error handling in agents and the guide on managing limits and budgeting.