Rate Limiting

Come comprendere e gestire i rate limit, le quote giornaliere e la frequenza burst di TCG Price Lookup API.


Rate limit per piano

PianoRichieste giornaliereFrequenza burst
Gratuito2001 richiesta/3 sec
Trader10.0001 richiesta/sec
Business100.0003 richieste/sec

I limiti giornalieri si azzerano ogni giorno a mezzanotte UTC.

Header di rate limit

Ogni risposta API include informazioni sullo stato corrente del rate limit:

X-RateLimit-Limit: 200
X-RateLimit-Remaining: 150
X-RateLimit-Reset: 1704067200
HeaderDescrizione
X-RateLimit-LimitNumero massimo di richieste nel periodo
X-RateLimit-RemainingRichieste rimanenti
X-RateLimit-ResetTimestamp Unix in cui il limite si azzera

Gestione degli errori 429

Quando si supera il rate limit, viene restituito 429 Too Many Requests:

{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Daily request limit reached. Resets at midnight UTC."
  }
}

Usa l’header Retry-After per sapere quanto aspettare prima della prossima richiesta:

async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    const response = await fetch(url, options);
    
    if (response.status === 429) {
      const retryAfter = parseInt(response.headers.get('retry-after') || '60');
      await new Promise(r => setTimeout(r, retryAfter * 1000));
      continue;
    }
    
    return response;
  }
}

Best practice

Usa le richieste batch (piano Trader o superiore):

// Inefficiente: 20 richieste separate
for (const id of cardIds) {
  await tcg.cards.get(id); // ✗
}

// Efficiente: 1 richiesta batch
const cards = await tcg.cards.batch(cardIds); // ✓

Usa la cache delle risposte:

I prezzi vengono aggiornati ogni poche ore. Una cache a breve termine (5-15 minuti) è appropriata per molti casi d’uso:

const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 minuti

async function getCachedCard(id) {
  const cached = cache.get(id);
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.data;
  }
  const data = await tcg.cards.get(id);
  cache.set(id, { data, timestamp: Date.now() });
  return data;
}