Skip to content
Skillpedia
APIs & servers (backend)35k · #5825

implementing-api-rate-limiting-and-throttling

Has your agent control how many times a service can be accessed. This prevents overload and attacks. It's useful for keeping services stable and secure.

What it does

This tool helps control how many times a user can access a part of a system (API) within a certain time frame. This prevents the system from being overloaded or misused.

When to use it

  • ✓Protecting logins against brute-force attacks.
  • ✓Preventing bots from sending too many requests quickly.
  • ✓Ensuring all users have fair access to resources.

Example of what to ask your AI

“Set a limit of 100 requests per minute for standard users and 10 requests per minute for free users on the search API.”

Want more? Open the sections below.

How to use

The easiest way: copy the message below and paste it into Claude, ChatGPT, Cursor or any AI. It reads the skill and follows the instructions.

Skill link

https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/implementing-api-rate-limiting-and-throttling/SKILL.md

Ready-to-paste message

Use this skill to help me: https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/implementing-api-rate-limiting-and-throttling/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
How it works

It works by setting rules on how many requests are allowed. If someone tries to make more requests than permitted, the system will tell them to wait a bit before trying again.

Installation

Easiest way: copy the skill link and paste it into Claude, ChatGPT or Cursor asking it to follow the instructions.

In the terminal (Claude Code, Codex, Cursor), in your project folder:

npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill implementing-api-rate-limiting-and-throttling

Or download just the file:

curl -L https://raw.githubusercontent.com/mukul975/Anthropic-Cybersecurity-Skills/main/skills/implementing-api-rate-limiting-and-throttling/SKILL.md -o SKILL.md
Technical content (original SKILL.md)

Original text by the author, straight from GitHub.

Implementing API Rate Limiting and Throttling

When to Use

  • Protecting authentication endpoints against brute force and credential stuffing attacks
  • Preventing API abuse and resource exhaustion from automated scripts and bots
  • Implementing fair usage quotas for different API consumer tiers (free, premium, enterprise)
  • Defending against denial-of-service attacks at the application layer
  • Meeting compliance requirements that mandate API abuse prevention controls

Do not use rate limiting as the sole defense against attacks. Combine with authentication, authorization, and WAF rules.

Prerequisites

  • Redis 6.0+ for distributed rate limit counters (or in-memory for single-instance deployments)
  • API framework (Express.js, FastAPI, Spring Boot, or Django REST Framework)
  • Monitoring system for rate limit metrics (Prometheus, CloudWatch, Datadog)
  • Understanding of the API's normal traffic patterns and peak usage
  • Load testing tool (k6, Gatling, or Locust) for validating rate limit behavior

Workflow

Step 1: Rate Limiting Strategy Design

Define rate limits per endpoint category and user tier:

# Rate limit configuration
RATE_LIMITS = {
    # Authentication endpoints (most restrictive)
    "auth": {
        "login": {"requests": 5, "window_seconds": 60, "by": "ip"},
        "register": {"requests": 3, "window_seconds": 300, "by": "ip"},
        "forgot_password": {"requests": 3, "window_seconds": 3600, "by": "ip"},
        "verify_mfa": {"requests": 5, "window_seconds": 300, "by": "user"},
    },
    # Standard API endpoints
    "api": {
        "free": {"requests": 60, "window_seconds": 60, "by": "user"},
        "premium": {"requests": 300, "window_seconds": 60, "by": "user"},
        "enterprise": {"requests": 1000, "window_seconds": 60, "by": "user"},
    },
    # Resource-intensive endpoints
    "expensive": {
        "search": {"requests": 10, "window_seconds": 60, "by": "user"},
        "export": {"requests": 5, "window_seconds": 3600, "by": "user"},
        "bulk_import": {"requests": 2, "window_seconds": 3600, "by": "user"},
    },
    # Global limits
    "global": {
        "per_ip": {"requests": 1000, "window_seconds": 60, "by": "ip"},
        "per_user": {"requests": 5000, "window_seconds": 3600, "by": "user"},
    },
}

Step 2: Sliding Window Rate Limiter (Redis)

import redis
import time
import hashlib
from functools import wraps
from flask import Flask, request, jsonify, g

app = Flask(__name__)
redis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

class SlidingWindowRateLimiter:
    """Sliding window rate limiter using Redis sorted sets."""

    def __init__(self, redis_conn):
        self.redis = redis_conn

    def is_allowed(self, key, max_requests, window_seconds):
        """Check if request is allowed and record it."""
        now = time.time()
        window_start = now - window_seconds
        pipe = self.redis.pipeline()

        # Remove expired entries
        pipe.zremrangebyscore(key, 0, window_start)
        # Count requests in current window
        pipe.zcard(key)
        # Add current request
        pipe.zadd(key, {f"{now}:{hashlib.md5(str(now).encode()).hexdigest()[:8]}": now})
        # Set TTL on the key
        pipe.expire(key, window_seconds + 1)

        results = pipe.execute()
        current_count = results[1]

        if current_count >= max_requests:
            # Calculate retry-after
            oldest = self.redis.zrange(key, 0, 0, withscores=True)
            if oldest:
                retry_after = int(oldest[0][1] + window_seconds - now) + 1
            else:
                retry_after = window_seconds
            return False, current_count, max_requests, retry_after

        return True, current_count + 1, max_requests, 0

rate_limiter = SlidingWindowRateLimiter(redis_client)

def rate_limit(max_requests, window_seconds, key_func=None):
    """Decorator for rate limiting API endpoints."""
    def decorator(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            # Determine the rate limit key
            if key_func:
                identifier = key_func()
            elif hasattr(g, 'user_id'):
                identifier = f"user:{g.user_id}"
            else:
                identifier = f"ip:{request.remote_addr}"

            key = f"ratelimit:{request.endpoint}:{identifier}"
            allowed, current, limit, retry_after = rate_limiter.is_allowed(

…
FAQ

What is 'rate limiting'?

'Rate limiting' is controlling the rate of requests a user can make to a service within a given time.

What is 'throttling'?

'Throttling' is the action of reducing or limiting the request rate when a limit is reached.

Why use request limits?

To protect the system from overload, attacks, and ensure fair usage for everyone.

Details

Original description by the author

Implements API rate limiting and throttling with token bucket, sliding window, and fixed window algorithms, configuring per-user, per-IP, and per-endpoint limits via Redis-backed counters, API gateway plugins, or middleware, and returning proper HTTP 429 responses with Retry-After headers. Use when setting up request quota management or preventing brute force, credential stuffing, and resource exh

repo: mukul975/Anthropic-Cybersecurity-Skills

Popularity

GitHub stars
35k
Ranking position
#5825
License
Apache-2.0
Updated
8/31/2026

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills