rate-limiter

用于设计与实现 API 速率限制中间件和滥用防护的参考资料。适用于需要添加请求限流、按用户配额控制、基于 IP 的封禁、滑动窗口或令牌桶算法、基于 Redis 的分布式计数器,或处理 429 响应的场景。触发词示例:速率限制、限流、API 滥用、请求过多、请求配额、DDoS 防护、暴力破解防护、凭证填充防御。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "rate-limiter":https://skillpi.com/zh/skills/deepskill-a56906084eebbfe6a9e3d68f04880b94cf66db6d388aaa993e2d965088af2193。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

用于设计与实现 API 速率限制中间件和滥用防护的参考资料。适用于需要添加请求限流、按用户配额控制、基于 IP 的封禁、滑动窗口或令牌桶算法、基于 Redis 的分布式计数器,或处理 429 响应的场景。触发词示例:速率限制、限流、API 滥用、请求过多、请求配额、DDoS 防护、暴力破解防护、凭证填充防御。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: rate-limiter
description: >-
  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.
license: Apache-2.0
compatibility: "Node.js 18+, Python 3.9+, or Go 1.21+. Redis 7+ for distributed mode."
metadata:
  author: terminal-skills
  version: "1.0.0"
  category: devops
  tags: ["rate-limiting", "api-security", "middleware"]

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:

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

当前收录版本

1.0.0

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

  • 解决 API 滥用防护的高频刚需场景
  • 覆盖多种技术栈(Node.js/Python/Go)和架构(单体/分布式)
  • 提供完整的算法选型指导和分层限流策略
触发精准95/100

亮点

  • 触发词覆盖全面,包含中英文变体
  • 边界清晰,无歧义或重叠风险
  • 在多个位置(description/frontmatter)均有体现
结构规范93/100

亮点

  • 7 个逻辑清晰的执行步骤
  • 包含两个端到端完整示例
  • frontmatter 信息完整且规范
执行可靠91/100

亮点

  • Redis 降级策略完善
  • 覆盖代理配置、时间同步等常见陷阱
  • 提供测试建议和监控日志规范
证据可验 (前四项均值)93/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。