Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)48k · #3777

api-rate-limit-handler

Skill này làm gì

Công cụ này giúp chương trình của bạn xử lý giới hạn tốc độ từ các API bên ngoài. Nếu một API từ chối yêu cầu vì quá tải hoặc lý do khác, nó sẽ thử lại một cách thông minh sau một khoảng thời gian chờ.

Khi nào nên dùng

  • ✓Khi gọi các API có giới hạn số lần yêu cầu dữ liệu.
  • ✓Khi bạn nhận được lỗi như “429 Too Many Requests” hoặc lỗi máy chủ tạm thời.
  • ✓Khi xây dựng chương trình cần đáng tin cậy khi dùng dịch vụ của bên thứ ba.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/api-rate-limit-handler/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/api-rate-limit-handler/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm thế nào để chương trình của tôi thử lại nếu API phản hồi chậm?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Trước tiên, công cụ kiểm tra loại lỗi để biết có nên thử lại không. Nếu có, nó chờ một khoảng thời gian (có thể do chính API quy định hoặc được tính tự động) trước khi thử lại, để tránh quá tải.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

API Rate Limit Handler

Overview

A skill for implementing production-grade rate limiting, exponential backoff, and retry strategies when integrating with external APIs. Prevents cascading failures, respects upstream quotas, and keeps your application resilient under load.

When to Use This Skill

  • Use when calling external APIs that enforce rate limits (OpenAI, Stripe, GitHub, etc.)
  • Use when you receive 429 Too Many Requests or 5xx errors and need graceful recovery
  • Use when building a client that must respect Retry-After headers
  • Use when designing a system that fans out to multiple API providers
  • Use when the user says "handle rate limits", "add retry logic", "backoff strategy", or "don't get throttled"

How It Works

Step 1: Classify the response

Determine whether a failed request is retryable or terminal.

Status Classification Action
200-299 Success Return response
400, 401, 403, 404 Terminal client error Do not retry — fix the request
408, 429 Retryable (rate limit / timeout) Retry with backoff
500, 502, 503, 504 Retryable (server error) Retry with backoff

Step 2: Parse rate limit headers

Always check upstream hints before computing your own delay.

function getRetryDelay(
  response: Response,
  attempt: number,
  maxDelayMs = 60_000
): number {
  // Prefer upstream hints
  const retryAfter = response.headers.get("Retry-After");
  if (retryAfter) {
    const seconds = Number(retryAfter);
    if (Number.isFinite(seconds) && seconds >= 0) {
      return seconds * 1000;
    }
    // HTTP-date format
    const date = new Date(retryAfter).getTime();
    if (Number.isFinite(date)) {
      return Math.max(0, date - Date.now());
    }
  }

  // GitHub documents x-ratelimit-reset as Unix epoch seconds.
  const resetHeader = response.headers.get("x-ratelimit-reset");
  const githubReset = resetHeader === null || resetHeader.trim() === "" ? NaN : Number(resetHeader);
  if (Number.isFinite(githubReset)) {
    return Math.max(0, githubReset * 1000 - Date.now());
  }

  // Fallback: capped exponential backoff with full jitter.
  const cap = Math.min(1000 * 2 ** attempt, maxDelayMs);
  return Math.floor(Math.random() * cap);
}

Upstream hints are minimum waits; never truncate them to retry early. If a hint exceeds the remaining operation budget, stop without scheduling another request. The cap applies only to fallback backoff.

Provider-specific reset headers do not share one unit or format. For example, some APIs return durations while GitHub returns epoch seconds. Parse an additional header only after checking that provider's current documentation.

Step 3: Implement the retry loop

async function fetchWithRetry(
  url: string,
  options: RequestInit,
  maxRetries = 3,
  maxElapsedMs = 120_000,
  retryNonIdempotent = false
): Promise<Response> {
  const startedAt = Date.now();
  const method = (options.method ?? "GET").toUpperCase();
  const replaySafe = ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"].includes(method)
    || retryNonIdempotent;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const response = await fetch(url, options);

    if (response.ok) return response;

    // Terminal errors — do not retry
    if (![408, 429, 500, 502, 503, 504].includes(response.status)) {
      throw new Error(`Terminal error ${response.status}: ${response.statusText}`);
    }

    if (!replaySafe) {
      throw new Error(
        `${method} was not retried because replay safety was not explicitly established`
      );
    }

    // Retryable — but exhausted attempts
    if (attempt === maxRetries) {
      throw new Error(`Failed after ${maxRetries} retries: ${response.status}`);
    }

    const remaining = maxElapsedMs - (Date.now() - startedAt);
    const delay = getRetryDelay(response, attempt);
    if (remaining <= 0 || delay > remaining) {
      throw new Error(`Retry cannot be scheduled within ${maxElapsedMs}ms`);
    }

    // Release the connection before waiting when the body is not needed.
    await response.body?.cancel();
    console.warn(
      `Request failed (${response.status}), retrying in ${Math.round(delay)}ms (attempt ${attempt + 1}/${maxRetries})`
    );
    await new Promise(resolve => setTimeout(resolve, delay));
  }

  throw new Error("Unreachable");
}

Step 4: Add a client-side rate limiter (proactive)

…

Câu hỏi thường gặp

“Rate limits” là gì?

Đây là quy định do các dịch vụ trực tuyến đặt ra để giới hạn số yêu cầu mà một người dùng hoặc chương trình có thể gửi trong một khoảng thời gian. Điều này ngăn một người dùng làm quá tải dịch vụ.

“Retry with backoff” nghĩa là gì?

Nghĩa là nếu một yêu cầu thất bại, chương trình sẽ chờ một khoảng thời gian rồi mới thử lại. Thời gian chờ tăng dần sau mỗi lần thất bại, để dịch vụ có thời gian phục hồi.

Lỗi “429” và “5xx” là gì?

Lỗi “429” nghĩa là bạn đã vượt quá giới hạn yêu cầu. Lỗi “5xx” (như 500, 503) cho thấy có vấn đề ở máy chủ của API, không phải do yêu cầu của bạn, và thường chỉ là tạm thời.

Chi tiết

Mô tả gốc của tác giả

Implement bounded, idempotency-aware API throttling, backoff, and retry handling for 429 and transient 5xx responses.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#3777
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự