HTTP 429 dalle API di AI: retry con backoff e Retry-After (Python, Node.js, Java)
Quando l'API di un modello risponde 429 Too Many Requests, riprovare subito peggiora le cose. Cosa dicono gli standard, quali errori ripetere e codice di retry testato, senza dipendenze, in Python, JavaScript e Java.

Prima o poi ogni applicazione che chiama l'API di un modello linguistico riceve questa risposta:
HTTP/1.1 429 Too Many Requests
Retry-After: 20
Le API di AI limitano quante richieste e quanti token puoi inviare al minuto, e una sola funzione molto usata può raggiungere quei limiti. La soluzione ingenua, riprovare subito in un ciclo, manda ancora più richieste a un servizio che ti ha appena chiesto di rallentare. Questa guida mostra una strategia di retry che funziona, con codice da incollare in Python, Node.js o Java. Le tre versioni usano solo la libreria standard e superano lo stesso test.
Cosa significano 429 e Retry-After
Il comportamento è definito da due standard:
- la RFC 6585, sezione 4 definisce 429 Too Many Requests: il client ha inviato troppe richieste in un certo intervallo di tempo. La risposta può contenere l'intestazione
Retry-After; - la RFC 9110, sezione 10.2.3 definisce Retry-After. Il valore è un numero di secondi (
Retry-After: 20) oppure una data HTTP (Retry-After: Fri, 31 Oct 2026 09:00:00 GMT).
Il tuo codice deve gestire entrambe le forme. Molti client leggono solo il numero e ignorano in silenzio la forma con la data.
Quali errori ripetere
| Codice | Ripetere? | Perché |
|---|---|---|
| 429 Too Many Requests | Sì, dopo aver atteso | Hai raggiunto un limite; si azzererà. |
| 500, 502, 503, 504 | Sì, poche volte | Problemi temporanei del server o del gateway. |
| 400, 422 | No | La richiesta è sbagliata (JSON non valido, prompt troppo lungo). Riprovare ripete lo stesso errore. |
| 401, 403 | No | Chiave mancante o non valida, oppure permessi insufficienti. Va corretta la configurazione. |
| 404 | No | URL o nome del modello sbagliato. |
Anche gli errori di rete e i timeout si possono ripetere, con lo stesso backoff. Il nostro riepilogo dei codici HTTP spiega ogni codice nel dettaglio.
Quanto aspettare
- Se il server invia
Retry-After, usalo. Il server sa quando il tuo limite si azzera; tu no. - Altrimenti usa il backoff esponenziale con jitter. Il tetto raddoppia a ogni tentativo (0,5 s, 1 s, 2 s, 4 s…) e l'attesa reale è un valore casuale tra zero e quel tetto ("full jitter"). La casualità evita che tanti client falliti insieme riprovino insieme. AWS descrive e confronta queste strategie in Exponential Backoff And Jitter.
- Metti un limite all'attesa e al numero di tentativi. Dall'altra parte c'è un utente che aspetta: dopo qualche tentativo, fallisci con un errore chiaro.
Puoi provare impostazioni diverse nel nostro simulatore di retry e backoff, che mostra quando parte ogni tentativo e come si distribuisce il carico nel tempo.
Python (libreria standard)
import email.utils
import json
import random
import time
import urllib.error
import urllib.request
RETRYABLE = {429, 500, 502, 503, 504}
def retry_after_seconds(value):
"""Retry-After is either a number of seconds or an HTTP date (RFC 9110, section 10.2.3)."""
if not value:
return None
value = value.strip()
if value.isdigit():
return int(value)
try:
when = email.utils.parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
return max(0.0, when.timestamp() - time.time())
def post_json(url, payload, headers=None, max_attempts=5, base=0.5, cap=30.0):
body = json.dumps(payload).encode()
for attempt in range(1, max_attempts + 1):
req = urllib.request.Request(url, data=body, method="POST",
headers={"content-type": "application/json", **(headers or {})})
try:
with urllib.request.urlopen(req, timeout=60) as resp:
return json.loads(resp.read())
except urllib.error.HTTPError as err:
if err.code not in RETRYABLE or attempt == max_attempts:
raise
wait = retry_after_seconds(err.headers.get("Retry-After"))
if wait is None:
# Exponential backoff with full jitter: random value between 0 and base * 2^attempt, capped.
wait = random.uniform(0, min(cap, base * 2 ** attempt))
wait = min(wait, cap)
print(f"HTTP {err.code}, attempt {attempt}/{max_attempts}, waiting {wait:.1f}s")
time.sleep(wait)
Se usi httpx o requests la logica è la stessa: leggi il codice di stato e l'intestazione Retry-After dalla risposta e attendi prima del tentativo successivo.
JavaScript (Node.js 18+)
const RETRYABLE = new Set([429, 500, 502, 503, 504]);
export function retryAfterMs(value) {
if (!value) return null;
const v = value.trim();
if (/^\d+$/.test(v)) return Number(v) * 1000; // seconds
const date = Date.parse(v); // or an HTTP date
return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export async function postJson(url, payload, { headers = {}, maxAttempts = 5, baseMs = 500, capMs = 30_000 } = {}) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const res = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json', ...headers },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(60_000),
});
if (res.ok) return res.json();
if (!RETRYABLE.has(res.status) || attempt === maxAttempts) {
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
let wait = retryAfterMs(res.headers.get('retry-after'));
if (wait === null) wait = Math.random() * Math.min(capMs, baseMs * 2 ** attempt); // full jitter
wait = Math.min(wait, capMs);
console.log(`HTTP ${res.status}, attempt ${attempt}/${maxAttempts}, waiting ${(wait / 1000).toFixed(1)}s`);
await res.body?.cancel();
await sleep(wait);
}
}
res.body?.cancel() libera il corpo dell'errore non letto prima del tentativo successivo, così le connessioni non restano occupate.
Java (11+, java.net.http)
private static final Set<Integer> RETRYABLE = Set.of(429, 500, 502, 503, 504);
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
static Optional<Duration> retryAfter(String value) {
if (value == null || value.isBlank()) return Optional.empty();
String v = value.trim();
if (v.chars().allMatch(Character::isDigit)) return Optional.of(Duration.ofSeconds(Long.parseLong(v)));
try {
Instant when = ZonedDateTime.parse(v, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant();
Duration d = Duration.between(Instant.now(), when);
return Optional.of(d.isNegative() ? Duration.ZERO : d);
} catch (DateTimeParseException e) {
return Optional.empty();
}
}
public String postJson(String url, String json, int maxAttempts) throws IOException, InterruptedException {
long baseMs = 500, capMs = 30_000;
for (int attempt = 1; ; attempt++) {
HttpRequest req = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(60))
.header("content-type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> res = http.send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() < 300) return res.body();
if (!RETRYABLE.contains(res.statusCode()) || attempt == maxAttempts) {
throw new IOException("HTTP " + res.statusCode() + ": " + res.body());
}
long ceiling = Math.min(capMs, baseMs << attempt);
long waitMs = retryAfter(res.headers().firstValue("retry-after").orElse(null))
.map(Duration::toMillis)
.orElseGet(() -> ThreadLocalRandom.current().nextLong(ceiling + 1)); // full jitter
waitMs = Math.min(waitMs, capMs);
Thread.sleep(waitMs);
}
}
DateTimeFormatter.RFC_1123_DATE_TIME interpreta il formato di data HTTP usato da Retry-After. Se usi Spring AI invece di chiamare l'API direttamente, i retry sono già inclusi; controlla i valori predefiniti nella nostra guida a Spring AI.
Provalo senza spendere un centesimo
Non aspettare un vero limite per scoprire se il tuo codice di retry funziona. Il repository contiene un server di prova di 30 righe che risponde 429 con Retry-After: 1, poi 429 con una data HTTP, poi 503 senza intestazione, poi 200. Tutti e tre i client qui sopra superano il test:
HTTP 429, attempt 1/5, waiting 1.0s
HTTP 429, attempt 2/5, waiting 0.6s
HTTP 503, attempt 3/5, waiting 0.3s
{'ok': True, 'attempts': 4}
Lancia ./test_retry.sh nella cartella dell'esempio per ripetere il test, oppure usa il tester di richieste HTTP sul tuo endpoint per vedere le intestazioni reali.
I retry non sono un limitatore di frequenza
I retry servono a superare limiti occasionali. Se ricevi 429 di continuo, rallenta dalla tua parte:
- limita le richieste in parallelo (un piccolo pool o un semaforo davanti al client dell'API);
- metti in coda il lavoro in background invece di inviarlo tutto insieme;
- invia meno token: prompt più brevi, contesto più piccolo, risposte in cache per le domande ripetute;
- leggi le intestazioni sui limiti che il tuo fornitore restituisce (molti indicano richieste e token rimanenti) e rallenta prima di arrivare a zero.
Un'ultima avvertenza: una richiesta ripetuta è una nuova richiesta. Con le API di AI, una chiamata andata in timeout dalla tua parte può essere stata comunque elaborata e fatturata. Tieni basso il numero di tentativi e registra ogni retry, così lo ritrovi nei costi.
L'esempio completo e testato di questo articolo è nel nostro repository pubblico: adamant-solutions/ai-dev-examples/retry-429