Rate Limiting

การทำความเข้าใจและจัดการ rate limit, quota รายวัน และ burst rate ของ TCG Price Lookup API


Rate Limit ตามแพ็กเกจ

แพ็กเกจRequests/วันBurst Rate
ฟรี2001 req/3 วินาที
Trader10,0001 req/วินาที
Business100,0003 req/วินาที

Limit รายวันรีเซ็ตทุกวันที่ เที่ยงคืน UTC

Rate Limit Header

ทุก API response มีข้อมูล rate limit ปัจจุบัน:

X-RateLimit-Limit: 200
X-RateLimit-Remaining: 150
X-RateLimit-Reset: 1704067200
Headerคำอธิบาย
X-RateLimit-Limitจำนวน request สูงสุดต่อช่วงเวลา
X-RateLimit-Remainingจำนวน request ที่เหลือ
X-RateLimit-ResetUNIX timestamp ที่ limit จะรีเซ็ต

การจัดการ Error 429

เมื่อเกิน rate limit จะได้รับ 429 Too Many Requests:

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

ใช้ header Retry-After เพื่อดูเวลาที่ต้องรอก่อน request ถัดไป:

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

ใช้ Batch Request (แพ็กเกจ Trader ขึ้นไป):

// ไม่มีประสิทธิภาพ: 20 request แยกกัน
for (const id of cardIds) {
  await tcg.cards.get(id); // ✗
}

// มีประสิทธิภาพ: 1 batch request
const cards = await tcg.cards.batch(cardIds); // ✓

Cache Response:

ราคาอัปเดตทุกไม่กี่ชั่วโมง การ cache ระยะสั้น (5–15 นาที) เหมาะสำหรับ use case ส่วนใหญ่:

const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 นาที

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;
}