跳到正文
cccskills
免费在 GitHub 公开

api-rate-limit-handler

Implement controlled retries and request throttling for external APIs. Covers retryable errors, provider-specified waiting times, increasing delays with random variation, retry limits, and checks that repeating a request will not cause unintended duplicate changes.

中文简介正在准备中。当前显示英语简介。

原文查看原文说明

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

查看安装方法

适用场景

  • Handle 429 and temporary server errors
  • Respect Retry-After waiting times
  • Limit outgoing API request frequency
  • Check replay safety for state-changing requests

包含的文件(1)

  • SKILL.md10.4 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

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.

StatusClassificationAction
200-299SuccessReturn response
400, 401, 403, 404Terminal client errorDo not retry — fix the request
408, 429Retryable (rate limit / timeout)Retry with backoff
500, 502, 503, 504Retryable (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)

Prevent hitting upstream limits in the first place with a token bucket or sliding window.

class TokenBucket {
  private tokens: number;
  private lastRefill: number;
  private queue: Promise<void> = Promise.resolve();

  constructor(
    private maxTokens: number,
    private refillRate: number // tokens per second
  ) {
    this.tokens = maxTokens;
    this.lastRefill = Date.now();
  }

  async acquire(): Promise<void> {
    const ticket = this.queue.then(() => this.acquireOnce());
    this.queue = ticket.catch(() => undefined);
    return ticket;
  }

  private async acquireOnce(): Promise<void> {
    this.refill();
    if (this.tokens < 1) {
      const waitMs = ((1 - this.tokens) / this.refillRate) * 1000;
      await new Promise(resolve => setTimeout(resolve, waitMs));
      this.refill();
    }
    this.tokens -= 1;
  }

  private refill(): void {
    const now = Date.now();
    const elapsed = (now - this.lastRefill) / 1000;
    this.tokens = Math.min(this.maxTokens, this.tokens + elapsed * this.refillRate);
    this.lastRefill = now;
  }
}

// Usage: limit to 60 requests/minute
const limiter = new TokenBucket(60, 1);

async function rateLimitedFetch(url: string, options: RequestInit) {
  await limiter.acquire();
  return fetchWithRetry(url, options);
}

Examples

Example 1: Idempotent API read with retry

const response = await fetchWithRetry(
  "https://api.github.com/repos/OWNER/REPO",
  {
    method: "GET",
    headers: {
      "Accept": "application/vnd.github+json",
      "Authorization": `Bearer ${githubToken}`,
    },
  },
  3
);

For a POST or another operation with side effects, leave retryNonIdempotent false unless the provider documents an idempotency mechanism and the same stable idempotency key is reused for every attempt.

Example 2: Python implementation

import time
import random
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import httpx

def fetch_with_retry(url: str, max_retries: int = 3, max_elapsed_s: float = 120, **kwargs) -> httpx.Response:
    started = time.monotonic()
    kwargs.setdefault("timeout", 10.0)
    for attempt in range(max_retries + 1):
        response = httpx.request("GET", url, **kwargs)
        if response.is_success:
            return response
        if response.status_code not in (408, 429, 500, 502, 503, 504) or attempt == max_retries:
            response.raise_for_status()
        retry_after = response.headers.get("retry-after")
        delay = min(2 ** attempt + random.uniform(0, 1), 60)
        if retry_after:
            try:
                seconds = float(retry_after)
                if seconds >= 0 and seconds < float("inf"):
                    delay = seconds
            except ValueError:
                try:
                    retry_at = parsedate_to_datetime(retry_after)
                    delay = max(0, (retry_at - datetime.now(timezone.utc)).total_seconds())
                except (ValueError, TypeError, OverflowError):
                    pass
        remaining = max_elapsed_s - (time.monotonic() - started)
        if remaining <= 0 or delay > remaining:
            response.close()
            raise TimeoutError("Retry cannot fit the remaining operation budget")
        response.close()
        time.sleep(delay)
    raise RuntimeError("Unreachable")

Best Practices

  • ✅ Always respect Retry-After headers — they come from the provider who knows their limits
  • ✅ Add jitter to backoff to prevent thundering herd when multiple clients retry simultaneously
  • ✅ Log every retry with status code, delay, and attempt number for debugging
  • ✅ Set a maximum total timeout to avoid hanging indefinitely
  • ✅ Use a client-side rate limiter proactively rather than only reacting to 429s
  • ✅ Retry state-changing requests only with a provider-documented idempotency mechanism and a stable key
  • ❌ Don't retry 4xx client errors (except 408 and 429) — fix the request instead
  • ❌ Don't use fixed delays — exponential backoff distributes load more evenly
  • ❌ Don't retry without a cap — unbounded retries can amplify outages
  • ❌ Don't ignore per-endpoint limits — some APIs have different quotas per route

Limitations

  • This skill does not replace environment-specific validation, testing, or expert review.
  • Token bucket is approximate for distributed systems — use Redis-backed rate limiting for multi-instance deployments (for example the upstash-ratelimit skill, or any shared-store limiter).
  • Some APIs use non-standard rate limit headers; check provider documentation.
  • The elapsed-time cap shown here bounds retry waits, not a single hung network call; combine it with an AbortSignal or client timeout.

Common Pitfalls

  • Problem: Retrying too aggressively during an outage amplifies the problem. Solution: Use exponential backoff with jitter and a circuit breaker for sustained failures.

  • Problem: Multiple instances of your app all retry at the same time (thundering herd). Solution: Add randomized jitter (Math.random() * 0.3 * delay) to decorrelate retries.

  • Problem: Retry-After header contains an HTTP-date instead of seconds. Solution: Parse both formats — check if the value is numeric first, then try Date parsing.

  • Problem: Client-side limiter doesn't account for concurrent requests already in-flight. Solution: Serialize acquisition within one process, decrement before send, and use a shared distributed limiter across instances.

Related Skills

  • @poka-yoke - Mistake-proofing APIs so invalid requests never reach the retry path
  • @circuit-breaker - When to stop retrying entirely and fail fast

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Assess a new or existing AI project by examining its code, goals, and constraints. Recommend skills confirmed to exist in the available registry, then outline tasks and implementation phases with dependencies, completion criteria, and checks.

中文简介正在准备中。当前显示英语简介。

  • Planning the first steps of a new AI project
  • Assessing technical issues in an existing project
  • Selecting relevant skills from an available registry
sickn33/agentic-awesome-skills4.8万2026年10月19日 更新

007

免费

Review code and infrastructure for security risks, map potential threats, and plan stronger defenses. The skill covers OWASP checks, attack and defense exercises, and incident response, with validation required for each environment.

中文简介正在准备中。当前显示英语简介。

  • Reviewing code and infrastructure security
  • Mapping threats with STRIDE or PASTA
  • Planning stronger security settings
sickn33/agentic-awesome-skills4.8万2026年10月19日 更新

Turn a repeatable task into an Andru.ia skill with clear inputs, outputs, examples, and limits. Draft SKILL.md, check the folder structure and required validations, and prepare a pull request describing the changes for review.

中文简介正在准备中。当前显示英语简介。

  • Creating a skill for a repeatable task
  • Improving an existing skill’s examples and limits
  • Validating skill files and preparing a pull request
sickn33/agentic-awesome-skills4.8万2026年10月19日 更新

Prepare an industry briefing once a project's sector is defined. It covers sector context, potentially applicable regulations, familiar interface patterns, technology choices, and risks, while separating verified evidence from hypotheses and questions requiring further review.

中文简介正在准备中。当前显示英语简介。

  • Researching industry requirements before product design
  • Checking regulations for a project's jurisdiction
  • Choosing interface patterns familiar to target users
sickn33/agentic-awesome-skills4.8万2026年10月19日 更新

Create presentation drafts from text, outlines, or documents through the 2slides API. Match a reference image's style, choose themes, add AI voice narration, and export slide images or audio for review and use.

中文简介正在准备中。当前显示英语简介。

  • Create a presentation from text or an outline
  • Summarize a document into slides
  • Match slide styling to a reference image
sickn33/agentic-awesome-skills4.8万2026年10月19日 更新

Plan a 360-degree or peer feedback process and create empty response templates from confirmed requirements. Produces consistent CSV, SQL, JSON Schema, or Notion property mappings while keeping visibility choices and scoring configuration separate.

中文简介正在准备中。当前显示英语简介。

  • Plan an anonymous peer feedback process
  • Create a CSV template for feedback responses
  • Align feedback fields across SQL and JSON Schema
sickn33/agentic-awesome-skills4.8万2026年10月19日 更新

查看 sickn33 的全部技能

报告此技能的问题