Errori di limitazione del numero di richieste

Ultimo aggiornamento: 3 mesi fa

Se vedi 429 Too Many Requests, stai chiamando l’API troppo frequentemente. Ecco come gestirlo correttamente.

L’errore

HTTP 429 Too Many Requests
{
  "error": "Limit exceed."
}

Perché succede

Le limitazioni di velocità proteggono l’API da un uso eccessivo:

  • Troppe richieste in un breve periodo

  • Polling aggressivo o scraping

  • Nessun ritardo tra le richieste

  • Richieste concorrenti senza throttling

Strategia di backoff esponenziale

Il modo migliore per gestire le limitazioni di velocità è il backoff esponenziale: attendi più a lungo dopo ogni nuovo tentativo:

async function fetchWithBackoff(url, options, maxRetries = 5) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);
      
      if (response.status === 429) {
        const waitTime = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s, 8s, 16s
        console.log(`Rate limited. Waiting ${waitTime}ms before retry ${attempt + 1}/${maxRetries}`);
        
        await new Promise(resolve => setTimeout(resolve, waitTime));
        continue;
      }
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      
      return await response.json();
      
    } catch (error) {
      if (attempt === maxRetries - 1) throw error;
    }
  }
  
  throw new Error('Max retries exceeded');
}

Prevenire le limitazioni di velocità

Aggiungi ritardi tra le richieste:

// Sbagliato: richieste a raffica
for (const id of mediaIds) {
  await api.getResource(id); // Nessun ritardo
}
// Giusto: richieste con throttling
for (const id of mediaIds) {
  await api.getResource(id);
  await sleep(500); // Ritardo di 500ms
}

Raggruppa le operazioni:

// Elabora in batch da 10 con ritardi
const batchSize = 10;
for (let i = 0; i < mediaIds.length; i += batchSize) {
  const batch = mediaIds.slice(i, i + batchSize);
  await Promise.all(batch.map(id => api.getResource(id)));
  
  if (i + batchSize < mediaIds.length) {
    await sleep(2000); // 2s tra i batch
  }
}

Usa la cache delle risposte:

const cache = new Map();
async function getCachedResource(mediaId) {
  if (cache.has(mediaId)) {
    return cache.get(mediaId);
  }
  
  const data = await api.getResource(mediaId);
  cache.set(mediaId, data);
  return data;
}

Cosa NON fare

  • ❌ Riprova immediatamente senza ritardo

  • ❌ Effettuare richieste in parallelo senza limiti

  • ❌ Ignorare gli errori 429

  • ❌ Usare ritardi fissi e brevi (usa sempre il backoff esponenziale)

Se i problemi persistono

Contatta l’assistenza per gli sviluppatori se hai davvero bisogno di limiti di velocità più alti per il tuo caso d’uso. Fornisci dettagli su:

  • La tua applicazione e il tuo caso d’uso

  • Volume di richieste previsto

  • Implementazione attuale (con backoff)

Questo articolo è stato utile?