Communitygithub.com

API 速率限制与节流专家

使用令牌桶、滑动窗口和基于 Redis 的分布式计数器,实现公平、高效的 API 速率限制。

API 速率限制与节流专家 是什么?

该技能专注于为 API 实现公平且高效的速率限制与节流机制。它涵盖了令牌桶、滑动窗口日志、滑动窗口计数器和固定窗口等多种算法,并提供了基于 Redis(7.4+)、Valkey 或 DragonflyDB 的分布式存储方案。对于开发者来说,该技能包含了快速集成指南、最佳实践和反模式说明,例如避免在分布式系统中使用内存计数器或缺少 `Retry-After` 头。此外,它还提供了多层级速率限制架构(如区分免费/专业/企业用户)和符合 IETF 标准的响应头实现示例,支持平台包括自定义后端、Kong/Nginx/Traefik 等网关,以及 JavaScript/TypeScript 生态系统中的常用库(如 `rate-limiter-flexible`)。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/curiositech/windags-skills/tree/HEAD/skills/api-rate-limiting-throttling-expert

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

API 速率限制与节流专家 是做什么的?

使用令牌桶、滑动窗口和固定窗口算法,结合基于 Redis 的分布式计数器,实现公平、高效的速率限制。

触发条件

适用于: “速率限制”、“节流”、“令牌桶”、“滑动窗口”、“API 滥用”、“DDoS 防护”、“配额管理”、“429 Too Many Requests”、“请求限制”

不适用于: API 网关配置 → api-gateway-reverse-proxy-expert | 缓存策略 → cache-strategy-invalidation-expert | WAF/防火墙规则 → 相关安全技能

快速入门

  1. 定义限制 — 基于 API 密钥、IP 或用户层级的每分钟请求数
  2. 选择算法 — 滑动窗口日志(精确)、令牌桶(允许突发)、固定窗口(简单)
  3. 使用 Redis — 通过 MULTI/EXEC 或 Lua 脚本实现原子操作,用于分布式速率限制
  4. 返回正确的请求头 — X-RateLimit-Limit、X-RateLimit-Remaining、Retry-After
  5. 区分层级 — 免费/专业/企业用户获得不同的限制

核心能力

领域技术
算法令牌桶、滑动窗口日志、滑动窗口计数器、固定窗口
存储Redis 7.4+、Valkey、DragonflyDB、内存(单节点)
库rate-limiter-flexible, @upstash/ratelimit, express-rate-limit
网关插件Kong rate-limiting, Nginx limit_req, Traefik ratelimit
标准RFC 6585 (429)、RateLimit 请求头 (draft-ietf-httpapi-ratelimit)

架构模式

滑动窗口计数器 (Redis Lua)

-- Redis Lua 脚本:滑动窗口速率限制器
-- KEYS[1] = 速率限制键
-- ARGV[1] = 窗口大小(秒)
-- ARGV[2] = 最大请求数
-- ARGV[3] = 当前时间戳

local key = KEYS[1]
local window = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local now = tonumber(ARGV[3])

-- 移除过期条目
redis.call('ZREMRANGEBYSCORE', key, 0, now - 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}  -- 允许,返回剩余数
else
  return {0, 0}  -- 拒绝,剩余 0
end

多层级速率限制

请求 → IP 速率限制 (100/分钟)
              │ 通过
              ↓
         认证检查 → API 密钥速率限制 (基于层级)
              │           免费:  60/分钟
              │           专业:   600/分钟
              │           企业: 6000/分钟
              ↓ 通过
         端点速率限制 (按路由)
              │   POST /upload: 10/分钟
              │   GET /search:  120/分钟
              ↓ 通过
         处理请求

响应头 (IETF 草案标准)

// 中间件:附加速率限制请求头
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(),
  };
}

// 返回 429 响应时:
res.status(429).set({
  ...rateLimitHeaders(limit, 0, resetAt),
  'Retry-After': Math.ceil((resetAt - Date.now()) / 1000).toString(),
}).json({ error: 'Too Many Requests', retryAfter: resetAt });

反模式

  1. 在分布式系统中使用内存计数器 — 速率限制必须在所有实例间共享;请使用 Redis 或等效方案
  2. 缺少 Retry-After 头 — 429 响应若不含 Retry-After,会导致客户端盲目重试,引发惊群效应
  3. 仅基于 IP 的速率限制 — IP 限制无法检测基于身份认证的滥用,并且会惩罚共享 IP(如 NAT、VPN);应与 API 密钥限制结合
  4. 无突发能力的硬性切断 — 令牌桶允许在维持平均速率的同时处理小规模突发;纯固定窗口过于僵化
  5. 内部 API 不设速率限制 — 行为不端的内部服务可能导致数据库级联故障;始终应加以限制

质量检查清单

  • 速率限制使用分布式存储 (Redis/Valkey),而非内存
  • 每个响应都包含 RateLimit-Limit、RateLimit-Remaining、RateLimit-Reset 请求头
  • 429 响应包含 Retry-After 请求头
  • 不同认证层级(免费/专业/企业)有不同限制
  • 对高消耗操作(如上传、搜索)设置按端点限制
  • 使用 Lua 脚本或原子管道进行计数器递增(避免竞态条件)
  • 速率限制键同时包含身份标识(如 API 密钥)和作用域(如端点)
  • 监控仪表盘显示命中率、拒绝次数和主要消费者
  • 优雅降级:尽可能采用排队或减速而非直接拒绝

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

curiositech/windags-skills

Expert in 2000s-era music visualization (Milkdrop, AVS, Geiss) and modern WebGL implementations. Specializes in Butterchurn integration, Web Audio API AnalyserNode FFT data, GLSL shaders for audio-reactive visuals, and psychedelic generative art. Activate on "Milkdrop", "music visualization", "WebGL visualizer", "Butterchurn", "audio reactive", "FFT visualization", "spectrum analyzer". NOT for simple bar charts/waveforms (use basic canvas), video editing, or non-audio visuals.

curiositech/windags-skills

Expert legal research agent for finding and scraping expungement data state by state. Knows authoritative sources, URL patterns, Firecrawl configuration, and 2026 legal landscape.

curiositech/windags-skills

Expert in 3D computer vision labeling tools, workflows, and AI-assisted annotation for LiDAR, point clouds, and sensor fusion. Covers SAM4D/Point-SAM, human-in-the-loop architectures, and vertical-specific training strategies. Activate on '3D labeling', 'point cloud annotation', 'LiDAR labeling', 'SAM 3D', 'SAM4D', 'sensor fusion annotation', '3D bounding box', 'semantic segmentation point cloud'. NOT for 2D image labeling (use clip-aware-embeddings), general ML training (use ml-engineer), video annotation without 3D (use computer-vision-pipeline), or VLM prompt engineering (use prompt-engineer).

curiositech/windags-skills

Implement WCAG 2.2 AA/AAA compliance with automated testing, keyboard navigation, screen reader support, and focus management. Activate on: accessibility audit, WCAG compliance, keyboard navigation, screen reader, aria attributes, axe-core, focus trap. NOT for: design-level accessibility review (use design-accessibility-auditor), color contrast only (use css-in-js-architect).

curiositech/windags-skills

Time-blind friendly planning, executive function support, and daily structure for ADHD brains. Specializes in realistic time estimation, dopamine-aware task design, and building systems that actually work for neurodivergent minds.

curiositech/windags-skills

Designs digital experiences for ADHD brains using neuroscience research and UX principles. Expert in reducing cognitive load, time blindness solutions, dopamine-driven engagement, and compassionate design patterns. Activate on 'ADHD design', 'cognitive load', 'accessibility', 'neurodivergent UX', 'time blindness', 'dopamine-driven', 'executive function'. NOT for general accessibility (WCAG only), neurotypical UX design, or simple UI styling without ADHD context.

curiositech/windags-skills

>- Apply crisis decision-making research to agent routing, uncertainty triage, and coordination failure analysis in time-pressured systems. Use when diagnosing handoff failures, analytical paralysis, or expert judgment under incomplete information. NOT for routine coding, simple CRUD design, or static single-agent tasks with complete information.

curiositech/windags-skills

Extend and modify the admin dashboard, developer portal, and operations console. Use when adding new admin tabs, metrics, monitoring features, or internal tools. Activates for dashboard development, analytics, user management, and internal tooling.

curiositech/windags-skills

Conversation patterns and interaction protocols for multi-agent systems. Covers request/response, pub/sub, blackboard, delegation chains, debate, critique, consensus, fan-out/fan-in, supervisor-worker, and peer negotiation. Deep analysis of AutoGen conversation patterns, CrewAI delegation, LangGraph state passing, and FIPA-ACL performatives. Teaches how to design what agents say to each other and in what order. Activate on: "agent conversation", "agent protocol", "multi-agent debate", "agent delegation", "supervisor worker pattern", "agent voting", "consensus protocol", "fan-out fan-in", "agent negotiation", "blackboard pattern", "agent dialogue", "conversation topology", "agent handoff". NOT for: wire format or serialization (use agent-interchange-formats), orchestration infrastructure (use agentic-infrastructure-2026), single agent behavior (use agentic-patterns).

curiositech/windags-skills

Meta-agent for creating new custom agents, skills, and MCP integrations. Expert in agent design, MCP development, skill architecture, and rapid prototyping. Activate on 'create agent', 'new skill', 'MCP server', 'custom tool', 'agent design'. NOT for using existing agents (invoke them directly), general coding (use language-specific skills), or infrastructure setup (use deployment-engineer).

curiositech/windags-skills

AI-powered calendar management and agent-based scheduling coordination. Covers calendar APIs (Google Calendar, CalDAV/iCal), AI scheduling assistants (Reclaim, Clockwise, Motion, Cal.com), building custom calendar agents with MCP, multi-calendar merging, timezone management, focus block protection, meeting fatigue detection, and agent-to-agent meeting negotiation protocols. Activate on: "calendar agent", "AI scheduling", "calendar coordination", "meeting scheduling", "calendar API", "focus time protection", "calendar optimization", "Google Calendar MCP", "Reclaim", "Clockwise", "Motion", "Cal.com", "smart scheduling", "calendar-aware agent", "timezone scheduling", "agent negotiation meetings". NOT for: manual calendar UI component design (use form-validation-architect), project management scheduling or Gantt charts (use project-management-guru-adhd), general time-tracking or pomodoro apps (use adhd-daily-planner for time-awareness), building the agent itself from scratch (use agent-creator).

curiositech/windags-skills

Build and adopt production AI agent infrastructure in 2026. Covers framework selection (LangGraph, CrewAI, AutoGen, MCP), orchestration patterns, evaluation, observability, memory systems, and tool use. Also covers the SOCIAL dimension: how to sell agent infrastructure internally, change management, measuring ROI, building trust in autonomous systems, and scaling adoption across teams. Activate on: "agent infrastructure", "agent framework comparison", "which agent framework", "sell AI tools internally", "agent adoption", "agent observability", "agent evaluation", "MCP architecture", "agentic mesh", "enterprise AI agents", "AI change management", "agent ROI". NOT for: building specific agents (use ai-engineer), designing agent behavior patterns (use agentic-patterns), prompt tuning (use prompt-engineer).

curiositech/windags-skills

Fundamental patterns for effective agentic behavior. Teaches decomposition, tool orchestration, error recovery, context management, quality self-assessment, and knowing when to stop. Model-agnostic principles that make any agent more effective regardless of domain. Activate on: "how should I structure this agent", "agentic workflow", "agent patterns", "multi-step task", "tool orchestration", "/agentic-patterns", "decompose this", "agent best practices", "chain of actions", "when should the agent stop", "agent loop design". NOT for: creating agent infrastructure (use agent-creator), building DAGs (use windags-architect), specific tool implementation.

curiositech/windags-skills

Automated discovery and matching of agent skills for dynamic task routing and capability assessment

curiositech/windags-skills

Cryptographic security for agentic systems — zero-trust agent networking, signed message envelopes (JWS/JWE), capability-based security (ocaps), Merkle tree audit trails, WASM sandboxing, and formal verification. Covers CLI dev tool security, mTLS between agents, permission boundaries (least privilege for AI agents), and supply chain security for skills/plugins. Activate on: "agent security", "zero trust agents", "secure agent communication", "capability-based security", "ocap", "signed messages between agents", "agent audit trail", "sandbox agent execution", "agent permissions", "mTLS agents", "cryptographic verification", "agent supply chain", "OWASP agentic", "prove agent did X", "tamper-proof agent logs". NOT for: application-level SAST scanning (use security-auditor), network firewall rules (use infrastructure), SOC2/HIPAA compliance (organizational), or prompt injection defense (use prompt-engineer).

curiositech/windags-skills

Data structures and serialization formats for agent-to-agent communication. Covers message envelopes, structured output schemas, capability declarations, task handoff payloads, error/retry signaling, and context windows as data structures. Deep comparison of A2A protocol, MCP, OpenAI function calling, and LangChain message types. Teaches when to use rigid schemas vs free-form with validation, typed vs untyped, streaming vs batch. Activate on: "agent message format", "agent communication schema", "agent-to-agent protocol", "A2A protocol", "MCP message format", "structured output for agents", "agent interop", "interchange format", "agent serialization", "task handoff format", "capability declaration". NOT for: what agents say to each other (use agent-conversation-protocols), orchestration topology (use multi-agent-coordination), building agent infrastructure (use agentic-infrastructure-2026).

curiositech/windags-skills

Logic-based agent programming language implementing BDI architecture for practical autonomous agent development

curiositech/windags-skills

>- Design AgentSpeak(L)-style BDI agents with context-guarded plans, selection functions, and intention stacks. Use for interruptible autonomy, agent policy, and multi-agent orchestration in dynamic environments. NOT for simple rule engines, static planners, or centralized workflows.

curiositech/windags-skills

Foundational concurrent computation model where actors communicate exclusively through asynchronous message passing

curiositech/windags-skills

license: Apache-2.0 NOT for unrelated tasks outside this domain.

相关技能