Designs and implements API rate limiting middleware and abuse protection. Use when you need to add request throttling, per-user quotas, IP-based blocking, sliding window or token bucket algorithms, Redis-backed distributed counters, or 429 response handling. Trigger words: rate limit, throttle, API abuse, too many requests, request quota, DDoS protection, brute force prevention, credential stuffing defense.
This skill enables AI agents to design, implement, and configure production-grade rate limiting for APIs. It covers algorithm selection, middleware generation, Redis-backed distributed counting, abuse pattern detection, and proper HTTP response headers.
Before writing any code, analyze the target application:
Select based on the use case:
| Algorithm | Best For | Trade-off | |-----------|----------|-----------| | Fixed Window | Simple per-minute caps | Burst at window edges | | Sliding Window Log | Precise per-user limits | Higher memory per key | | Sliding Window Counter | Balance of accuracy and memory | Slight approximation | | Token Bucket | APIs with burst allowance | More complex to tune | | Leaky Bucket | Smooth output rate | Delays rather than rejects |
Default recommendation: Sliding Window Counter — it handles 95% of use cases with good accuracy and reasonable memory usage.
Always implement at least two layers:
Layer 1 — Global IP limit: Catches volumetric abuse before authentication. Typical: 100-300 req/min per IP.
Layer 2 — Endpoint-specific limits: Different limits per endpoint category. Auth endpoints get the strictest limits (3-10 req/min).
Layer 3 — Authenticated user quotas (if applicable): Daily or hourly caps per API key or user ID. Return quota status in response headers.
Always include these headers on EVERY response (not just 429s):
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1708012800
Retry-After: 30 (only on 429 responses)
Beyond simple counting, detect:
Always implement a fallback when Redis is unavailable:
X-Forwarded-For is parsed. Behind a load balancer, the client IP may not be req.ipip:endpoint, userId:endpoint) not just IP aloneTIME command) not local clock for distributed setupsPrompt: "Add rate limiting to my Express API. Auth endpoints should allow 5 requests per minute per IP. All other endpoints 60 per minute per authenticated user."
Output: The agent creates src/middleware/rateLimiter.ts:
import { Redis } from 'ioredis';
import { Request, Response, NextFunction } from 'express';
const redis = new Redis(process.env.REDIS_URL);
interface RateLimitConfig {
windowMs: number;
max: number;
keyGenerator: (req: Request) => string;
}
const configs: Record<string, RateLimitConfig> = {
auth: {
windowMs: 60_000,
max: 5,
keyGenerator: (req) => `rl:auth:${req.ip}`,
},
default: {
windowMs: 60_000,
max: 60,
keyGenerator: (req) => `rl:api:${(req as any).userId ?? req.ip}`,
},
};
export function rateLimit(category: keyof typeof configs) {
const config = configs[category];
return async (req: Request, res: Response, next: NextFunction) => {
const key = config.keyGenerator(req);
const now = Date.now();
const windowStart = now - config.windowMs;
const multi = redis.multi();
multi.zremrangebyscore(key, 0, windowStart);
multi.zadd(key, now.toString(), `${now}:${Math.random()}`);
multi.zcard(key);
multi.expire(key, Math.ceil(config.windowMs / 1000));
const results = await multi.exec();
const count = results![2][1] as number;
res.set('X-RateLimit-Limit', config.max.toString());
res.set('X-RateLimit-Remaining', Math.max(0, config.max - count).toString());
res.set('X-RateLimit-Reset', Math.ceil((now + config.windowMs) / 1000).toString());
if (count > config.max) {
res.set('Retry-After', Math.ceil(config.windowMs / 1000).toString());
return res.status(429).json({ error: 'Too many requests' });
}
next();
};
}
Prompt: "Detect credential stuffing on my login endpoint. Block IPs that try more than 20 unique usernames in 5 minutes."
Output: The agent adds a detection middleware that tracks unique username attempts per IP using a Redis HyperLogLog, blocking IPs that exceed the threshold and logging the event with full request metadata for incident response.
npx skills add TerminalSkills/rate-limiter下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer