跳到正文
Skillpedia
API 与服务器(后端)48k · #3777

api-rate-limit-handler

它能做什么

这个工具可以帮助你的程序应对外部 API 的速率限制。如果某个 API 因为负载过高或其他原因拒绝了你的请求,它会智能地延迟一段时间后再次尝试。

适用场景

  • ✓调用有请求频率限制的 API 时。
  • ✓收到“429 Too Many Requests”之类的错误,或临时服务器错误时。
  • ✓构建需要依赖第三方服务且要保证可靠性的程序时。

技能链接

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

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/api-rate-limit-handler/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“如果 API 响应很慢,我怎样让程序自动重试?”

每周 5 个新技能,1 分钟读完。

工作原理

首先,它会检查错误类型,判断是否应该重试。如果需要重试,它会先等待一段时间(等待时长可以由 API 本身指定,也可以自动计算),然后再重试,从而避免过载。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

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)

…

常见问题

什么是“速率限制”(rate limits)?

这是在线服务设定的规则,用来限制用户或程序在一定时间内可以发出的请求数量。这样可以防止某一个用户把服务压垮。

“带退避的重试”(retry with backoff)是什么意思?

意思是请求失败后,程序会等待一段时间再试。每失败一次,等待时间就会变得更长(即退避),给服务留出恢复的时间。

“429”和“5xx”错误是什么?

“429”错误表示你超出了请求次数限制。“5xx”错误(如 500、503)表示 API 的服务器出了问题,而不是你的请求有问题,通常是暂时性的。

详情

作者的原始描述

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

repo: sickn33/agentic-awesome-skills

热度

GitHub 星标
48k
排名
#3777
许可证
MIT
更新时间
2026/10/15

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能