jpskill.com
🛠️ 開発・MCP コミュニティ

rate-limiter

APIの利用頻度を制限し、過剰なリクエストや不正アクセスからシステムを保護するために、ユーザーごとやIPアドレスごとのリクエスト数制限、DDoS攻撃対策などを実装するSkill。

📜 元の英語説明(参考)

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.

🇯🇵 日本人クリエイター向け解説

一言でいうと

APIの利用頻度を制限し、過剰なリクエストや不正アクセスからシステムを保護するために、ユーザーごとやIPアドレスごとのリクエスト数制限、DDoS攻撃対策などを実装するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o rate-limiter.zip https://jpskill.com/download/15316.zip && unzip -o rate-limiter.zip && rm rate-limiter.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15316.zip -OutFile "$d\rate-limiter.zip"; Expand-Archive "$d\rate-limiter.zip" -DestinationPath $d -Force; ri "$d\rate-limiter.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して rate-limiter.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → rate-limiter フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Rate Limッター

概要

このスキルは、AIエージェントがAPIの本番環境グレードのレート制限を設計、実装、構成できるようにします。アルゴリズムの選択、ミドルウェアの生成、Redisをバックエンドとした分散カウンティング、不正利用パターンの検出、適切なHTTPレスポンスヘッダーについて説明します。

手順

1. APIサーフェスの評価

コードを書く前に、対象のアプリケーションを分析します。

  • すべてのパブリックエンドポイントとそれらのHTTPメソッドをリストアップします
  • エンドポイントを感度によって分類します:認証(最高)、書き込み操作(高)、読み取り操作(中)、静的/ヘルス(低)
  • 既存のミドルウェアスタックとフレームワーク(Express、Fastify、Django、Ginなど)を特定します
  • Redisまたは別の共有ストアが分散レート制限に使用できるかどうかを確認します

2. 適切なアルゴリズムの選択

ユースケースに基づいて選択します。

アルゴリズム 最適な用途 トレードオフ
Fixed Window 1分あたりの単純な上限 ウィンドウの端でバーストが発生する
Sliding Window Log ユーザーごとの正確な制限 キーごとのメモリ使用量が多い
Sliding Window Counter 精度とメモリのバランス わずかな近似
Token Bucket バースト許容のあるAPI チューニングがより複雑
Leaky Bucket スムーズな出力レート 拒否ではなく遅延させる

デフォルトの推奨:Sliding Window Counter — 優れた精度と妥当なメモリ使用量で、ユースケースの95%を処理します。

3. 階層化された制限の実装

常に少なくとも2つのレイヤーを実装します。

レイヤー1 — グローバルIP制限: 認証前にボリュームベースの不正利用をキャッチします。典型的には、IPあたり100〜300 req/分です。

レイヤー2 — エンドポイント固有の制限: エンドポイントのカテゴリごとに異なる制限を設定します。認証エンドポイントには最も厳しい制限(3〜10 req/分)を設定します。

レイヤー3 — 認証済みユーザーのクォータ(該当する場合):APIキーまたはユーザーIDごとの1日または1時間あたりの上限。レスポンスヘッダーにクォータステータスを返します。

4. レスポンスヘッダー

常にすべてのレスポンスにこれらのヘッダーを含めます(429の場合だけでなく)。

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1708012800
Retry-After: 30  (429レスポンスの場合のみ)

5. 不正利用検出パターン

単純なカウントを超えて、以下を検出します。

  • Credential stuffing: 認証エンドポイントで1つのIPから多数の一意のユーザー名が試行される
  • Scraping: リストエンドポイントでの連続的なアクセスパターン
  • Header anomalies: User-Agentの欠落、急速なリクエストでのヘッダーのローテーション
  • Distributed attacks: 多数のIPにわたる同じUser-Agent/フィンガープリント

6. グレースフルデグラデーション

Redisが利用できない場合は、常にフォールバックを実装します。

  • プロセスごとのインメモリレート制限にフォールバックします
  • Redisの障害を明確にログに記録します
  • 明示的に構成されていない限り、fail open(無制限のリクエストを許可する)しないでください

7. よくある落とし穴の回避

  • Trust proxy configuration: X-Forwarded-Forがどのように解析されるかを常に確認します。ロードバランサーの背後では、クライアントIPがreq.ipではない可能性があります
  • Shared NAT: IPごとの制限を低く設定しすぎないでください。企業ネットワークでは、1つのIPの背後に数千人のユーザーがいる可能性があります。非認証エンドポイントの場合は、最低100 req/分
  • Key design: IPだけでなく、複合キー(ip:endpointuserId:endpoint)を使用します
  • Time sync: 分散セットアップでは、ローカルクロックではなくRedisサーバー時間(TIMEコマンド)を使用します

例1:Redisスライディングウィンドウを使用したExpressミドルウェア

プロンプト: 「Express APIにレート制限を追加してください。認証エンドポイントは、IPあたり1分あたり5リクエストを許可する必要があります。他のすべてのエンドポイントは、認証済みユーザーあたり1分あたり60リクエストを許可する必要があります。」

出力: エージェントは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();
  };
}

例2:Credential stuffingの不正利用検出

プロンプト: 「ログインエンドポイントでcredential stuffingを検出します。5分間に20を超える一意のユーザー名を試行するIPをブロックします。」

出力: エージェントは、Redis HyperLogLogを使用してIPごとの一意のユーザー名試行を追跡する検出ミドルウェアを追加し、しきい値を超えるIPをブロックし、インシデント対応のために完全なリクエストメタデータとともにイベントをログに記録します。

ガイドライン

  • 同時リクエストでレート制限を常にテストしてください — カウンターロジックの競合状態は一般的です
  • 429レスポンスとヘッダー値を検証する統合テストを含めます
  • APIドキュメントまたはOpenAPI仕様でレート制限を文書化します
  • コード変更ではなく、構成を介して有料ティアのレート制限の引き上げを提供することを検討してください
  • セキュリティ監視のために、構造化された形式ですべてのレート制限イベントをログに記録します
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

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