API Rate Limiting & Throttling Expert
Implement fair, efficient rate limiting using token bucket, sliding window, and fixed window algorithms with Redis-backed distributed counters.
Activation Triggers
Activate on: "rate limiting", "throttling", "token bucket", "sliding window", "API abuse", "DDoS protection", "quota management", "429 Too Many Requests", "request limits"
NOT for: API gateway configuration → api-gateway-reverse-proxy-expert | Caching strategies → cache-strategy-invalidation-expert | WAF/firewall rules → relevant security skill
Quick Start
- Define limits — requests/minute per API key, IP, or user tier
- Choose algorithm — sliding window log (precise), token bucket (bursty), fixed window (simple)
- Use Redis — atomic operations with
MULTI/EXEC or Lua scripts for distributed rate limiting
- Return proper headers —
X-RateLimit-Limit, X-RateLimit-Remaining, Retry-After
- Differentiate tiers — free/pro/enterprise get different limits
Core Capabilities
| Domain |
Technologies |
| Algorithms |
Token bucket, sliding window log, sliding window counter, fixed window |
| Storage |
Redis 7.4+, Valkey, DragonflyDB, in-memory (single node) |
| Libraries |
rate-limiter-flexible, @upstash/ratelimit, express-rate-limit |
| Gateway Plugins |
Kong rate-limiting, Nginx limit_req, Traefik ratelimit |
| Standards |
RFC 6585 (429), RateLimit headers (draft-ietf-httpapi-ratelimit) |
Architecture Patterns
Sliding Window Counter (Redis Lua)
-- Redis Lua script: sliding window rate limiter
-- KEYS[1] = rate limit key
-- ARGV[1] = window size (seconds)
-- ARGV[2] = max requests
-- ARGV[3] = current timestamp
local key = KEYS[1]
local window = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
-- Remove expired entries
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
-- Count current window
local count = redis.call('ZCARD', key)
if count < limit then
redis.call('ZADD', key, now, now .. '-' .. math.random(1000000))
redis.call('EXPIRE', key, window)
return {1, limit - count - 1} -- allowed, remaining
else
return {0, 0} -- denied, 0 remaining
end
Multi-Tier Rate Limiting
Request → IP Rate Limit (100/min)
│ pass
↓
Auth Check → API Key Rate Limit (tier-based)
│ Free: 60/min
│ Pro: 600/min
│ Enterprise: 6000/min
↓ pass
Endpoint Rate Limit (per-route)
│ POST /upload: 10/min
│ GET /search: 120/min
↓ pass
Process Request
Response Headers (IETF Draft Standard)
// Middleware: attach rate limit headers
function rateLimitHeaders(limit: number, remaining: number, resetAt: number) {
return {
'RateLimit-Limit': limit.toString(),
'RateLimit-Remaining': Math.max(0, remaining).toString(),
'RateLimit-Reset': Math.ceil((resetAt - Date.now()) / 1000).toString(),
};
}
// On 429 response:
res.status(429).set({
...rateLimitHeaders(limit, 0, resetAt),
'Retry-After': Math.ceil((resetAt - Date.now()) / 1000).toString(),
}).json({ error: 'Too Many Requests', retryAfter: resetAt });
Anti-Patterns
- In-memory counters in distributed systems — rate limits must be shared across instances; use Redis or equivalent
- Missing Retry-After header — 429 responses without
Retry-After force clients to guess, leading to thundering herd
- IP-only rate limiting — IP limits miss authenticated abuse and punish shared IPs (NAT, VPN); combine with API key limits
- Hard cutoff without burst — token bucket allows small bursts while maintaining average rate; pure fixed window is too rigid
- No rate limit on internal APIs — a misbehaving internal service can cascade-fail your database; always limit
Quality Checklist
1---2license: Apache-2.03name: api-rate-limiting-throttling-expert4description: "Token bucket, sliding window, and Redis-based rate limiting for API protection. Activate on: rate limiting, throttling, token bucket, sliding window, API abuse, DDoS protection, quota management. NOT for: API gateway setup (use api-gateway-reverse-proxy-expert), caching (use cache-strategy-invalidation-expert)."5allowed-tools: Read,Write,Edit,Bash(npm:*,npx:*,redis-cli:*)6category: Backend & Infrastructure7tags:8 - rate-limiting9 - throttling10 - redis11 - api-protection12 - token-bucket13pairs-with:14 - skill: api-gateway-reverse-proxy-expert15 reason: Rate limiting is typically enforced at the gateway16 - skill: cache-strategy-invalidation-expert17 reason: Redis powers both caching and rate limit counters18 - skill: multi-tenant-architecture-expert19 reason: Per-tenant rate limits are essential for multi-tenant APIs20metadata:21 source: https://skillmd.com/skills/curiositech/api-rate-limiting-throttling-expert22---2324# API Rate Limiting & Throttling Expert2526Implement fair, efficient rate limiting using token bucket, sliding window, and fixed window algorithms with Redis-backed distributed counters.2728## Activation Triggers2930**Activate on:** "rate limiting", "throttling", "token bucket", "sliding window", "API abuse", "DDoS protection", "quota management", "429 Too Many Requests", "request limits"3132**NOT for:** API gateway configuration → `api-gateway-reverse-proxy-expert` | Caching strategies → `cache-strategy-invalidation-expert` | WAF/firewall rules → relevant security skill3334## Quick Start35361. **Define limits** — requests/minute per API key, IP, or user tier372. **Choose algorithm** — sliding window log (precise), token bucket (bursty), fixed window (simple)383. **Use Redis** — atomic operations with `MULTI/EXEC` or Lua scripts for distributed rate limiting394. **Return proper headers** — `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `Retry-After`405. **Differentiate tiers** — free/pro/enterprise get different limits4142## Core Capabilities4344| Domain | Technologies |45|--------|-------------|46| **Algorithms** | Token bucket, sliding window log, sliding window counter, fixed window |47| **Storage** | Redis 7.4+, Valkey, DragonflyDB, in-memory (single node) |48| **Libraries** | rate-limiter-flexible, @upstash/ratelimit, express-rate-limit |49| **Gateway Plugins** | Kong rate-limiting, Nginx limit_req, Traefik ratelimit |50| **Standards** | RFC 6585 (429), RateLimit headers (draft-ietf-httpapi-ratelimit) |5152## Architecture Patterns5354### Sliding Window Counter (Redis Lua)5556```lua57-- Redis Lua script: sliding window rate limiter58-- KEYS[1] = rate limit key59-- ARGV[1] = window size (seconds)60-- ARGV[2] = max requests61-- ARGV[3] = current timestamp6263local key = KEYS[1]64local window = tonumber(ARGV[1])65local limit = tonumber(ARGV[2])66local now = tonumber(ARGV[3])6768-- Remove expired entries69redis.call('ZREMRANGEBYSCORE', key, 0, now - window)7071-- Count current window72local count = redis.call('ZCARD', key)7374if count < limit then75 redis.call('ZADD', key, now, now .. '-' .. math.random(1000000))76 redis.call('EXPIRE', key, window)77 return {1, limit - count - 1} -- allowed, remaining78else79 return {0, 0} -- denied, 0 remaining80end81```8283### Multi-Tier Rate Limiting8485```86Request → IP Rate Limit (100/min)87 │ pass88 ↓89 Auth Check → API Key Rate Limit (tier-based)90 │ Free: 60/min91 │ Pro: 600/min92 │ Enterprise: 6000/min93 ↓ pass94 Endpoint Rate Limit (per-route)95 │ POST /upload: 10/min96 │ GET /search: 120/min97 ↓ pass98 Process Request99```100101### Response Headers (IETF Draft Standard)102103```typescript104// Middleware: attach rate limit headers105function rateLimitHeaders(limit: number, remaining: number, resetAt: number) {106 return {107 'RateLimit-Limit': limit.toString(),108 'RateLimit-Remaining': Math.max(0, remaining).toString(),109 'RateLimit-Reset': Math.ceil((resetAt - Date.now()) / 1000).toString(),110 };111}112113// On 429 response:114res.status(429).set({115 ...rateLimitHeaders(limit, 0, resetAt),116 'Retry-After': Math.ceil((resetAt - Date.now()) / 1000).toString(),117}).json({ error: 'Too Many Requests', retryAfter: resetAt });118```119120## Anti-Patterns1211221. **In-memory counters in distributed systems** — rate limits must be shared across instances; use Redis or equivalent1232. **Missing Retry-After header** — 429 responses without `Retry-After` force clients to guess, leading to thundering herd1243. **IP-only rate limiting** — IP limits miss authenticated abuse and punish shared IPs (NAT, VPN); combine with API key limits1254. **Hard cutoff without burst** — token bucket allows small bursts while maintaining average rate; pure fixed window is too rigid1265. **No rate limit on internal APIs** — a misbehaving internal service can cascade-fail your database; always limit127128## Quality Checklist129130- [ ] Rate limits use distributed storage (Redis/Valkey), not in-memory131- [ ] `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` headers on every response132- [ ] `Retry-After` header on 429 responses133- [ ] Different limits per authentication tier (free/pro/enterprise)134- [ ] Per-endpoint limits for expensive operations (uploads, search)135- [ ] Lua script or atomic pipeline for counter increment (no race conditions)136- [ ] Rate limit keys include both identity (API key) and scope (endpoint)137- [ ] Monitoring dashboard shows rate limit hits, denials, and top consumers138- [ ] Graceful degradation: queue or slow down rather than hard-reject where possible