AI Error Handling: Retry, Fallback, and Rate Limit Patterns
Production-ready Python code for handling LLM API errors with exponential backoff, full jitter, token bucket rate limiting, circuit breakers, and fallbacks.
Production LLM reliability depends on four layered defenses: classifying transient versus terminal errors, retrying with full randomized jitter, shaping outgoing traffic with token buckets, and failing fast through circuit breakers and multi-provider fallbacks. HTTP 429 rate-limit exceptions cause roughly 60% of production LLM API failures, making defensive client architecture more decisive for uptime than raw model selection.
Unlike deterministic REST backends, frontier inference APIs combine variable reasoning latency with simultaneous token, request, and spend quotas. Engineering teams building on how LLM APIs handle requests and quotas prevent cascading outages by embedding retry classification, spend caps, and request-ID logging directly into a shared client wrapper.
Key Takeaways
- Dominant Error Surface: HTTP 429 rate-limit exceptions account for roughly 60% of production LLM failures, requiring proactive token-bucket pacing paired with
Retry-Afterheader parsing.- Terminal vs Transient 429s: Retrying HTTP 429 errors caused by
insufficient_quotaor monthly spend caps without aRetry-Afterheader wastes latency and should fail fast.- Full Jitter Backoff: Truncated exponential backoff with full randomized jitter eliminates synchronized thundering-herd retry waves across concurrent worker queues.
- Circuit Breakers & Fallbacks: Tripping a
CircuitBreakerafter 5 consecutive upstream 5xx or timeout faults prevents thread pool exhaustion and shifts traffic to backup providers such as Claude Sonnet 5.5 or Gemini 4 Hydrogen.
Common AI API Errors and Failure Classification
Classifying HTTP status codes and SDK exception payloads separates transient capacity spikes from permanent client bugs before executing any retry loop. Retrying malformed prompts or exhausted billing accounts wastes compute and blocks downstream workers.
| Error | HTTP Code | Root Cause | Retryable? | Recovery Action |
|---|---|---|---|---|
| Rate Limited (Traffic) | 429 | RPM, ITPM, OTPM, or TPM ceiling exceeded | Yes | Honor Retry-After header or jittered backoff |
| Quota / Spend Cap | 429 | insufficient_quota or monthly hard limit |
No | Fail fast and alert billing owner |
| Provider Overload | 503 / 529 | Upstream model cluster saturated | Yes | Exponential backoff with full jitter or fallback |
| Timeout | 408 / 504 | Reasoning pass exceeded socket deadline | Conditional | Retry idempotent calls with deduplication key |
| Authentication | 401 / 403 | Expired key or content policy violation | No | Verify secrets or sanitize prompt payload |
| Context Exceeded | 400 | Input + max output exceeded context window | No | Truncate history or chunk documents pre-flight |
| Internal Server Error | 500 | Transient upstream inference fault | Yes | Retry with backoff or route to fallback provider |
Provider-Side vs Client-Side vs Network Faults
Provider-side errors originate on OpenAI, Anthropic, or Google Cloud infrastructure during peak load. Traffic throttles documented in the OpenAI API Rate Limits Documentation and the Anthropic Claude Rate Limits Documentation surface as HTTP 429, 503, or 529 responses that generally recover after a bounded wait window.
Client-side errors stem from invalid request payloads, expired API keys, or prompts exceeding model limits. Even though Claude Opus 5.5 supports 200K to 1M tokens and Gemini 4 Hydrogen handles 1M tokens, retrieval-augmented generation pipelines inside production RAG retrieval systems can still breach context budgets when top-k document chunks stack unexpectedly.
Network errors occur between application servers and model endpoints, including DNS resolution hiccups, TLS handshakes, and socket resets. Production telemetry from mid-scale workloads shows rate limits accounting for roughly 60% of errors, timeouts for 20%, upstream 5xx faults for 15%, auth failures for 4%, and invalid requests for 1%.
Transient Throttles vs Terminal Quota Exhaustion
Not every HTTP 429 error deserves a retry. OpenAI distinguishes temporary traffic throttles (which carry a Retry-After header and x-ratelimit-reset-tokens) from insufficient_quota billing caps that never self-heal on wait.
Similarly, Anthropic enforces separate Input Tokens Per Minute (ITPM) and Output Tokens Per Minute (OTPM) token buckets. When Anthropic returns HTTP 429 without a Retry-After header, it typically signals a monthly workspace spend limit rather than a short-lived burst throttle.
Error Handling Architecture for Non-Deterministic LLM APIs
Traditional microservices assume predictable sub-second response times and flat per-request quotas. Production LLM clients must accommodate multi-second latency swings, multi-dimensional token accounting, and partial stream delivery.
Why LLM APIs Break Traditional REST Assumptions
Inference time depends heavily on generated output length and reasoning depth, swinging from 400 milliseconds on lightweight classification to over 30 seconds on multi-step tool planning. Calibrating static HTTP client timeouts without distinguishing time-to-first-token from total stream duration causes healthy long completions to abort prematurely.
Providers also throttle simultaneously across requests per minute (RPM), input and output tokens per minute (TPM/ITPM/OTPM), and concurrent in-flight connections. Engineers estimating capacity across how large language models allocate compute must also guard against silent token billing when a client drops a connection after the server already started decoding.
Four-Level Error Handling Pyramid and Graceful Degradation
Resilient AI systems organize defensive code into four sequential layers:
- Level 1 (Detection): Catch SDK-specific exceptions, parse response headers, and log structured UTC metrics with provider request IDs.
- Level 2 (Classification): Separate transient throttles and 5xx faults from terminal
400,401, andinsufficient_quotafailures. - Level 3 (Recovery): Apply
Retry-Afterwaits, full-jitter exponential backoff, circuit breakers, and cross-provider model fallback chains. - Level 4 (Prevention): Enforce proactive token-bucket pacing, pre-flight token counting, prompt caching, and daily spend caps before dispatching HTTP calls.
When every upstream route degrades simultaneously, graceful degradation preserves user trust. Applications can serve cached responses for frequent queries, downgrade to fast models like GPT-6.1 Terra or Claude Haiku 5.5, revert search UIs to lexical BM25 results, or queue non-urgent reports for asynchronous completion.
Exponential Backoff with Full Jitter and Selective Retry
Naive immediate retries hammer overloaded endpoints and worsen outages across distributed worker pools. Truncated exponential backoff spreads retries over widening intervals, while full randomized jitter prevents concurrent threads from waking in lockstep.
Base Exponential Backoff vs Full Jitter Math
With deterministic exponential backoff (base_delay * 2 ** attempt), 200 worker pods failing at t = 0 all retry together at 1s, 2s, 4s, and 8s, triggering a thundering herd wave that re-trips provider rate limiters. Full jitter replaces fixed steps with a uniform random sleep between 0 and min(max_delay, base_delay * 2 ** attempt).
The Python helper below implements full-jitter exponential backoff while exposing explicit exception filtering so terminal errors bypass retry loops immediately.
import random
import time
from typing import Callable, Tuple, Type, TypeVar
T = TypeVar("T")
class TerminalAPIError(Exception):
"""Non-retryable client, auth, or billing quota failure."""
class TransientAPIError(Exception):
"""Retryable capacity, timeout, or transient throttle error."""
def __init__(self, message: str, retry_after: float | None = None):
super().__init__(message)
self.retry_after = retry_after
def retry_with_full_jitter(
func: Callable[[], T],
max_retries: int = 4,
base_delay: float = 1.0,
max_delay: float = 30.0,
retryable_exceptions: Tuple[Type[BaseException], ...] = (TransientAPIError,),
) -> T:
"""Retry a callable using truncated exponential backoff with full jitter."""
for attempt in range(max_retries + 1):
try:
return func()
except TerminalAPIError:
raise
except retryable_exceptions as exc:
if attempt == max_retries:
raise
retry_after = getattr(exc, "retry_after", None)
if retry_after is not None:
sleep_seconds = min(float(retry_after), max_delay)
else:
cap = min(max_delay, base_delay * (2 ** attempt))
sleep_seconds = random.uniform(0.0, cap)
time.sleep(sleep_seconds)
raise RuntimeError("Unreachable retry loop termination")
Passing retry_after directly inside TransientAPIError ensures provider cooldown hints override blind random backoff whenever an upstream Retry-After header is present. Capping sleep_seconds at max_delay keeps interactive web handlers within predictable SLA limits.
Selective Retry by Exception Type
Production wrappers should bind official SDK exceptions directly into the retry classifier rather than catching bare Exception. OpenAI BadRequestError, AuthenticationError, and RateLimitError payloads carrying insufficient_quota must raise TerminalAPIError immediately.
from openai import (
APIConnectionError,
APIStatusError,
AuthenticationError,
BadRequestError,
OpenAI,
RateLimitError,
)
client = OpenAI()
def call_gpt_with_classification(prompt: str, model: str = "gpt-6.2-sol") -> str:
"""Invoke GPT-6.2 Sol and map SDK exceptions into transient vs terminal classes."""
try:
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content or ""
except (BadRequestError, AuthenticationError) as exc:
raise TerminalAPIError(f"Non-retryable client error: {exc}") from exc
except RateLimitError as exc:
if "insufficient_quota" in str(exc).lower():
raise TerminalAPIError("Hard billing quota exhausted") from exc
header_val = exc.response.headers.get("retry-after") if getattr(exc, "response", None) else None
wait_s = float(header_val) if header_val else None
raise TransientAPIError("Transient OpenAI 429 rate limit", retry_after=wait_s) from exc
except (APIConnectionError, APIStatusError) as exc:
if isinstance(exc, APIStatusError) and exc.status_code < 500:
raise TerminalAPIError(f"Non-retryable status {exc.status_code}: {exc}") from exc
raise TransientAPIError(f"Transient upstream failure: {exc}") from exc
Checking "insufficient_quota" in str(exc).lower() prevents worker pools from wasting 60 seconds retrying a billing block. Wrapping call_gpt_with_classification inside retry_with_full_jitter keeps transient network and capacity errors isolated cleanly.
Rate Limit Handling: Headers, Token Buckets, and Async Queues
Reactive retries alone introduce tail-latency spikes when bursty batch jobs slam provider RPM or TPM ceilings simultaneously. Combining reactive header parsing with proactive local pacing keeps steady-state utilization around 80% of assigned quotas.
OpenAI, Anthropic ITPM/OTPM, and Gemini Quotas
Providers throttle across distinct rate-limit dimensions that evolve as workspace spend tiers grow. Checking Google AI Studio Gemini Rate Limits Documentation alongside OpenAI and Anthropic docs reveals critical differences in quota accounting.
| Provider | Primary Limit Dimensions | Rate-Limit Signal & Headers | Prompt Caching Impact |
|---|---|---|---|
| OpenAI | RPM, TPM, TPD, concurrent requests | HTTP 429 + Retry-After, x-ratelimit-remaining-tokens |
Cached input tokens reduce effective cost & latency |
| Anthropic | RPM, ITPM (input), OTPM (output) token buckets | HTTP 429 rate_limit_error + Retry-After |
Cached prompt reads drastically reduce ITPM pressure |
| Google Gemini | RPM, TPM, RPD, 10-min rolling spend | HTTP 429 RESOURCE_EXHAUSTED (tighter on -preview) |
Context caching cuts repeated prefix token throughput |
[!TIP] Enabling prompt caching on long static system prompts and tool schemas cuts Anthropic Input Tokens Per Minute (ITPM) consumption on cached reads, allowing higher concurrency before hitting tier rate limits.
Proactive Token Bucket Limiter and Retry-After Extraction
A thread-safe token bucket paces outgoing calls smoothly at a configured refill rate while absorbing short bursts up to max_tokens. Monitoring token budgeting in AI pipelines lets teams size separate buckets for requests per second and tokens per second.
import re
import threading
import time
from typing import Optional
def extract_retry_after(error: Exception, default_seconds: float = 30.0) -> float:
"""Extract wait duration from response headers or provider error text."""
response = getattr(error, "response", None)
if response is not None and hasattr(response, "headers"):
header_val = response.headers.get("retry-after") or response.headers.get("Retry-After")
if header_val:
return float(header_val)
message = str(error)
sec_match = re.search(r"retry after (\d+(?:\.\d+)?)\s*s", message, re.IGNORECASE)
if sec_match:
return float(sec_match.group(1))
ms_match = re.search(r"try again in (\d+(?:\.\d+)?)\s*ms", message, re.IGNORECASE)
if ms_match:
return float(ms_match.group(1)) / 1000.0
return default_seconds
class TokenBucket:
"""Thread-safe proactive rate limiter for requests or estimated tokens."""
def __init__(self, rate_per_second: float, capacity: Optional[float] = None):
self.rate_per_second = rate_per_second
self.capacity = capacity if capacity is not None else max(1.0, rate_per_second * 10.0)
self.tokens = self.capacity
self.last_refill = time.monotonic()
self.lock = threading.Lock()
def _refill(self) -> None:
now = time.monotonic()
elapsed = now - self.last_refill
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate_per_second)
self.last_refill = now
def acquire(self, tokens: float = 1.0, timeout: float = 30.0) -> bool:
"""Block until requested tokens are available or timeout expires."""
deadline = time.monotonic() + timeout
while True:
with self.lock:
self._refill()
if self.tokens >= tokens:
self.tokens -= tokens
return True
deficit = tokens - self.tokens
wait_hint = deficit / self.rate_per_second
remaining = deadline - time.monotonic()
if remaining <= 0:
return False
time.sleep(min(wait_hint, remaining, 0.25))
Using time.monotonic() avoids clock-skew bugs during NTP adjustments, and computing wait_hint = deficit / self.rate_per_second prevents busy-spin polling while keeping threads responsive to timeout limits.
Async Request Queue for Batch Throughput
High-volume indexing or evaluation scripts can serialize requests through an asyncio.Queue worker with deterministic pacing between dispatches. Pairing the queue with asyncio.Semaphore bounds concurrent in-flight sockets cleanly.
import asyncio
from dataclasses import dataclass
from typing import Any, Awaitable, Callable
@dataclass
class QueuedJob:
prompt: str
future: asyncio.Future
class AsyncBatchDispatcher:
"""Bounded concurrency dispatcher for rate-limited async LLM batches."""
def __init__(self, handler: Callable[[str], Awaitable[Any]], requests_per_minute: int = 60, max_concurrency: int = 5):
self.handler = handler
self.min_interval = 60.0 / requests_per_minute
self.semaphore = asyncio.Semaphore(max_concurrency)
self.queue: asyncio.Queue[QueuedJob] = asyncio.Queue()
self._running = False
async def run_worker(self) -> None:
self._running = True
while self._running:
try:
job = await asyncio.wait_for(self.queue.get(), timeout=0.5)
except asyncio.TimeoutError:
continue
async def _execute(item: QueuedJob) -> None:
async with self.semaphore:
try:
result = await self.handler(item.prompt)
item.future.set_result(result)
except Exception as exc:
item.future.set_exception(exc)
asyncio.create_task(_execute(job))
await asyncio.sleep(self.min_interval)
async def submit(self, prompt: str) -> Any:
loop = asyncio.get_running_loop()
future = loop.create_future()
await self.queue.put(QueuedJob(prompt=prompt, future=future))
return await future
def stop(self) -> None:
self._running = False
Decoupling queue pacing (self.min_interval) from socket concurrency (self.semaphore) ensures long completions do not stall subsequent dispatches while capping maximum parallel open sockets.
Multi-Provider Fallback Cascades and Health Tracking
Single-provider retries cannot protect applications during regional provider outages or prolonged model capacity freezes. Fallback cascades preserve availability by failing over across models or independent AI vendors.
Same-Provider vs Cross-Provider Fallback Design
When designing fallback routes, architects balance capability parity, output schema consistency, latency variance, and cost escalation:
| Workload Type | Recommended Strategy | Example Primary -> Fallback Route | Primary Risk Managed |
|---|---|---|---|
| Customer-facing chat | Cross-provider cascade | gpt-6.2-sol -> claude-5-5-sonnet-20260928 -> gemini-4-hydrogen |
Full single-vendor outage |
| Strict JSON extraction | Same-provider downgrade | claude-5-5-sonnet-20260928 -> claude-5-5-haiku-20261007 |
Schema compliance drift |
| Mission-critical agents | Hybrid two-stage cascade | Same-provider fast tier -> Secondary vendor flagship | Both transient load and vendor outages |
| High-volume summarization | Cost-capped downgrade | gemini-4-neon -> gemini-4-hydrogen |
Latency spikes and token cost overruns |
Never route TerminalAPIError failures (such as malformed JSON schemas or disallowed content flags) blindly down a cross-provider fallback chain, because the same broken payload will fail across all providers.
Priority Cascade and Provider Health Cooldowns
A lightweight health tracker places degraded providers into temporary cooldown after repeated failures so healthy vendors receive traffic immediately without waiting for primary timeouts on every request.
import time
from dataclasses import dataclass
from enum import Enum
from typing import Dict, List
class ProviderStatus(Enum):
HEALTHY = "healthy"
DEGRADED = "degraded"
DOWN = "down"
@dataclass
class ModelRoute:
provider: str
model: str
priority: int
class ProviderHealthTracker:
"""Track per-provider error streaks and enforce exponential cooldown windows."""
def __init__(self, providers: List[str], trip_after: int = 3, max_cooldown_s: float = 300.0):
self.providers = providers
self.trip_after = trip_after
self.max_cooldown_s = max_cooldown_s
self.error_counts: Dict[str, int] = {p: 0 for p in providers}
self.cooldown_until: Dict[str, float] = {p: 0.0 for p in providers}
def record_success(self, provider: str) -> None:
self.error_counts[provider] = 0
self.cooldown_until[provider] = 0.0
def record_failure(self, provider: str) -> None:
self.error_counts[provider] += 1
if self.error_counts[provider] >= self.trip_after:
exponent = self.error_counts[provider] - self.trip_after
cooldown = min(self.max_cooldown_s, 30.0 * (2 ** exponent))
self.cooldown_until[provider] = time.monotonic() + cooldown
def get_status(self, provider: str) -> ProviderStatus:
if time.monotonic() < self.cooldown_until[provider]:
return ProviderStatus.DOWN
if self.error_counts[provider] > 0:
return ProviderStatus.DEGRADED
return ProviderStatus.HEALTHY
def healthy_routes(self, routes: List[ModelRoute]) -> List[ModelRoute]:
active = [r for r in routes if self.get_status(r.provider) != ProviderStatus.DOWN]
return sorted(active, key=lambda r: (self.error_counts[r.provider], r.priority))
Sorting routes by (self.error_counts[r.provider], r.priority) automatically demotes degraded endpoints behind healthy secondary providers while preserving configured priority during normal operation.
Circuit Breakers and Runaway Cost Protection
Retries recover from isolated blips, whereas circuit breakers and spending guards stop sustained outages and recursive loops from exhausting worker pools or monthly cloud budgets.
CLOSED, OPEN, and HALF_OPEN State Machine
A circuit breaker wraps upstream calls in three explicit states. In CLOSED, requests flow normally while tracking consecutive failures; once failures cross failure_threshold (typically 5), the breaker flips to OPEN and fails fast for recovery_timeout seconds before probing recovery in HALF_OPEN.
import time
from enum import Enum
from typing import Callable, TypeVar
T = TypeVar("T")
class CircuitState(Enum):
CLOSED = "closed"
OPEN = "open"
HALF_OPEN = "half_open"
class CircuitOpenError(Exception):
"""Raised immediately when an open circuit rejects outbound calls."""
class CircuitBreaker:
"""Fail-fast circuit breaker protecting worker pools during LLM provider outages."""
def __init__(self, failure_threshold: int = 5, recovery_timeout: float = 30.0, half_open_probes: int = 1):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.half_open_probes = half_open_probes
self.state = CircuitState.CLOSED
self.failure_count = 0
self.half_open_successes = 0
self.last_failure_time = 0.0
def call(self, func: Callable[[], T]) -> T:
if self.state == CircuitState.OPEN:
if time.monotonic() - self.last_failure_time >= self.recovery_timeout:
self.state = CircuitState.HALF_OPEN
self.half_open_successes = 0
else:
raise CircuitOpenError("Upstream LLM circuit breaker is OPEN")
try:
result = func()
self._on_success()
return result
except TerminalAPIError:
# Client validation bugs should not trip an upstream health breaker
raise
except Exception:
self._on_failure()
raise
def _on_success(self) -> None:
if self.state == CircuitState.HALF_OPEN:
self.half_open_successes += 1
if self.half_open_successes >= self.half_open_probes:
self.state = CircuitState.CLOSED
self.failure_count = 0
else:
self.failure_count = 0
def _on_failure(self) -> None:
self.failure_count += 1
self.last_failure_time = time.monotonic()
if self.state == CircuitState.HALF_OPEN or self.failure_count >= self.failure_threshold:
self.state = CircuitState.OPEN
Notice that TerminalAPIError re-raises without incrementing self.failure_count. Separating client prompt bugs from upstream provider faults stops malformed user requests from falsely tripping the circuit breaker for every healthy tenant.
Daily Spend Guards and Pre-Flight Token Estimation
Multi-step autonomous AI agent loops can enter recursive tool-calling cycles that burn thousands of dollars in minutes if left uncapped. Enforcing pre-flight token counting with the OpenAI Tiktoken Repository on GitHub paired with hard daily spend caps eliminates surprise invoices.
from datetime import datetime, timezone
import tiktoken
class SpendingGuard:
"""Thread-safe daily USD cap and pre-flight token estimator."""
def __init__(self, daily_limit_usd: float, input_per_1m: float = 2.00, output_per_1m: float = 10.00):
self.daily_limit_usd = daily_limit_usd
self.input_rate = input_per_1m / 1_000_000
self.output_rate = output_per_1m / 1_000_000
self.today_spend = 0.0
self.last_reset_date = datetime.now(timezone.utc).date()
self.encoder = tiktoken.get_encoding("o200k_base")
def _maybe_reset(self) -> None:
today = datetime.now(timezone.utc).date()
if today > self.last_reset_date:
self.today_spend = 0.0
self.last_reset_date = today
def estimate_max_cost(self, prompt: str, max_output_tokens: int = 1024) -> float:
input_tokens = len(self.encoder.encode(prompt))
return (input_tokens * self.input_rate) + (max_output_tokens * self.output_rate)
def authorize_or_raise(self, prompt: str, max_output_tokens: int = 1024) -> float:
self._maybe_reset()
est_cost = self.estimate_max_cost(prompt, max_output_tokens)
if self.today_spend + est_cost > self.daily_limit_usd:
raise TerminalAPIError(f"Daily budget cap ${self.daily_limit_usd:.2f} reached")
return est_cost
def record_actual_spend(self, input_tokens: int, output_tokens: int) -> None:
self._maybe_reset()
self.today_spend += (input_tokens * self.input_rate) + (output_tokens * self.output_rate)
Reserving worst-case cost using max_output_tokens before dispatch blocks oversized prompts before tokens leave your VPC, while record_actual_spend reconciles true usage from the response payload.
Timeout Management and Streaming Interruption Recovery
Unbounded HTTP sockets stall worker threads indefinitely during upstream gateway hangs. Calibrating deadlines by model speed tier and recovering gracefully from mid-stream drops keeps user experiences predictable.
Calibrating Timeouts Across Frontier Models
User-facing chat APIs should enforce strict 15-second to 30-second timeouts, whereas asynchronous deep-reasoning jobs can safely allow 60 to 120 seconds. When nesting multiple sequential LLM calls inside one request, individual step timeouts must sum below the outer HTTP gateway deadline.
| Model Tier | Typical Latency | Suggested API Timeout | Recommended Workload |
|---|---|---|---|
| GPT-6.1 Terra / GPT-6.2 Sol | 0.8s to 5s | 20 seconds | Interactive chat, structured extraction, agent routing |
| GPT-6.2 Astra (Reasoning) | 4s to 25s | 60 seconds | Complex multi-step analysis and architecture |
| Claude Haiku 5.5 | 0.6s to 3s | 15 seconds | High-throughput classification and guardrails |
| Claude Sonnet 5.5 / Opus 5.5 | 2s to 18s | 45 to 60 seconds | Agentic coding, tool orchestration, long-context RAG |
| Gemini 4 Hydrogen / Neon | 0.8s to 6s | 20 to 30 seconds | Multimodal extraction and 1M-context synthesis |
import asyncio
from typing import Optional
from openai import AsyncOpenAI
async_client = AsyncOpenAI()
async def completion_with_timeout(
prompt: str,
timeout_s: float = 20.0,
model: str = "gpt-6.2-sol",
) -> Optional[str]:
"""Execute an async LLM completion bounded by an explicit asyncio timeout."""
try:
response = await asyncio.wait_for(
async_client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
),
timeout=timeout_s,
)
return response.choices[0].message.content
except asyncio.TimeoutError:
return None
Returning None or raising a typed TransientAPIError on asyncio.TimeoutError lets the caller trigger a faster fallback model rather than blocking event loops.
Handling Partial Streaming Responses and Idempotency
Streaming endpoints split failures into two modes: pre-first-token timeouts (safe to retry transparently) and mid-stream socket drops after partial text already reached the client.
import logging
from typing import AsyncIterator
async def stream_with_partial_recovery(stream: AsyncIterator) -> AsyncIterator[str]:
"""Yield streamed chunks and preserve partial output if mid-stream errors occur."""
emitted_chars = 0
try:
async for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
emitted_chars += len(delta)
yield delta
except Exception as exc:
logging.warning("Stream interrupted after %d chars: %s", emitted_chars, exc)
if emitted_chars > 0:
yield "\n\n[Generation interrupted by upstream timeout. Retry to continue.]"
else:
raise TransientAPIError(f"Pre-stream failure: {exc}") from exc
If zero characters were emitted before the connection dropped, raising TransientAPIError permits a clean retry; if partial tokens already streamed to the browser, emitting a structured truncation marker prevents duplicated opening sentences.
For non-idempotent tool actions such as issuing customer refunds or creating database records, attach an explicit idempotency key derived from the logical workflow step ID before dispatching or retrying timed-out requests. Storing completed step digests in Redis or PostgreSQL guarantees a retry after an ambiguous 504 Gateway Timeout replays the cached tool result instead of mutating state twice.
import hashlib
def make_step_idempotency_key(workflow_id: str, step_name: str, payload_json: str) -> str:
"""Derive a deterministic idempotency key for non-idempotent agent tool calls."""
digest = hashlib.sha256(f"{workflow_id}:{step_name}:{payload_json}".encode("utf-8")).hexdigest()
return f"idem_{digest[:24]}"
Hashing the workflow identifier alongside the serialized tool payload ensures identical retries map to one unique execution slot even across separate worker pods.
Production Wrapper, Observability, and Chaos Testing
Combining token-bucket pacing, circuit breakers, retry classification, spend guards, and structured logging into one unified client eliminates duplicated error-handling logic across application microservices.
Unified ResilientLLMClient Architecture
The wrapper below integrates every defense pattern into a cohesive Python entry point targeting GPT-6.2 Sol with automatic fallback to Claude Sonnet 5.5 and Gemini 4 Hydrogen.
import time
from dataclasses import dataclass
from typing import Callable, List
@dataclass
class CompletionResult:
content: str
model_used: str
attempts: int
total_time_s: float
class ResilientLLMClient:
"""Unified LLM wrapper combining spend guard, rate limiter, breaker, jitter, and fallback."""
def __init__(
self,
routes: List[tuple[str, Callable[[str], str]]],
daily_budget_usd: float = 50.0,
rate_per_second: float = 2.0,
max_retries_per_route: int = 3,
):
self.routes = routes
self.max_retries = max_retries_per_route
self.spend_guard = SpendingGuard(daily_limit_usd=daily_budget_usd)
self.rate_limiter = TokenBucket(rate_per_second=rate_per_second)
self.breakers = {name: CircuitBreaker() for name, _ in routes}
def complete(self, prompt: str) -> CompletionResult:
self.spend_guard.authorize_or_raise(prompt)
start = time.monotonic()
total_attempts = 0
last_error: Exception | None = None
for route_name, fn in self.routes:
breaker = self.breakers[route_name]
def _attempt_once() -> str:
nonlocal total_attempts
total_attempts += 1
if not self.rate_limiter.acquire(timeout=15.0):
raise TransientAPIError("Local TokenBucket queue timeout")
return breaker.call(lambda: fn(prompt))
try:
output = retry_with_full_jitter(_attempt_once, max_retries=self.max_retries)
return CompletionResult(
content=output,
model_used=route_name,
attempts=total_attempts,
total_time_s=round(time.monotonic() - start, 3),
)
except TerminalAPIError:
raise
except Exception as exc:
last_error = exc
continue
raise RuntimeError(f"All LLM routes exhausted after {total_attempts} attempts: {last_error}")
Every route receives its own isolated CircuitBreaker instance so an OpenAI capacity freeze does not block calls to Anthropic or Google Gemini. For teams expanding beyond single-turn calls into multi-turn agent streams, see our Claude API streaming and caching patterns guide.
Provider-Specific SDK Handlers and Request-ID Logging
Each vendor SDK exposes distinct exception hierarchies and support trace headers. OpenAI includes x-request-id, Anthropic attaches request-id, and Google’s current google-genai SDK raises genai.errors.APIError with HTTP status codes.
import json
import logging
from datetime import datetime, timezone
import anthropic
from google import genai
from google.genai import errors as genai_errors
def call_anthropic_classified(client: anthropic.Anthropic, prompt: str) -> str:
"""Invoke Claude Sonnet 5.5 and classify Anthropic token-bucket vs spend-cap errors."""
try:
msg = client.messages.create(
model="claude-5-5-sonnet-20260928",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
)
return msg.content[0].text
except anthropic.RateLimitError as exc:
retry_after = exc.response.headers.get("retry-after") if getattr(exc, "response", None) else None
if retry_after is None:
raise TerminalAPIError("Anthropic 429 without Retry-After (check spend limit)") from exc
raise TransientAPIError("Anthropic rate limit", retry_after=float(retry_after)) from exc
except anthropic.APIStatusError as exc:
if exc.status_code in (500, 502, 503, 529):
raise TransientAPIError(f"Anthropic transient {exc.status_code}") from exc
raise TerminalAPIError(f"Anthropic client error {exc.status_code}: {exc}") from exc
def call_gemini_classified(client: genai.Client, prompt: str) -> str:
"""Invoke Gemini 4 Hydrogen via google-genai SDK and classify RESOURCE_EXHAUSTED."""
try:
resp = client.models.generate_content(model="gemini-4-hydrogen", contents=prompt)
return resp.text or ""
except genai_errors.APIError as exc:
if exc.code in (429, 500, 503, 504):
raise TransientAPIError(f"Gemini transient {exc.code}: {exc.message}") from exc
raise TerminalAPIError(f"Gemini terminal {exc.code}: {exc.message}") from exc
def emit_structured_log(request_id: str, model: str, prompt_tokens: int, completion_tokens: int, latency_ms: float, status: str, error_type: str | None = None) -> None:
payload = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"request_id": request_id,
"model": model,
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"latency_ms": round(latency_ms, 2),
"status": status,
"error_type": error_type,
}
logging.info(json.dumps(payload))
Logging request_id in UTC JSON allows on-call engineers to correlate local trace IDs directly with vendor support escalations and filter dashboards by error type or P95 latency.
Prometheus Telemetry and Automated Chaos Tests
Dashboards should alert when error rates exceed 5% over 5 minutes, P95 latency doubles baseline norms, or daily quota utilization crosses 80%. Pairing Prometheus counters with deterministic unittest.mock chaos tests verifies that retries, jitter, and circuit breakers work before production traffic hits them.
from unittest.mock import MagicMock
import pytest
from prometheus_client import Counter, Histogram
AI_REQUESTS = Counter("ai_requests_total", "Total LLM API calls", ["model", "status"])
AI_LATENCY = Histogram("ai_request_latency_seconds", "LLM API latency", ["model"])
def tracked_call(model: str, fn: Callable[[], str]) -> str:
with AI_LATENCY.labels(model=model).time():
try:
output = fn()
AI_REQUESTS.labels(model=model, status="success").inc()
return output
except Exception:
AI_REQUESTS.labels(model=model, status="error").inc()
raise
def test_circuit_breaker_trips_and_fails_fast() -> None:
breaker = CircuitBreaker(failure_threshold=3, recovery_timeout=60.0)
failing_fn = MagicMock(side_effect=TransientAPIError("503 overloaded"))
for _ in range(3):
with pytest.raises(TransientAPIError):
breaker.call(failing_fn)
assert breaker.state == CircuitState.OPEN
with pytest.raises(CircuitOpenError):
breaker.call(lambda: "should not invoke upstream")
Running failure-injection suites alongside staging chaos tools such as toxiproxy and pytest-timeout guarantees your resilience layer catches rate-limit storms and upstream hangs in CI. Automated tests should assert four core invariants on every release: backoff delays respect Retry-After overrides, terminal 400/insufficient_quota faults never trigger retries, CircuitBreaker trips into OPEN after the configured threshold, and SpendingGuard blocks calls once daily spend reaches the configured cap.
# prometheus-alerts.yml: Production LLM error and quota thresholds
groups:
- name: llm-api-resilience
rules:
- alert: HighLLMErrorRate
expr: sum(rate(ai_requests_total{status="error"}[5m])) / sum(rate(ai_requests_total[5m])) > 0.05
for: 5m
- alert: LLMLatencyP95Degraded
expr: histogram_quantile(0.95, sum(rate(ai_request_latency_seconds_bucket[5m])) by (le, model)) > 20
for: 5m
Encoding these Prometheus rules directly into CI/CD alert definitions bridges application-level Python wrappers with on-call incident response before minor provider throttles cascade into user-facing outages.
Frequently Asked Questions
How many retries should teams configure for production LLM APIs?
User-facing web applications should configure at most 3 retries with exponential backoff and full jitter so total request latency remains within interactive expectations. Asynchronous background workers and batch pipelines can safely configure 5 to 7 retries with wider backoff ceilings.
When should an application NOT retry an HTTP 429 rate-limit error?
Never retry HTTP 429 errors triggered by insufficient_quota, exhausted prepaid balances, or Anthropic rate_limit_error responses lacking a Retry-After header due to monthly workspace spend caps. Those failures are terminal until account quotas or billing limits increase.
Should applications always fall back to another model during outages?
Route to cross-provider fallback models only when downstream workflows tolerate minor shifts in phrasing, reasoning depth, and latency. Pipelines enforcing strict structured JSON schemas or safety policies should test fallback models identically in CI or fail fast gracefully.
How do engineering teams handle context length errors in production?
HTTP 400 context overflow errors never succeed on retry and must trigger TerminalAPIError handling. Applications should estimate prompt token counts locally with libraries like Tiktoken before dispatch, truncating stale conversation turns or reducing retrieved document chunks early.
Is it safe to retry LLM requests that timed out mid-flight?
Read-only completion calls are safe to retry idempotently, although duplicate invocations bill additional tokens if the provider completed generation after client timeout. Agentic tool calls that mutate external databases or financial state must attach idempotency keys before retrying.
What is the difference between rate limiting and circuit breaking?
Proactive rate limiting uses constructs like a TokenBucket to pace outgoing request and token velocity below known provider quotas. A circuit breaker tracks live upstream error streaks and temporarily halts all calls (OPEN state) during sustained service outages.
How should teams log LLM errors for provider support escalation?
Record UTC timestamps, provider name, model identifier, HTTP status code, prompt and completion token counts, elapsed latency, and vendor request IDs (x-request-id for OpenAI, request-id for Anthropic). Vendor support teams rely on request IDs to inspect server-side traces.