rate-limiting
Use when the user asks about rate limiting, protecting a public API from abuse with request throttling, token bucket, sliding window, 429 Too Many Requests…
от j4flmao★ 47 звёзд на GitHub
Установить rate-limiting в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Rate Limiting
Purpose
Protect services and enforce fair use by bounding how many requests (or how much cost) a client can consume per unit of time. Correct rate limiting needs the right algorithm, the right key (who is limited), the right enforcement point, and responses that let well-behaved clients back off.
Agent Protocol
Trigger
Exact user phrases: "rate limit", "rate limiting", "throttle requests", "token bucket", "leaky bucket", "sliding window", "429 too many requests", "API quota", "per-user limit", "distributed rate limiter", "Retry-After".
Input Context
- What is being protected (whole API, expensive endpoint, login, outbound calls to a third party).
- Identity available at enforcement time (API key, user ID, tenant, IP).
- Number of instances and shared stores (Redis), gateway in front (Envoy, NGINX, Kong, cloud gateway).
- Desired limits and burst tolerance.
Output Artifact
Limit policy table plus middleware/gateway code or config. No files unless requested.
Response Format
Scope: {endpoint/group} Key: {api_key | user_id | tenant | ip}
Algorithm: {token bucket | sliding window counter | fixed window | GCRA}
Limit: {N} per {window}, burst {B}
Store: {in-memory | Redis (Lua, atomic) | gateway}
On limit: 429 + Retry-After {s} + RateLimit headers
Fail mode if store down: {open | closed}
Algorithms
| Algorithm | Behaviour | Memory/key | Bursts | Notes |
|---|---|---|---|---|
| Fixed window counter | INCR per window, reset at boundary |
1 counter | Up to 2x limit across a boundary | Simplest; fine for coarse quotas (per day) |
| Sliding window log | Store each request timestamp | O(limit) | Exact | Precise but memory-heavy |
| Sliding window counter | Weighted current + previous window counts | 2 counters | Approximate, smooth | Good default for "N per minute" APIs |
| Token bucket | Tokens refill at rate r up to capacity b; request spends tokens | 2 values | Allows bursts up to b | Best when bursts are acceptable; supports variable cost |
| Leaky bucket (queue) | Requests drain at fixed rate | Queue | Smooths output | NGINX limit_req is leaky-bucket based |
| GCRA | Token-bucket-equivalent using one timestamp (theoretical arrival time) | 1 value | Configurable | Used by redis-cell and several gateways |
Decision rules:
- Public API with per-key plans: token bucket or sliding window counter, keyed by API key.
- Login / OTP / password reset: strict fixed or sliding window keyed by account and by IP, plus exponential lockout.
- Calling a third-party API with a published quota: client-side token bucket that waits (not rejects) before sending.
- Expensive endpoints: cost-based token bucket (e.g. a report costs 10 tokens).
Choosing the Key
- Prefer authenticated identity (API key, user, tenant). IP limits punish NAT/corporate users and are easily rotated by attackers; use them for unauthenticated endpoints only.
- Behind proxies, derive client IP from a trusted
X-Forwarded-Forhop configured on the proxy; never trust the header from arbitrary clients. - Layer limits: global (protect the service) + per tenant (fairness) + per endpoint (expensive operations).
Distributed Token Bucket (Redis + Lua)
Atomic check-and-update in one script avoids the race in "GET then SET". Using Redis TIME avoids clock skew between app instances.
-- token_bucket.lua KEYS[1]=bucket key ARGV: capacity, refill_per_sec, cost
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate)
local allowed, retry_ms = 0, 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
retry_ms = math.ceil((cost - tokens) / rate * 1000)
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) + 1000)
-- return floats as strings: Redis converts Lua numbers to integers
return { allowed, tostring(tokens), retry_ms }
Express middleware using ioredis:
import type { Request, Response, NextFunction } from 'express';
import Redis from 'ioredis';
import { readFileSync } from 'node:fs';
const redis = new Redis(process.env.REDIS_URL!);
redis.defineCommand('tokenBucket', {
numberOfKeys: 1,
lua: readFileSync(new URL('./token_bucket.lua', import.meta.url), 'utf8'),
});
declare module 'ioredis' {
interface RedisCommander<Context> {
tokenBucket(key: string, capacity: number, rate: number, cost: number): Result<[number, string, number], Context>;
}
}
export function rateLimit(opts: { capacity: number; perSecond: number; cost?: number }) {
return async (req: Request, res: Response, next: NextFunction) => {
const id = (req as Request &
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/algorithms.md
- references/backpressure.md
- references/distributed-rate-limiting.md
- references/implementation-patterns.md
- references/merged-system-design-rate-limiting.md
- references/rate-limiting-api-gateway.md
- references/rate-limiting-implementations.md
- references/rate-limiting-monitoring.md
- references/rate-limiting-queuing.md
FAQ
Что делает скилл rate-limiting?
Use when the user asks about rate limiting, protecting a public API from abuse with request throttling, token bucket, sliding window, 429 Too Many Requests, Retry-After or per-user quotas. Produces an algorithm, key and Redis-backed limiter. Not for circuit breakers and bulkheads (use backend-resilience-patterns).
Как установить скилл rate-limiting?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл rate-limiting запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…