[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78QEZ5GTAF26AXYTHX6NFGS":3,"skill-same:01M78QEZ5GTAF26AXYTHX6NFGS":75},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":36,"commitSha":37,"skillDirectory":38,"forksCount":39,"repositoryHtmlUrl":40,"repositoryHomepageUrl":6,"ownerHtmlUrl":41,"ownerBlogUrl":42,"ownerDescription":43,"updatedAt":44,"install":45,"resources":58},"01M78QEZ5GTAF26AXYTHX6NFGS","implementing-api-rate-limiting-and-throttling",null,"Implements API rate limiting and throttling controls using token bucket, sliding window, and fixed window algorithms to protect against brute force attacks, credential stuffing, resource exhaustion, and API abuse. The engineer configures per-user, per-IP, and per-endpoint rate limits using Redis-backed counters, API gateway plugins, or application middleware, and implements proper HTTP 429 responses with Retry-After headers. Activates for requests involving rate limiting implementation, API throttling setup, request quota management, or API abuse prevention.","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: implementing-api-rate-limiting-and-throttling\ndescription: >\n  Implements API rate limiting and throttling controls using token bucket, sliding window,\n  and fixed window algorithms to protect against brute force attacks, credential stuffing,\n  resource exhaustion, and API abuse. The engineer configures per-user, per-IP, and per-endpoint\n  rate limits using Redis-backed counters, API gateway plugins, or application middleware,\n  and implements proper HTTP 429 responses with Retry-After headers. Activates for requests\n  involving rate limiting implementation, API throttling setup, request quota management,\n  or API abuse prevention.\ndomain: cybersecurity\nsubdomain: api-security\ntags: [api-security, rate-limiting, throttling, redis, token-bucket, abuse-prevention]\nversion: 1.0.0\nauthor: mahipal\nlicense: Apache-2.0\n---\n# Implementing API Rate Limiting and Throttling\n\n## When to Use\n\n- Protecting authentication endpoints against brute force and credential stuffing attacks\n- Preventing API abuse and resource exhaustion from automated scripts and bots\n- Implementing fair usage quotas for different API consumer tiers (free, premium, enterprise)\n- Defending against denial-of-service attacks at the application layer\n- Meeting compliance requirements that mandate API abuse prevention controls\n\n**Do not use** rate limiting as the sole defense against attacks. Combine with authentication, authorization, and WAF rules.\n\n## Prerequisites\n\n- Redis 6.0+ for distributed rate limit counters (or in-memory for single-instance deployments)\n- API framework (Express.js, FastAPI, Spring Boot, or Django REST Framework)\n- Monitoring system for rate limit metrics (Prometheus, CloudWatch, Datadog)\n- Understanding of the API's normal traffic patterns and peak usage\n- Load testing tool (k6, Gatling, or Locust) for validating rate limit behavior\n\n## Workflow\n\n### Step 1: Rate Limiting Strategy Design\n\nDefine rate limits per endpoint category and user tier:\n\n```python\n# Rate limit configuration\nRATE_LIMITS = {\n    # Authentication endpoints (most restrictive)\n    \"auth\": {\n        \"login\": {\"requests\": 5, \"window_seconds\": 60, \"by\": \"ip\"},\n        \"register\": {\"requests\": 3, \"window_seconds\": 300, \"by\": \"ip\"},\n        \"forgot_password\": {\"requests\": 3, \"window_seconds\": 3600, \"by\": \"ip\"},\n        \"verify_mfa\": {\"requests\": 5, \"window_seconds\": 300, \"by\": \"user\"},\n    },\n    # Standard API endpoints\n    \"api\": {\n        \"free\": {\"requests\": 60, \"window_seconds\": 60, \"by\": \"user\"},\n        \"premium\": {\"requests\": 300, \"window_seconds\": 60, \"by\": \"user\"},\n        \"enterprise\": {\"requests\": 1000, \"window_seconds\": 60, \"by\": \"user\"},\n    },\n    # Resource-intensive endpoints\n    \"expensive\": {\n        \"search\": {\"requests\": 10, \"window_seconds\": 60, \"by\": \"user\"},\n        \"export\": {\"requests\": 5, \"window_seconds\": 3600, \"by\": \"user\"},\n        \"bulk_import\": {\"requests\": 2, \"window_seconds\": 3600, \"by\": \"user\"},\n    },\n    # Global limits\n    \"global\": {\n        \"per_ip\": {\"requests\": 1000, \"window_seconds\": 60, \"by\": \"ip\"},\n        \"per_user\": {\"requests\": 5000, \"window_seconds\": 3600, \"by\": \"user\"},\n    },\n}\n```\n\n### Step 2: Sliding Window Rate Limiter (Redis)\n\n```python\nimport redis\nimport time\nimport hashlib\nfrom functools import wraps\nfrom flask import Flask, request, jsonify, g\n\napp = Flask(__name__)\nredis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)\n\nclass SlidingWindowRateLimiter:\n    \"\"\"Sliding window rate limiter using Redis sorted sets.\"\"\"\n\n    def __init__(self, redis_conn):\n        self.redis = redis_conn\n\n    def is_allowed(self, key, max_requests, window_seconds):\n        \"\"\"Check if request is allowed and record it.\"\"\"\n        now = time.time()\n        window_start = now - window_seconds\n        pipe = self.redis.pipeline()\n\n        # Remove expired entries\n        pipe.zremrangebyscore(key, 0, window_start)\n        # Count requests in current window\n        pipe.zcard(key)\n        # Add current request\n        pipe.zadd(key, {f\"{now}:{hashlib.md5(str(now).encode()).hexdigest()[:8]}\": now})\n        # Set TTL on the key\n        pipe.expire(key, window_seconds + 1)\n\n        results = pipe.execute()\n        current_count = results[1]\n\n        if current_count >= max_requests:\n            # Calculate retry-after\n            oldest = self.redis.zrange(key, 0, 0, withscores=True)\n            if oldest:\n                retry_after = int(oldest[0][1] + window_seconds - now) + 1\n            else:\n                retry_after = window_seconds\n            return False, current_count, max_requests, retry_after\n\n        return True, current_count + 1, max_requests, 0\n\nrate_limiter = SlidingWindowRateLimiter(redis_client)\n\ndef rate_limit(max_requests, window_seconds, key_func=None):\n    \"\"\"Decorator for rate limiting API endpoints.\"\"\"\n    def decorator(f):\n        @wraps(f)\n        def wrapped(*args, **kwargs):\n            # Determine the rate limit key\n            if key_func:\n                identifier = key_func()\n            elif hasattr(g, 'user_id'):\n                identifier = f\"user:{g.user_id}\"\n            else:\n                identifier = f\"ip:{request.remote_addr}\"\n\n            key = f\"ratelimit:{request.endpoint}:{identifier}\"\n            allowed, current, limit, retry_after = rate_limiter.is_allowed(\n                key, max_requests, window_seconds)\n\n            # Always set rate limit headers\n            headers = {\n                \"X-RateLimit-Limit\": str(limit),\n                \"X-RateLimit-Remaining\": str(max(0, limit - current)),\n                \"X-RateLimit-Reset\": str(int(time.time()) + window_seconds),\n            }\n\n            if not allowed:\n                headers[\"Retry-After\"] = str(retry_after)\n                response = jsonify({\n                    \"error\": \"rate_limit_exceeded\",\n                    \"message\": \"Too many requests. Please try again later.\",\n                    \"retry_after\": retry_after\n                })\n                response.status_code = 429\n                for h, v in headers.items():\n                    response.headers[h] = v\n                return response\n\n            response = f(*args, **kwargs)\n            for h, v in headers.items():\n                response.headers[h] = v\n            return response\n        return wrapped\n    return decorator\n\n# Apply rate limiting to endpoints\n@app.route('\u002Fapi\u002Fv1\u002Fauth\u002Flogin', methods=['POST'])\n@rate_limit(max_requests=5, window_seconds=60,\n            key_func=lambda: f\"ip:{request.remote_addr}\")\ndef login():\n    # Login logic\n    return jsonify({\"message\": \"Login successful\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fusers\u002Fme', methods=['GET'])\n@rate_limit(max_requests=60, window_seconds=60)\ndef get_profile():\n    # Profile logic\n    return jsonify({\"user\": \"data\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fsearch', methods=['GET'])\n@rate_limit(max_requests=10, window_seconds=60)\ndef search():\n    # Search logic\n    return jsonify({\"results\": []})\n```\n\n### Step 3: Token Bucket Rate Limiter\n\n```python\nimport redis\nimport time\n\nclass TokenBucketRateLimiter:\n    \"\"\"Token bucket rate limiter allowing burst traffic within limits.\"\"\"\n\n    def __init__(self, redis_conn):\n        self.redis = redis_conn\n\n    def is_allowed(self, key, max_tokens, refill_rate, refill_interval=1):\n        \"\"\"\n        Token bucket algorithm:\n        - max_tokens: Maximum burst capacity\n        - refill_rate: Tokens added per refill_interval\n        - refill_interval: Seconds between refills\n        \"\"\"\n        now = time.time()\n        bucket_key = f\"tb:{key}\"\n\n        # Lua script for atomic token bucket operation\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_tokens = tonumber(ARGV[1])\n        local refill_rate = tonumber(ARGV[2])\n        local refill_interval = tonumber(ARGV[3])\n        local now = tonumber(ARGV[4])\n\n        local bucket = redis.call('hmget', key, 'tokens', 'last_refill')\n        local tokens = tonumber(bucket[1])\n        local last_refill = tonumber(bucket[2])\n\n        if tokens == nil then\n            tokens = max_tokens\n            last_refill = now\n        end\n\n        -- Refill tokens\n        local elapsed = now - last_refill\n        local refills = math.floor(elapsed \u002F refill_interval)\n        if refills > 0 then\n            tokens = math.min(max_tokens, tokens + (refills * refill_rate))\n            last_refill = last_refill + (refills * refill_interval)\n        end\n\n        local allowed = 0\n        if tokens >= 1 then\n            tokens = tokens - 1\n            allowed = 1\n        end\n\n        redis.call('hmset', key, 'tokens', tokens, 'last_refill', last_refill)\n        redis.call('expire', key, math.ceil(max_tokens \u002F refill_rate * refill_interval) + 10)\n\n        return {allowed, tokens, max_tokens}\n        \"\"\"\n\n        result = self.redis.eval(lua_script, 1, bucket_key,\n                                  max_tokens, refill_rate, refill_interval, now)\n        allowed = bool(result[0])\n        remaining = int(result[1])\n        limit = int(result[2])\n\n        return allowed, remaining, limit\n```\n\n### Step 4: Tiered Rate Limiting with User Plans\n\n```python\nfrom enum import Enum\n\nclass UserTier(Enum):\n    FREE = \"free\"\n    PREMIUM = \"premium\"\n    ENTERPRISE = \"enterprise\"\n\nTIER_LIMITS = {\n    UserTier.FREE: {\n        \"default\": (60, 60),          # 60 req\u002Fmin\n        \"search\": (10, 60),           # 10 req\u002Fmin\n        \"export\": (5, 3600),          # 5 req\u002Fhour\n        \"daily_total\": (1000, 86400), # 1000 req\u002Fday\n    },\n    UserTier.PREMIUM: {\n        \"default\": (300, 60),\n        \"search\": (50, 60),\n        \"export\": (20, 3600),\n        \"daily_total\": (10000, 86400),\n    },\n    UserTier.ENTERPRISE: {\n        \"default\": (1000, 60),\n        \"search\": (200, 60),\n        \"export\": (100, 3600),\n        \"daily_total\": (100000, 86400),\n    },\n}\n\ndef get_rate_limit_for_request(user_tier, endpoint_category=\"default\"):\n    \"\"\"Get rate limit configuration based on user tier and endpoint.\"\"\"\n    tier_config = TIER_LIMITS.get(user_tier, TIER_LIMITS[UserTier.FREE])\n    limit_config = tier_config.get(endpoint_category, tier_config[\"default\"])\n    return limit_config  # (max_requests, window_seconds)\n\nclass TieredRateLimitMiddleware:\n    \"\"\"Middleware that applies rate limits based on user subscription tier.\"\"\"\n\n    def __init__(self, app, redis_conn):\n        self.app = app\n        self.limiter = SlidingWindowRateLimiter(redis_conn)\n\n    def __call__(self, environ, start_response):\n        # Extract user info from request\n        user_id = environ.get(\"HTTP_X_USER_ID\")\n        user_tier = UserTier(environ.get(\"HTTP_X_USER_TIER\", \"free\"))\n        endpoint = environ.get(\"PATH_INFO\", \"\u002F\")\n\n        # Determine endpoint category\n        category = \"default\"\n        if \"\u002Fsearch\" in endpoint:\n            category = \"search\"\n        elif \"\u002Fexport\" in endpoint:\n            category = \"export\"\n\n        max_requests, window = get_rate_limit_for_request(user_tier, category)\n        key = f\"tiered:{user_id or environ.get('REMOTE_ADDR')}:{category}\"\n\n        allowed, current, limit, retry_after = self.limiter.is_allowed(\n            key, max_requests, window)\n\n        if not allowed:\n            status = \"429 Too Many Requests\"\n            headers = [\n                (\"Content-Type\", \"application\u002Fjson\"),\n                (\"Retry-After\", str(retry_after)),\n                (\"X-RateLimit-Limit\", str(limit)),\n                (\"X-RateLimit-Remaining\", \"0\"),\n            ]\n            start_response(status, headers)\n            body = f'{{\"error\":\"rate_limit_exceeded\",\"retry_after\":{retry_after},\"tier\":\"{user_tier.value}\"}}'\n            return [body.encode()]\n\n        return self.app(environ, start_response)\n```\n\n### Step 5: Distributed Rate Limiting for Microservices\n\n```python\n# Centralized rate limiting service using Redis Cluster\nimport redis\nfrom redis.cluster import RedisCluster\n\nclass DistributedRateLimiter:\n    \"\"\"Rate limiter for microservice architectures using Redis Cluster.\"\"\"\n\n    def __init__(self):\n        self.redis = RedisCluster(\n            startup_nodes=[\n                {\"host\": \"redis-node-1\", \"port\": 6379},\n                {\"host\": \"redis-node-2\", \"port\": 6379},\n                {\"host\": \"redis-node-3\", \"port\": 6379},\n            ],\n            decode_responses=True\n        )\n\n    def check_and_increment(self, service_name, user_id, endpoint,\n                             max_requests, window_seconds):\n        \"\"\"Atomic check-and-increment using Redis Lua script.\"\"\"\n        key = f\"rl:{{{service_name}}}:{user_id}:{endpoint}\"\n\n        # Lua script ensures atomicity across the check and increment\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_requests = tonumber(ARGV[1])\n        local window = tonumber(ARGV[2])\n        local now = tonumber(ARGV[3])\n        local window_start = now - window\n\n        -- Remove old entries\n        redis.call('zremrangebyscore', key, '-inf', window_start)\n\n        -- Count current entries\n        local count = redis.call('zcard', key)\n\n        if count >= max_requests then\n            -- Get oldest entry for retry-after calculation\n            local oldest = redis.call('zrange', key, 0, 0, 'WITHSCORES')\n            local retry_after = 0\n            if #oldest > 0 then\n                retry_after = math.ceil(tonumber(oldest[2]) + window - now)\n            end\n            return {0, count, retry_after}\n        end\n\n        -- Add new entry\n        redis.call('zadd', key, now, now .. ':' .. math.random(100000))\n        redis.call('expire', key, window + 1)\n\n        return {1, count + 1, 0}\n        \"\"\"\n\n        result = self.redis.eval(lua_script, 1, key,\n                                  max_requests, window_seconds, time.time())\n        return {\n            \"allowed\": bool(result[0]),\n            \"current\": int(result[1]),\n            \"retry_after\": int(result[2]),\n        }\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Sliding Window** | Rate limiting algorithm that tracks requests in a rolling time window, providing smoother rate enforcement than fixed windows |\n| **Token Bucket** | Algorithm where tokens are added at a fixed rate and consumed per request, allowing controlled bursts up to the bucket capacity |\n| **Fixed Window** | Simplest rate limiting where requests are counted per fixed time window (e.g., per minute), susceptible to burst at window boundaries |\n| **429 Too Many Requests** | HTTP status code indicating the client has exceeded the rate limit, accompanied by Retry-After header |\n| **Retry-After Header** | HTTP response header telling the client how many seconds to wait before retrying, essential for well-behaved API clients |\n| **Distributed Rate Limiting** | Rate limiting across multiple server instances using shared state (Redis, Memcached) to maintain accurate global counters |\n\n## Tools & Systems\n\n- **Redis**: In-memory data store used for distributed rate limit counters with atomic operations via Lua scripts\n- **Kong Rate Limiting Plugin**: API gateway plugin supporting fixed-window and sliding-window rate limiting with Redis backend\n- **express-rate-limit**: Express.js middleware for simple rate limiting with Redis, Memcached, or in-memory stores\n- **Flask-Limiter**: Flask extension for rate limiting with support for multiple backends and configurable limits per endpoint\n- **Envoy Rate Limit Service**: Centralized rate limiting service for Envoy-based service mesh architectures\n\n## Common Scenarios\n\n### Scenario: Implementing Rate Limiting for a Public API\n\n**Context**: A company launches a public API with free, premium, and enterprise tiers. The API must protect against abuse while providing fair access to paying customers. The API runs on 6 instances behind an AWS ALB.\n\n**Approach**:\n1. Deploy Redis Cluster (3 nodes) for distributed rate limit state\n2. Implement sliding window rate limiter using Redis sorted sets with Lua scripts for atomicity\n3. Configure per-tier limits: Free (60 req\u002Fmin), Premium (300 req\u002Fmin), Enterprise (1000 req\u002Fmin)\n4. Add stricter limits on authentication endpoints (5 req\u002Fmin per IP) regardless of tier\n5. Implement resource-intensive endpoint limits (search: 10 req\u002Fmin free, export: 5 req\u002Fhour)\n6. Set rate limit response headers on every response (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset)\n7. Return 429 with Retry-After header and JSON error body when limits are exceeded\n8. Set up Prometheus metrics for rate limit hits and CloudWatch alarms for unusual patterns\n\n**Pitfalls**:\n- Using in-memory rate limiting without shared state across instances, allowing limit bypass by hitting different servers\n- Not implementing rate limiting on authentication endpoints separately from general API limits\n- Using fixed windows that allow burst at window boundaries (2x the limit in a short period)\n- Not including rate limit headers on successful responses, giving clients no visibility into their quota\n- Trusting X-Forwarded-For for IP identification without validating it against the load balancer\n\n## Output Format\n\n```\n## Rate Limiting Implementation Report\n\n**API**: Public API v2\n**Algorithm**: Sliding Window (Redis Sorted Sets)\n**Backend**: Redis Cluster (3 nodes)\n**Deployment**: 6 API instances behind AWS ALB\n\n### Rate Limit Configuration\n\n| Tier | Default | Search | Export | Auth (per IP) |\n|------|---------|--------|--------|---------------|\n| Free | 60\u002Fmin | 10\u002Fmin | 5\u002Fhour | 5\u002Fmin |\n| Premium | 300\u002Fmin | 50\u002Fmin | 20\u002Fhour | 5\u002Fmin |\n| Enterprise | 1000\u002Fmin | 200\u002Fmin | 100\u002Fhour | 10\u002Fmin |\n\n### Validation Results (k6 load test)\n\n- Free tier: Rate limited at 61st request (correct)\n- Premium tier: Rate limited at 301st request (correct)\n- Cross-instance: Rate limiting consistent across all 6 instances\n- Redis failover: Rate limiting degrades gracefully (allows traffic) when Redis is unreachable\n- Retry-After header: Accurate within 1 second of actual reset time\n- Response overhead: \u003C 2ms added latency per request for rate limit check\n```\n","# Implementing API Rate Limiting and Throttling\n\n## When to Use\n\n- Protecting authentication endpoints against brute force and credential stuffing attacks\n- Preventing API abuse and resource exhaustion from automated scripts and bots\n- Implementing fair usage quotas for different API consumer tiers (free, premium, enterprise)\n- Defending against denial-of-service attacks at the application layer\n- Meeting compliance requirements that mandate API abuse prevention controls\n\n**Do not use** rate limiting as the sole defense against attacks. Combine with authentication, authorization, and WAF rules.\n\n## Prerequisites\n\n- Redis 6.0+ for distributed rate limit counters (or in-memory for single-instance deployments)\n- API framework (Express.js, FastAPI, Spring Boot, or Django REST Framework)\n- Monitoring system for rate limit metrics (Prometheus, CloudWatch, Datadog)\n- Understanding of the API's normal traffic patterns and peak usage\n- Load testing tool (k6, Gatling, or Locust) for validating rate limit behavior\n\n## Workflow\n\n### Step 1: Rate Limiting Strategy Design\n\nDefine rate limits per endpoint category and user tier:\n\n```python\n# Rate limit configuration\nRATE_LIMITS = {\n    # Authentication endpoints (most restrictive)\n    \"auth\": {\n        \"login\": {\"requests\": 5, \"window_seconds\": 60, \"by\": \"ip\"},\n        \"register\": {\"requests\": 3, \"window_seconds\": 300, \"by\": \"ip\"},\n        \"forgot_password\": {\"requests\": 3, \"window_seconds\": 3600, \"by\": \"ip\"},\n        \"verify_mfa\": {\"requests\": 5, \"window_seconds\": 300, \"by\": \"user\"},\n    },\n    # Standard API endpoints\n    \"api\": {\n        \"free\": {\"requests\": 60, \"window_seconds\": 60, \"by\": \"user\"},\n        \"premium\": {\"requests\": 300, \"window_seconds\": 60, \"by\": \"user\"},\n        \"enterprise\": {\"requests\": 1000, \"window_seconds\": 60, \"by\": \"user\"},\n    },\n    # Resource-intensive endpoints\n    \"expensive\": {\n        \"search\": {\"requests\": 10, \"window_seconds\": 60, \"by\": \"user\"},\n        \"export\": {\"requests\": 5, \"window_seconds\": 3600, \"by\": \"user\"},\n        \"bulk_import\": {\"requests\": 2, \"window_seconds\": 3600, \"by\": \"user\"},\n    },\n    # Global limits\n    \"global\": {\n        \"per_ip\": {\"requests\": 1000, \"window_seconds\": 60, \"by\": \"ip\"},\n        \"per_user\": {\"requests\": 5000, \"window_seconds\": 3600, \"by\": \"user\"},\n    },\n}\n```\n\n### Step 2: Sliding Window Rate Limiter (Redis)\n\n```python\nimport redis\nimport time\nimport hashlib\nfrom functools import wraps\nfrom flask import Flask, request, jsonify, g\n\napp = Flask(__name__)\nredis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)\n\nclass SlidingWindowRateLimiter:\n    \"\"\"Sliding window rate limiter using Redis sorted sets.\"\"\"\n\n    def __init__(self, redis_conn):\n        self.redis = redis_conn\n\n    def is_allowed(self, key, max_requests, window_seconds):\n        \"\"\"Check if request is allowed and record it.\"\"\"\n        now = time.time()\n        window_start = now - window_seconds\n        pipe = self.redis.pipeline()\n\n        # Remove expired entries\n        pipe.zremrangebyscore(key, 0, window_start)\n        # Count requests in current window\n        pipe.zcard(key)\n        # Add current request\n        pipe.zadd(key, {f\"{now}:{hashlib.md5(str(now).encode()).hexdigest()[:8]}\": now})\n        # Set TTL on the key\n        pipe.expire(key, window_seconds + 1)\n\n        results = pipe.execute()\n        current_count = results[1]\n\n        if current_count >= max_requests:\n            # Calculate retry-after\n            oldest = self.redis.zrange(key, 0, 0, withscores=True)\n            if oldest:\n                retry_after = int(oldest[0][1] + window_seconds - now) + 1\n            else:\n                retry_after = window_seconds\n            return False, current_count, max_requests, retry_after\n\n        return True, current_count + 1, max_requests, 0\n\nrate_limiter = SlidingWindowRateLimiter(redis_client)\n\ndef rate_limit(max_requests, window_seconds, key_func=None):\n    \"\"\"Decorator for rate limiting API endpoints.\"\"\"\n    def decorator(f):\n        @wraps(f)\n        def wrapped(*args, **kwargs):\n            # Determine the rate limit key\n            if key_func:\n                identifier = key_func()\n            elif hasattr(g, 'user_id'):\n                identifier = f\"user:{g.user_id}\"\n            else:\n                identifier = f\"ip:{request.remote_addr}\"\n\n            key = f\"ratelimit:{request.endpoint}:{identifier}\"\n            allowed, current, limit, retry_after = rate_limiter.is_allowed(\n                key, max_requests, window_seconds)\n\n            # Always set rate limit headers\n            headers = {\n                \"X-RateLimit-Limit\": str(limit),\n                \"X-RateLimit-Remaining\": str(max(0, limit - current)),\n                \"X-RateLimit-Reset\": str(int(time.time()) + window_seconds),\n            }\n\n            if not allowed:\n                headers[\"Retry-After\"] = str(retry_after)\n                response = jsonify({\n                    \"error\": \"rate_limit_exceeded\",\n                    \"message\": \"Too many requests. Please try again later.\",\n                    \"retry_after\": retry_after\n                })\n                response.status_code = 429\n                for h, v in headers.items():\n                    response.headers[h] = v\n                return response\n\n            response = f(*args, **kwargs)\n            for h, v in headers.items():\n                response.headers[h] = v\n            return response\n        return wrapped\n    return decorator\n\n# Apply rate limiting to endpoints\n@app.route('\u002Fapi\u002Fv1\u002Fauth\u002Flogin', methods=['POST'])\n@rate_limit(max_requests=5, window_seconds=60,\n            key_func=lambda: f\"ip:{request.remote_addr}\")\ndef login():\n    # Login logic\n    return jsonify({\"message\": \"Login successful\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fusers\u002Fme', methods=['GET'])\n@rate_limit(max_requests=60, window_seconds=60)\ndef get_profile():\n    # Profile logic\n    return jsonify({\"user\": \"data\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fsearch', methods=['GET'])\n@rate_limit(max_requests=10, window_seconds=60)\ndef search():\n    # Search logic\n    return jsonify({\"results\": []})\n```\n\n### Step 3: Token Bucket Rate Limiter\n\n```python\nimport redis\nimport time\n\nclass TokenBucketRateLimiter:\n    \"\"\"Token bucket rate limiter allowing burst traffic within limits.\"\"\"\n\n    def __init__(self, redis_conn):\n        self.redis = redis_conn\n\n    def is_allowed(self, key, max_tokens, refill_rate, refill_interval=1):\n        \"\"\"\n        Token bucket algorithm:\n        - max_tokens: Maximum burst capacity\n        - refill_rate: Tokens added per refill_interval\n        - refill_interval: Seconds between refills\n        \"\"\"\n        now = time.time()\n        bucket_key = f\"tb:{key}\"\n\n        # Lua script for atomic token bucket operation\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_tokens = tonumber(ARGV[1])\n        local refill_rate = tonumber(ARGV[2])\n        local refill_interval = tonumber(ARGV[3])\n        local now = tonumber(ARGV[4])\n\n        local bucket = redis.call('hmget', key, 'tokens', 'last_refill')\n        local tokens = tonumber(bucket[1])\n        local last_refill = tonumber(bucket[2])\n\n        if tokens == nil then\n            tokens = max_tokens\n            last_refill = now\n        end\n\n        -- Refill tokens\n        local elapsed = now - last_refill\n        local refills = math.floor(elapsed \u002F refill_interval)\n        if refills > 0 then\n            tokens = math.min(max_tokens, tokens + (refills * refill_rate))\n            last_refill = last_refill + (refills * refill_interval)\n        end\n\n        local allowed = 0\n        if tokens >= 1 then\n            tokens = tokens - 1\n            allowed = 1\n        end\n\n        redis.call('hmset', key, 'tokens', tokens, 'last_refill', last_refill)\n        redis.call('expire', key, math.ceil(max_tokens \u002F refill_rate * refill_interval) + 10)\n\n        return {allowed, tokens, max_tokens}\n        \"\"\"\n\n        result = self.redis.eval(lua_script, 1, bucket_key,\n                                  max_tokens, refill_rate, refill_interval, now)\n        allowed = bool(result[0])\n        remaining = int(result[1])\n        limit = int(result[2])\n\n        return allowed, remaining, limit\n```\n\n### Step 4: Tiered Rate Limiting with User Plans\n\n```python\nfrom enum import Enum\n\nclass UserTier(Enum):\n    FREE = \"free\"\n    PREMIUM = \"premium\"\n    ENTERPRISE = \"enterprise\"\n\nTIER_LIMITS = {\n    UserTier.FREE: {\n        \"default\": (60, 60),          # 60 req\u002Fmin\n        \"search\": (10, 60),           # 10 req\u002Fmin\n        \"export\": (5, 3600),          # 5 req\u002Fhour\n        \"daily_total\": (1000, 86400), # 1000 req\u002Fday\n    },\n    UserTier.PREMIUM: {\n        \"default\": (300, 60),\n        \"search\": (50, 60),\n        \"export\": (20, 3600),\n        \"daily_total\": (10000, 86400),\n    },\n    UserTier.ENTERPRISE: {\n        \"default\": (1000, 60),\n        \"search\": (200, 60),\n        \"export\": (100, 3600),\n        \"daily_total\": (100000, 86400),\n    },\n}\n\ndef get_rate_limit_for_request(user_tier, endpoint_category=\"default\"):\n    \"\"\"Get rate limit configuration based on user tier and endpoint.\"\"\"\n    tier_config = TIER_LIMITS.get(user_tier, TIER_LIMITS[UserTier.FREE])\n    limit_config = tier_config.get(endpoint_category, tier_config[\"default\"])\n    return limit_config  # (max_requests, window_seconds)\n\nclass TieredRateLimitMiddleware:\n    \"\"\"Middleware that applies rate limits based on user subscription tier.\"\"\"\n\n    def __init__(self, app, redis_conn):\n        self.app = app\n        self.limiter = SlidingWindowRateLimiter(redis_conn)\n\n    def __call__(self, environ, start_response):\n        # Extract user info from request\n        user_id = environ.get(\"HTTP_X_USER_ID\")\n        user_tier = UserTier(environ.get(\"HTTP_X_USER_TIER\", \"free\"))\n        endpoint = environ.get(\"PATH_INFO\", \"\u002F\")\n\n        # Determine endpoint category\n        category = \"default\"\n        if \"\u002Fsearch\" in endpoint:\n            category = \"search\"\n        elif \"\u002Fexport\" in endpoint:\n            category = \"export\"\n\n        max_requests, window = get_rate_limit_for_request(user_tier, category)\n        key = f\"tiered:{user_id or environ.get('REMOTE_ADDR')}:{category}\"\n\n        allowed, current, limit, retry_after = self.limiter.is_allowed(\n            key, max_requests, window)\n\n        if not allowed:\n            status = \"429 Too Many Requests\"\n            headers = [\n                (\"Content-Type\", \"application\u002Fjson\"),\n                (\"Retry-After\", str(retry_after)),\n                (\"X-RateLimit-Limit\", str(limit)),\n                (\"X-RateLimit-Remaining\", \"0\"),\n            ]\n            start_response(status, headers)\n            body = f'{{\"error\":\"rate_limit_exceeded\",\"retry_after\":{retry_after},\"tier\":\"{user_tier.value}\"}}'\n            return [body.encode()]\n\n        return self.app(environ, start_response)\n```\n\n### Step 5: Distributed Rate Limiting for Microservices\n\n```python\n# Centralized rate limiting service using Redis Cluster\nimport redis\nfrom redis.cluster import RedisCluster\n\nclass DistributedRateLimiter:\n    \"\"\"Rate limiter for microservice architectures using Redis Cluster.\"\"\"\n\n    def __init__(self):\n        self.redis = RedisCluster(\n            startup_nodes=[\n                {\"host\": \"redis-node-1\", \"port\": 6379},\n                {\"host\": \"redis-node-2\", \"port\": 6379},\n                {\"host\": \"redis-node-3\", \"port\": 6379},\n            ],\n            decode_responses=True\n        )\n\n    def check_and_increment(self, service_name, user_id, endpoint,\n                             max_requests, window_seconds):\n        \"\"\"Atomic check-and-increment using Redis Lua script.\"\"\"\n        key = f\"rl:{{{service_name}}}:{user_id}:{endpoint}\"\n\n        # Lua script ensures atomicity across the check and increment\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_requests = tonumber(ARGV[1])\n        local window = tonumber(ARGV[2])\n        local now = tonumber(ARGV[3])\n        local window_start = now - window\n\n        -- Remove old entries\n        redis.call('zremrangebyscore', key, '-inf', window_start)\n\n        -- Count current entries\n        local count = redis.call('zcard', key)\n\n        if count >= max_requests then\n            -- Get oldest entry for retry-after calculation\n            local oldest = redis.call('zrange', key, 0, 0, 'WITHSCORES')\n            local retry_after = 0\n            if #oldest > 0 then\n                retry_after = math.ceil(tonumber(oldest[2]) + window - now)\n            end\n            return {0, count, retry_after}\n        end\n\n        -- Add new entry\n        redis.call('zadd', key, now, now .. ':' .. math.random(100000))\n        redis.call('expire', key, window + 1)\n\n        return {1, count + 1, 0}\n        \"\"\"\n\n        result = self.redis.eval(lua_script, 1, key,\n                                  max_requests, window_seconds, time.time())\n        return {\n            \"allowed\": bool(result[0]),\n            \"current\": int(result[1]),\n            \"retry_after\": int(result[2]),\n        }\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Sliding Window** | Rate limiting algorithm that tracks requests in a rolling time window, providing smoother rate enforcement than fixed windows |\n| **Token Bucket** | Algorithm where tokens are added at a fixed rate and consumed per request, allowing controlled bursts up to the bucket capacity |\n| **Fixed Window** | Simplest rate limiting where requests are counted per fixed time window (e.g., per minute), susceptible to burst at window boundaries |\n| **429 Too Many Requests** | HTTP status code indicating the client has exceeded the rate limit, accompanied by Retry-After header |\n| **Retry-After Header** | HTTP response header telling the client how many seconds to wait before retrying, essential for well-behaved API clients |\n| **Distributed Rate Limiting** | Rate limiting across multiple server instances using shared state (Redis, Memcached) to maintain accurate global counters |\n\n## Tools & Systems\n\n- **Redis**: In-memory data store used for distributed rate limit counters with atomic operations via Lua scripts\n- **Kong Rate Limiting Plugin**: API gateway plugin supporting fixed-window and sliding-window rate limiting with Redis backend\n- **express-rate-limit**: Express.js middleware for simple rate limiting with Redis, Memcached, or in-memory stores\n- **Flask-Limiter**: Flask extension for rate limiting with support for multiple backends and configurable limits per endpoint\n- **Envoy Rate Limit Service**: Centralized rate limiting service for Envoy-based service mesh architectures\n\n## Common Scenarios\n\n### Scenario: Implementing Rate Limiting for a Public API\n\n**Context**: A company launches a public API with free, premium, and enterprise tiers. The API must protect against abuse while providing fair access to paying customers. The API runs on 6 instances behind an AWS ALB.\n\n**Approach**:\n1. Deploy Redis Cluster (3 nodes) for distributed rate limit state\n2. Implement sliding window rate limiter using Redis sorted sets with Lua scripts for atomicity\n3. Configure per-tier limits: Free (60 req\u002Fmin), Premium (300 req\u002Fmin), Enterprise (1000 req\u002Fmin)\n4. Add stricter limits on authentication endpoints (5 req\u002Fmin per IP) regardless of tier\n5. Implement resource-intensive endpoint limits (search: 10 req\u002Fmin free, export: 5 req\u002Fhour)\n6. Set rate limit response headers on every response (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset)\n7. Return 429 with Retry-After header and JSON error body when limits are exceeded\n8. Set up Prometheus metrics for rate limit hits and CloudWatch alarms for unusual patterns\n\n**Pitfalls**:\n- Using in-memory rate limiting without shared state across instances, allowing limit bypass by hitting different servers\n- Not implementing rate limiting on authentication endpoints separately from general API limits\n- Using fixed windows that allow burst at window boundaries (2x the limit in a short period)\n- Not including rate limit headers on successful responses, giving clients no visibility into their quota\n- Trusting X-Forwarded-For for IP identification without validating it against the load balancer\n\n## Output Format\n\n```\n## Rate Limiting Implementation Report\n\n**API**: Public API v2\n**Algorithm**: Sliding Window (Redis Sorted Sets)\n**Backend**: Redis Cluster (3 nodes)\n**Deployment**: 6 API instances behind AWS ALB\n\n### Rate Limit Configuration\n\n| Tier | Default | Search | Export | Auth (per IP) |\n|------|---------|--------|--------|---------------|\n| Free | 60\u002Fmin | 10\u002Fmin | 5\u002Fhour | 5\u002Fmin |\n| Premium | 300\u002Fmin | 50\u002Fmin | 20\u002Fhour | 5\u002Fmin |\n| Enterprise | 1000\u002Fmin | 200\u002Fmin | 100\u002Fhour | 10\u002Fmin |\n\n### Validation Results (k6 load test)\n\n- Free tier: Rate limited at 61st request (correct)\n- Premium tier: Rate limited at 301st request (correct)\n- Cross-instance: Rate limiting consistent across all 6 instances\n- Redis failover: Rate limiting degrades gracefully (allows traffic) when Redis is unreachable\n- Retry-After header: Accurate within 1 second of actual reset time\n- Response overhead: \u003C 2ms added latency per request for rate limit check\n```\n",{"name":5,"tags":25,"author":32,"domain":33,"license":15,"version":34,"subdomain":26,"description":35},[26,27,28,29,30,31],"api-security","rate-limiting","throttling","redis","token-bucket","abuse-prevention","mahipal","cybersecurity","1.0.0","Implements API rate limiting and throttling controls using token bucket, sliding window, and fixed window algorithms to protect against brute force attacks, credential stuffing, resource exhaustion, and API abuse. The engineer configures per-user, per-IP, and per-endpoint rate limits using Redis-backed counters, API gateway plugins, or application middleware, and implements proper HTTP 429 responses with Retry-After headers. Activates for requests involving rate limiting implementation, API throttling setup, request quota management, or API abuse prevention.\n","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fimplementing-api-rate-limiting-and-throttling",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill implementing-api-rate-limiting-and-throttling",{"tool":51,"command":52},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill implementing-api-rate-limiting-and-throttling",{"tool":54,"command":55},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill implementing-api-rate-limiting-and-throttling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002FSKILL.md",true,[59,63,69],{"path":60,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":62,"sourceHtmlUrl":16},"LICENSE","许可证",11255,{"path":64,"resourceType":65,"resourceTypeDesc":66,"sizeBytes":67,"sourceHtmlUrl":68},"references\u002Fapi-reference.md","REFERENCE","参考文档",1793,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002Freferences\u002Fapi-reference.md",{"path":70,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":74},"scripts\u002Fagent.py","SCRIPT","脚本",6314,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002Fscripts\u002Fagent.py",[76,84,91,98,105,113],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":80,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":20},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":80,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":20},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":80,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":20},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":80,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":20},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":80,"licenseFileUrl":109,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":20},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":80,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":20},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]