rate-limiter
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.
What this skill does
# Rate Limiter
## Overview
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.
## Instructions
### 1. Assess the API Surface
Before writing any code, analyze the target application:
- List all public endpoints and their HTTP methods
- Classify endpoints by sensitivity: authentication (highest), write operations (high), read operations (medium), static/health (low)
- Identify existing middleware stack and framework (Express, Fastify, Django, Gin, etc.)
- Check if Redis or another shared store is available for distributed rate limiting
### 2. Choose the Right Algorithm
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.
### 3. Implement Layered Limits
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.
### 4. 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)
```
### 5. Abuse Detection Patterns
Beyond simple counting, detect:
- **Credential stuffing**: Many unique usernames from one IP on auth endpoints
- **Scraping**: Sequential access patterns on listing endpoints
- **Header anomalies**: Missing User-Agent, rotating headers on rapid requests
- **Distributed attacks**: Same user-agent/fingerprint across many IPs
### 6. Graceful Degradation
Always implement a fallback when Redis is unavailable:
- Fall back to in-memory rate limiting per process
- Log the Redis failure prominently
- Do NOT fail open (allowing unlimited requests) unless explicitly configured
### 7. Avoid Common Pitfalls
- **Trust proxy configuration**: Always verify how `X-Forwarded-For` is parsed. Behind a load balancer, the client IP may not be `req.ip`
- **Shared NAT**: Don't set per-IP limits too low — corporate networks may have thousands of users behind one IP. Minimum 100 req/min for non-auth endpoints
- **Key design**: Use composite keys (`ip:endpoint`, `userId:endpoint`) not just IP alone
- **Time sync**: Use Redis server time (`TIME` command) not local clock for distributed setups
## Examples
### Example 1: Express middleware with Redis sliding window
**Prompt**: "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`:
```typescript
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();
};
}
```
### Example 2: Abuse detection for credential stuffing
**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.
## Guidelines
- Always test rate limiting with concurrent requests — race conditions in counter logic are common
- Include integration tests that verify 429 responses and header values
- Document the rate limits in your API documentation or OpenAPI spec
- Consider offering rate limit increase for paid tiers via configuration, not code changes
- Log all rate limit events in structured format for security monitoring
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.