Api Rate Limiting

作者 secondsky88378361314fMIT227 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫10 天前更新

Implements API rate limiting using token bucket, sliding window, and Redis-based algorithms to protect against abuse. Use when securing public APIs, implementing tiered access, or preventing denial-of-service attacks.

AI 產生的概覽

指導使用權杖桶、滑動視窗與以 Redis 為基礎的演算法實作 API 限流。

功能
此技能為 API 加入限流提供參考指引,涵蓋權杖桶、滑動視窗與固定視窗演算法及其優缺點。內容包含 Node.js 權杖桶範例程式碼、Express 中介軟體設定、標準限流回應標頭,以及分層請求額度。它也列出最佳實務,例如使用 Redis 進行分散式限流,以及回傳帶有 Retry-After 的 429 回應。
適用情境
適用於保護公開 API 免於濫用、依方案實作分層存取,或防範阻斷服務攻擊的情境。適合為現有 API 加入請求節流的開發者。
執行需求
不隨附指令碼,僅為說明文件。套用範例需要 Node.js 環境,可選用 express-rate-limit 套件,分散式限流則需要 Redis。

API Rate Limiting

Protect APIs from abuse using rate limiting algorithms with per-user and per-endpoint strategies.

Algorithms

AlgorithmProsCons
Token BucketHandles bursts, smoothMemory per user
Sliding WindowAccurateMemory intensive
Fixed WindowSimpleBoundary spikes

Token Bucket (Node.js)

javascript
class TokenBucket {  constructor(capacity, refillRate) {    this.capacity = capacity;    this.tokens = capacity;    this.refillRate = refillRate; // tokens per second    this.lastRefill = Date.now();  }
  consume() {    this.refill();    if (this.tokens >= 1) {      this.tokens--;      return true;    }    return false;  }
  refill() {    const now = Date.now();    const elapsed = (now - this.lastRefill) / 1000;    this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillRate);    this.lastRefill = now;  }}

Express Middleware

javascript
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({  windowMs: 15 * 60 * 1000, // 15 minutes  max: 100,  standardHeaders: true,  message: { error: 'Too many requests, try again later' }});
app.use('/api/', limiter);

Response Headers

X-RateLimit-Limit: 100X-RateLimit-Remaining: 45X-RateLimit-Reset: 1705320000Retry-After: 60

Tiered Limits

TierRequests/Hour
Free100
Pro1,000
Enterprise10,000

Best Practices

  • Use Redis for distributed rate limiting
  • Include proper headers in responses
  • Return 429 status with Retry-After
  • Implement tiered limits for different plans
  • Monitor rate limit metrics
  • Test under load

來源與署名

來源:secondsky/claude-skills位於plugins/api-rate-limiting/skills/api-rate-limiting提交8837836

授權條款: MIT

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架