Backoff esponenziale su HTTP 429
In questa pagina
Comprendere l’errore 429
Un errore HTTP 429 significa che hai superato i limiti di frequenza (rate limits) dell’API. Il server xAI rifiuta temporaneamente le tue richieste per proteggere l’infrastruttura. Questo errore è normale in un contesto di elaborazione batch: indica semplicemente che stai inviando richieste troppo velocemente.
La reazione appropriata non è rinunciare, ma attendere prima di riprovare. Il backoff esponenziale è la strategia standard per gestire questa situazione.
Come funziona il backoff esponenziale
Invece di riprovare immediatamente (il che scatenerebbe un altro 429), attendi un ritardo crescente tra ogni tentativo:
- 1° fallimento: attendi 1 secondo
- 2° fallimento: attendi 2 secondi
- 3° fallimento: attendi 4 secondi
- 4° fallimento: attendi 8 secondi
- 5° fallimento: rinuncia
Il ritardo raddoppia a ogni tentativo, da qui il termine «esponenziale». Questo dà al server il tempo di recuperare capacità.
Implementazione manuale
import asyncio
import random
from openai import RateLimitError
async def request_with_backoff(
prompt: str,
max_retries: int = 5,
base_delay: float = 1.0
) -> str:
for attempt in range(max_retries):
try:
response = await client.chat.completions.create(
model="grok-4.5",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
except RateLimitError:
if attempt == max_retries - 1:
raise # ultimo tentativo, propaga l'errore
delay = base_delay * (2 ** attempt)
jitter = random.uniform(0, delay * 0.1)
wait_time = delay + jitter
print(f"Rate limit hit, attempt {attempt + 1}/{max_retries}. "
f"Waiting {wait_time:.1f}s")
await asyncio.sleep(wait_time)
Il jitter (variazione casuale) è importante. Se più coroutine ricevono un 429 allo stesso tempo, senza jitter riproverebbero tutte esattamente nello stesso istante, innescando un altro 429. Il jitter desincronizza i tentativi.
Utilizzo della libreria tenacity
Per l’uso in produzione, la libreria tenacity semplifica l’implementazione:
from tenacity import (
retry,
stop_after_attempt,
wait_exponential,
retry_if_exception_type
)
from openai import RateLimitError
@retry(
stop=stop_after_attempt(5),
wait=wait_exponential(multiplier=1, min=1, max=60),
retry=retry_if_exception_type(RateLimitError)
)
async def robust_request(prompt: str) -> str:
response = await client.chat.completions.create(
model="grok-4.5",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
Il decoratore @retry intercetta RateLimitError, attende un ritardo esponenziale (tra 1 e 60 secondi) e riprova fino a 5 volte. Il codice della funzione rimane pulito e leggibile.
Combinare backoff e semaforo
In pratica, combini il backoff con un semaforo per un controllo totale:
async def resilient_batch(prompts: list[str], max_concurrent: int = 5) -> list[str]:
sem = Semaphore(max_concurrent)
async def single_request(prompt: str) -> str:
async with sem:
return await request_with_backoff(prompt)
tasks = [single_request(p) for p in prompts]
return await asyncio.gather(*tasks, return_exceptions=True)
Il semaforo previene il sovraccarico dell’API, mentre il backoff gestisce gli errori 429 residui. Questa doppia protezione è la configurazione raccomandata per la produzione.
Adattare il backoff al tipo di errore
Non tutti gli errori giustificano un nuovo tentativo. Ecco una classificazione:
from openai import RateLimitError, APITimeoutError, APIConnectionError, BadRequestError
async def smart_retry(prompt: str, max_retries: int = 5) -> str:
for attempt in range(max_retries):
try:
return await client.chat.completions.create(
model="grok-4.5",
messages=[{"role": "user", "content": prompt}]
)
except RateLimitError:
delay = 2 ** attempt
await asyncio.sleep(delay)
except (APITimeoutError, APIConnectionError):
delay = 2 ** attempt
await asyncio.sleep(delay)
except BadRequestError:
raise # errore nel prompt, inutile riprovare
Gli errori 429 (limite di frequenza), i timeout e gli errori di connessione meritano un nuovo tentativo. Tuttavia, un BadRequestError (prompt non valido) non verrà risolto riprovando.
Punti chiave
- Un errore 429 è normale e atteso durante l’elaborazione batch
- Il backoff esponenziale raddoppia il ritardo tra ogni tentativo (1s, 2s, 4s, 8s…)
- Il jitter desincronizza i nuovi tentativi per evitare collisioni
- La libreria
tenacitysemplifica l’implementazione in produzione - Combina sempre semaforo e backoff per la massima resilienza
- Non riprovare in caso di errori di richiesta non valida (
BadRequestError)