rate-limiting-implementation — скилл для Claude Code: лимиты и квоты
Скилл помогает агенту добавить в сервис ограничение частоты запросов, квоты и backpressure. Пригодится, когда API открыт наружу или нагрузка растёт.
npx skills add aj-geddes/useful-ai-prompts --skill rate-limiting-implementation -a claude-codeЧто делает rate-limiting-implementation
Скилл описывает, как встроить в проект ограничение частоты запросов и защиту от перегрузки. Внутри — готовые примеры: token bucket на TypeScript, распределённый лимитер на Redis, middleware для Express, sliding window на Python, а также tiered и adaptive rate limiting. Каждый разбор лежит отдельным файлом в каталоге references/.
Агенту скилл задаёт и правила поведения: возвращать код 429, добавлять заголовок Retry-After, писать нарушения в лог, делать несколько уровней лимита — по секундам, минутам, часам. Для нескольких серверов советует хранить счётчики в Redis, а не в памяти процесса: иначе каждый инстанс считает запросы сам и общий лимит не работает.
Есть и список того, чего делать не стоит: не блокировать весь IP из-за одного нарушителя, не ставить слишком жёсткие пороги, не отказывать всем запросам, если лимитер упал. Последнее особенно важно — при сбое хранилища сервис должен продолжать отвечать.
Какие задачи решает
- защитить публичный API от перебора и флуда
- ввести квоты по тарифам для разных клиентов
- считать лимиты сразу на нескольких серверах через Redis
- добавить middleware с ограничением частоты в Express
- сгладить всплески трафика без падения сервиса
Примеры запросов агенту
- добавь rate limiting в наш Express API, лимит по IP и по API-ключу
- сделай распределённый лимитер на Redis для нескольких инстансов
- настрой tiered-лимиты: отдельно на секунду, минуту и час
Как установить rate-limiting-implementation
1Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill rate-limiting-implementation -a claude-code2Вручную: положить файлы
~/.claude/skills/rate-limiting-implementation/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/rate-limiting-implementation/
1Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill rate-limiting-implementation -a codex2Вручную: положить файлы
.agents/skills/rate-limiting-implementation/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill rate-limiting-implementation -a cursor2Вручную: положить файлы
.cursor/skills/rate-limiting-implementation/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install aj-geddes/useful-ai-prompts rate-limiting-implementation2Вручную: положить файлы
.github/skills/rate-limiting-implementation/SKILL.md1Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill rate-limiting-implementation -a gemini-cli2Командой платформы
gemini skills install https://github.com/aj-geddes/useful-ai-prompts --path skills/rate-limiting-implementationВручную: положить файлы
.devin/skills/rate-limiting-implementation/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill rate-limiting-implementation -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о rate-limiting-implementation
Как установить rate-limiting-implementation в Claude?
Выполните npx skills add aj-geddes/useful-ai-prompts --skill rate-limiting-implementation -a claude-code. Скилл появится в ~/.claude/skills/rate-limiting-implementation/SKILL.md.
Что делает этот скилл?
Даёт агенту инструкции и примеры кода для ограничения частоты запросов, квот и backpressure. Внутри — token bucket, sliding window, лимитер на Redis и middleware для Express.
Нужен ли Redis для работы скилла?
Для распределённого лимитера на нескольких серверах — да, счётчики хранятся там. Если сервис работает на одном инстансе, хватит примеров с локальным состоянием.
Исходный текст
SKILL.md · MIT
---
name: rate-limiting-implementation
description: >
Implement rate limiting, throttling, API quotas, and backpressure mechanisms
to protect services from abuse and ensure fair resource usage. Use when
building APIs, preventing DOS attacks, or managing system load.
---
# Rate Limiting Implementation
## Table of Contents
- [Overview](#overview)
- [When to Use](#when-to-use)
- [Quick Start](#quick-start)
- [Reference Guides](#reference-guides)
- [Best Practices](#best-practices)
## Overview
Implement rate limiting and throttling mechanisms to protect your services from abuse, ensure fair resource allocation, and maintain system stability under load.
## When to Use
- Protecting public APIs from abuse
- Preventing DOS/DDOS attacks
- Ensuring fair resource usage across users
- Implementing API quotas and billing tiers
- Managing system load and backpressure
- Enforcing SLA limits
- Controlling third-party API usage
- Database connection management
## Quick Start
Minimal working example:
```typescript
interface TokenBucketConfig {
capacity: number;
refillRate: number; // tokens per second
refillInterval: number; // milliseconds
}
class TokenBucket {
private tokens: number;
private lastRefill: number;
private readonly capacity: number;
private readonly refillRate: number;
private readonly refillInterval: number;
private refillTimer?: NodeJS.Timeout;
constructor(config: TokenBucketConfig) {
this.capacity = config.capacity;
this.tokens = config.capacity;
this.refillRate = config.refillRate;
this.refillInterval = config.refillInterval;
this.lastRefill = Date.now();
this.startRefill();
}
private startRefill(): void {
// ... (see reference guides for full implementation)
```
## Reference Guides
Detailed implementations in the `references/` directory:
| Guide | Contents |
|---|---|
| [Token Bucket Algorithm (TypeScript)](references/token-bucket-algorithm-typescript.md) | Token Bucket Algorithm (TypeScript) |
| [Redis-Based Distributed Rate Limiter](references/redis-based-distributed-rate-limiter.md) | Redis-Based Distributed Rate Limiter |
| [Express Middleware](references/express-middleware.md) | Express Middleware |
| [Sliding Window Algorithm (Python)](references/sliding-window-algorithm-python.md) | Sliding Window Algorithm (Python) |
| [Tiered Rate Limiting](references/tiered-rate-limiting.md) | Tiered Rate Limiting |
| [Adaptive Rate Limiting](references/adaptive-rate-limiting.md) | Adaptive Rate Limiting |
## Best Practices
### ✅ DO
- Use distributed rate limiting for multi-server deployments
- Implement multiple rate limit tiers (per second, minute, hour, day)
- Return proper HTTP status codes (429 Too Many Requests)
- Include Retry-After header in responses
- Log rate limit violations for monitoring
- Implement graceful degradation
- Use Redis or similar for persistence
- Consider cost-based rate limiting (expensive operations cost more)
- Implement burst allowances for legitimate traffic spikes
- Provide clear API documentation about limits
### ❌ DON'T
- Store rate limit data in application memory for distributed systems
- Use fixed window counters without considering edge cases
- Forget to clean up expired data
- Block all requests from an IP due to one bad actor
- Set limits too restrictive for legitimate use
- Ignore the impact of rate limiting on user experience
- Fail closed (deny all) when rate limiter fails
© aj-geddes · MIT · aj-geddes/useful-ai-prompts