[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ETZ60XNC4EP5D5TGTN7F3H":3,"skill-same:01M6ETZ60XNC4EP5D5TGTN7F3H":102},{"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":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":63,"commitSha":64,"skillDirectory":65,"forksCount":14,"repositoryHtmlUrl":66,"repositoryHomepageUrl":67,"ownerHtmlUrl":68,"ownerBlogUrl":6,"ownerDescription":69,"updatedAt":70,"install":71,"resources":84},"01M6ETZ60XNC4EP5D5TGTN7F3H","implementing-api-abuse-detection-with-rate-limiting",null,"Implement API abuse detection using token bucket, sliding window, and adaptive rate limiting algorithms to prevent DDoS, brute force, and credential stuffing attacks.","henriquescastilho\u002Fmy-claude","henriquescastilho","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F153296945?v=4","01M6ESH7EXPXTH9CVQ4K16SRG8","Henrique Scheer","01M6ESH7JHEK2PTNNH4HEH787Z",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"with","detection","rate limiting","implementing api abuse detection with rate limiting","api","ddos","attacks","de","id","007","cm","PS","cybersecurity","api-gateway","api-abuse","t1059","api-security","gateway","pr","implement","2026-11-10 10:12:30",false,"---\nname: implementing-api-abuse-detection-with-rate-limiting\ndescription: Implement API abuse detection using token bucket, sliding window, and\n  adaptive rate limiting algorithms to prevent DDoS, brute force, and credential stuffing\n  attacks.\ndomain: cybersecurity\nsubdomain: api-security\ntags:\n- api-security\n- rate-limiting\n- token-bucket\n- sliding-window\n- ddos-protection\n- brute-force-prevention\n- api-abuse\n- api-gateway\nversion: '1.0'\nauthor: mahipal\nlicense: Apache-2.0\nnist_csf:\n- PR.PS-01\n- ID.RA-01\n- PR.DS-10\n- DE.CM-01\nmitre_attack:\n- T1190\n- T1059.007\n- T1552.001\n- T1003\n- T1110\n---\n\n# Implementing API Abuse Detection with Rate Limiting\n\n## Overview\n\nAPI rate limiting is a critical security control that restricts the number of requests a client can make within a defined time period. It defends against denial-of-service (DDoS), brute force login attempts, credential stuffing, API scraping, and resource exhaustion attacks. Modern implementations use algorithms like token bucket, sliding window, and fixed window counters, often backed by distributed stores like Redis. Adaptive rate limiting dynamically tightens limits during detected attacks and relaxes during normal operation, achieving a 94% reduction in successful DDoS attempts compared to static IP-based approaches.\n\n\n## When to Use\n\n- When deploying or configuring implementing api abuse detection with rate limiting capabilities in your environment\n- When establishing security controls aligned to compliance requirements\n- When building or improving security architecture for this domain\n- When conducting security assessments that require this implementation\n\n## Prerequisites\n\n- API gateway (Kong, AWS API Gateway, Apigee) or reverse proxy (NGINX, Envoy)\n- Redis or Memcached for distributed rate limit counters\n- Monitoring and alerting infrastructure (Prometheus, Grafana, or SIEM)\n- Understanding of normal API traffic patterns and baselines\n- Python 3.8+ or Node.js for custom implementation\n\n## Rate Limiting Algorithms\n\n### Token Bucket Algorithm\n\nThe token bucket assigns each client a bucket with a fixed capacity of tokens. Tokens refill at a constant rate. Each request consumes one token. When the bucket is empty, requests are rejected. This allows controlled bursts while maintaining average limits.\n\n```python\n\"\"\"Token Bucket Rate Limiter with Redis Backend\n\nImplements a distributed token bucket algorithm for API rate limiting\nwith burst allowance and automatic refill.\n\"\"\"\n\nimport time\nimport redis\nimport json\nfrom typing import Tuple\n\nclass TokenBucketRateLimiter:\n    def __init__(self, redis_client: redis.Redis,\n                 max_tokens: int = 100,\n                 refill_rate: float = 10.0,\n                 key_prefix: str = \"ratelimit:tb\"):\n        self.redis = redis_client\n        self.max_tokens = max_tokens\n        self.refill_rate = refill_rate  # tokens per second\n        self.key_prefix = key_prefix\n\n    def _get_key(self, client_id: str) -> str:\n        return f\"{self.key_prefix}:{client_id}\"\n\n    def allow_request(self, client_id: str, tokens_required: int = 1) -> Tuple[bool, dict]:\n        \"\"\"Check if a request should be allowed under the rate limit.\n\n        Returns (allowed, info) where info contains remaining tokens\n        and retry-after seconds.\n        \"\"\"\n        key = self._get_key(client_id)\n        now = time.time()\n\n        # Atomic token bucket operation using Lua script\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_tokens = tonumber(ARGV[1])\n        local refill_rate = tonumber(ARGV[2])\n        local now = tonumber(ARGV[3])\n        local requested = 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        -- Initialize bucket if it doesn't exist\n        if tokens == nil then\n            tokens = max_tokens\n            last_refill = now\n        end\n\n        -- Calculate refilled tokens\n        local elapsed = now - last_refill\n        local refilled = elapsed * refill_rate\n        tokens = math.min(max_tokens, tokens + refilled)\n\n        -- Check if enough tokens available\n        local allowed = 0\n        if tokens >= requested then\n            tokens = tokens - requested\n            allowed = 1\n        end\n\n        -- Update bucket state\n        redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)\n        redis.call('EXPIRE', key, 3600)  -- TTL for cleanup\n\n        -- Calculate retry-after if denied\n        local retry_after = 0\n        if allowed == 0 then\n            retry_after = math.ceil((requested - tokens) \u002F refill_rate)\n        end\n\n        return {allowed, math.floor(tokens), retry_after}\n        \"\"\"\n        result = self.redis.eval(\n            lua_script, 1, key,\n            self.max_tokens, self.refill_rate, now, tokens_required\n        )\n\n        allowed = bool(result[0])\n        remaining = int(result[1])\n        retry_after = int(result[2])\n\n        return allowed, {\n            \"remaining\": remaining,\n            \"limit\": self.max_tokens,\n            \"retry_after\": retry_after,\n            \"reset\": int(now + (self.max_tokens - remaining) \u002F self.refill_rate)\n        }\n```\n\n### Sliding Window Rate Limiter\n\n```python\n\"\"\"Sliding Window Rate Limiter\n\nTracks requests over a continuously moving time window,\nproviding smoother rate limiting than fixed windows with\nonly a 2.3% false positive rate.\n\"\"\"\n\nclass SlidingWindowRateLimiter:\n    def __init__(self, redis_client: redis.Redis,\n                 window_seconds: int = 60,\n                 max_requests: int = 100,\n                 key_prefix: str = \"ratelimit:sw\"):\n        self.redis = redis_client\n        self.window = window_seconds\n        self.max_requests = max_requests\n        self.key_prefix = key_prefix\n\n    def allow_request(self, client_id: str) -> Tuple[bool, dict]:\n        key = f\"{self.key_prefix}:{client_id}\"\n        now = time.time()\n        window_start = now - self.window\n\n        # Atomic sliding window using sorted set\n        pipe = self.redis.pipeline()\n        # Remove expired entries\n        pipe.zremrangebyscore(key, 0, window_start)\n        # Add current request\n        pipe.zadd(key, {f\"{now}:{id(now)}\": now})\n        # Count requests in window\n        pipe.zcard(key)\n        # Set TTL\n        pipe.expire(key, self.window + 1)\n        results = pipe.execute()\n\n        current_count = results[2]\n        allowed = current_count \u003C= self.max_requests\n\n        if not allowed:\n            # Remove the request we just added since it's denied\n            self.redis.zremrangebyscore(key, now, now)\n\n        return allowed, {\n            \"remaining\": max(0, self.max_requests - current_count),\n            \"limit\": self.max_requests,\n            \"window\": self.window,\n            \"current_count\": current_count\n        }\n```\n\n### Adaptive Rate Limiter\n\n```python\n\"\"\"Adaptive Rate Limiter\n\nDynamically adjusts rate limits based on detected attack patterns.\nTightens limits during attacks and relaxes during normal operation.\n\"\"\"\n\nfrom enum import Enum\nfrom dataclasses import dataclass\n\nclass ThreatLevel(Enum):\n    NORMAL = \"normal\"\n    ELEVATED = \"elevated\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\n@dataclass\nclass AdaptiveLimits:\n    requests_per_minute: int\n    burst_size: int\n    block_duration_seconds: int\n\nTHREAT_LIMITS = {\n    ThreatLevel.NORMAL: AdaptiveLimits(100, 20, 0),\n    ThreatLevel.ELEVATED: AdaptiveLimits(50, 10, 60),\n    ThreatLevel.HIGH: AdaptiveLimits(20, 5, 300),\n    ThreatLevel.CRITICAL: AdaptiveLimits(5, 2, 3600),\n}\n\nclass AdaptiveRateLimiter:\n    def __init__(self, redis_client: redis.Redis):\n        self.redis = redis_client\n        self.token_bucket = TokenBucketRateLimiter(redis_client)\n        self.sliding_window = SlidingWindowRateLimiter(redis_client)\n\n    def assess_threat_level(self, client_id: str) -> ThreatLevel:\n        \"\"\"Assess the current threat level for a client based on behavior.\"\"\"\n        metrics_key = f\"metrics:{client_id}\"\n        metrics = self.redis.hgetall(metrics_key)\n\n        if not metrics:\n            return ThreatLevel.NORMAL\n\n        error_rate = float(metrics.get(b'error_rate', 0))\n        auth_failures = int(metrics.get(b'auth_failures_5m', 0))\n        unique_endpoints = int(metrics.get(b'unique_endpoints_5m', 0))\n        request_rate = float(metrics.get(b'requests_per_second', 0))\n\n        # Scoring-based threat assessment\n        score = 0\n        if auth_failures > 10:\n            score += 3\n        elif auth_failures > 5:\n            score += 2\n        elif auth_failures > 2:\n            score += 1\n\n        if error_rate > 0.8:\n            score += 3\n        elif error_rate > 0.5:\n            score += 2\n\n        if request_rate > 50:\n            score += 2\n        elif request_rate > 20:\n            score += 1\n\n        if unique_endpoints > 50:\n            score += 2  # Possible enumeration\n\n        if score >= 7:\n            return ThreatLevel.CRITICAL\n        elif score >= 5:\n            return ThreatLevel.HIGH\n        elif score >= 3:\n            return ThreatLevel.ELEVATED\n        return ThreatLevel.NORMAL\n\n    def allow_request(self, client_id: str, endpoint: str) -> Tuple[bool, dict]:\n        \"\"\"Rate limit with adaptive thresholds based on threat level.\"\"\"\n        threat_level = self.assess_threat_level(client_id)\n        limits = THREAT_LIMITS[threat_level]\n\n        # Check if client is currently blocked\n        block_key = f\"blocked:{client_id}\"\n        if self.redis.exists(block_key):\n            ttl = self.redis.ttl(block_key)\n            return False, {\n                \"blocked\": True,\n                \"threat_level\": threat_level.value,\n                \"retry_after\": ttl,\n                \"reason\": \"Temporarily blocked due to suspicious activity\"\n            }\n\n        # Apply rate limit with threat-adjusted parameters\n        self.token_bucket.max_tokens = limits.burst_size\n        self.token_bucket.refill_rate = limits.requests_per_minute \u002F 60.0\n\n        allowed, info = self.token_bucket.allow_request(client_id)\n\n        if not allowed and limits.block_duration_seconds > 0:\n            # Block the client for the threat-level duration\n            self.redis.setex(block_key, limits.block_duration_seconds, threat_level.value)\n\n        info[\"threat_level\"] = threat_level.value\n        return allowed, info\n\n    def record_request_outcome(self, client_id: str, status_code: int, endpoint: str):\n        \"\"\"Track request outcomes for threat assessment.\"\"\"\n        metrics_key = f\"metrics:{client_id}\"\n        pipe = self.redis.pipeline()\n\n        pipe.hincrby(metrics_key, 'total_requests', 1)\n        if status_code in (401, 403):\n            pipe.hincrby(metrics_key, 'auth_failures_5m', 1)\n        if status_code >= 400:\n            pipe.hincrby(metrics_key, 'errors_5m', 1)\n\n        # Track unique endpoints for enumeration detection\n        pipe.sadd(f\"endpoints:{client_id}\", endpoint)\n        pipe.expire(metrics_key, 300)  # 5-minute window\n        pipe.expire(f\"endpoints:{client_id}\", 300)\n        pipe.execute()\n```\n\n### NGINX Rate Limiting Configuration\n\n```nginx\n# Define rate limit zones\nlimit_req_zone $binary_remote_addr zone=api_general:10m rate=10r\u002Fs;\nlimit_req_zone $binary_remote_addr zone=api_auth:10m rate=3r\u002Fs;\nlimit_req_zone $binary_remote_addr zone=api_sensitive:10m rate=1r\u002Fs;\n\n# Apply rate limits to API routes\nserver {\n    listen 443 ssl;\n\n    # General API endpoints - 10 req\u002Fs with burst of 20\n    location \u002Fapi\u002Fv1\u002F {\n        limit_req zone=api_general burst=20 nodelay;\n        limit_req_status 429;\n        proxy_pass http:\u002F\u002Fapi_backend;\n    }\n\n    # Authentication endpoints - strict 3 req\u002Fs\n    location \u002Fapi\u002Fv1\u002Fauth\u002F {\n        limit_req zone=api_auth burst=5;\n        limit_req_status 429;\n        proxy_pass http:\u002F\u002Fapi_backend;\n    }\n\n    # Sensitive data endpoints - 1 req\u002Fs\n    location \u002Fapi\u002Fv1\u002Fadmin\u002F {\n        limit_req zone=api_sensitive burst=3;\n        limit_req_status 429;\n        proxy_pass http:\u002F\u002Fapi_backend;\n    }\n\n    # Custom 429 response with Retry-After header\n    error_page 429 = @rate_limited;\n    location @rate_limited {\n        add_header Retry-After 30;\n        add_header X-RateLimit-Limit $limit_req_status;\n        return 429 '{\"error\": \"rate_limit_exceeded\", \"retry_after\": 30}';\n    }\n}\n```\n\n## Response Headers\n\nAlways include standard rate limit headers:\n\n```\nHTTP\u002F1.1 429 Too Many Requests\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 0\nX-RateLimit-Reset: 1672531200\nRetry-After: 30\nContent-Type: application\u002Fjson\n\n{\"error\": \"rate_limit_exceeded\", \"retry_after\": 30}\n```\n\n## References\n\n- APIsec Rate Limiting Strategies: https:\u002F\u002Fwww.apisec.ai\u002Fblog\u002Fapi-rate-limiting-strategies-preventing\n- HackerOne Rate Limiting Best Practices: https:\u002F\u002Fwww.hackerone.com\u002Fblog\u002Frate-limiting-strategies-protecting-your-api-ddos-and-brute-force-attacks\n- API7.ai Rate Limiting Algorithms Guide: https:\u002F\u002Fapi7.ai\u002Fblog\u002Frate-limiting-guide-algorithms-best-practices\n- Redis Rate Limiting: https:\u002F\u002Fredis.io\u002Fglossary\u002Frate-limiting\u002F\n- Rakuten SixthSense API Rate Limiting: https:\u002F\u002Fsixthsense.rakuten.com\u002Fblog\u002FAPI-Rate-Limiting-A-Critical-Layer-for-API-Protection\n","# Implementing API Abuse Detection with Rate Limiting\n\n## Overview\n\nAPI rate limiting is a critical security control that restricts the number of requests a client can make within a defined time period. It defends against denial-of-service (DDoS), brute force login attempts, credential stuffing, API scraping, and resource exhaustion attacks. Modern implementations use algorithms like token bucket, sliding window, and fixed window counters, often backed by distributed stores like Redis. Adaptive rate limiting dynamically tightens limits during detected attacks and relaxes during normal operation, achieving a 94% reduction in successful DDoS attempts compared to static IP-based approaches.\n\n\n## When to Use\n\n- When deploying or configuring implementing api abuse detection with rate limiting capabilities in your environment\n- When establishing security controls aligned to compliance requirements\n- When building or improving security architecture for this domain\n- When conducting security assessments that require this implementation\n\n## Prerequisites\n\n- API gateway (Kong, AWS API Gateway, Apigee) or reverse proxy (NGINX, Envoy)\n- Redis or Memcached for distributed rate limit counters\n- Monitoring and alerting infrastructure (Prometheus, Grafana, or SIEM)\n- Understanding of normal API traffic patterns and baselines\n- Python 3.8+ or Node.js for custom implementation\n\n## Rate Limiting Algorithms\n\n### Token Bucket Algorithm\n\nThe token bucket assigns each client a bucket with a fixed capacity of tokens. Tokens refill at a constant rate. Each request consumes one token. When the bucket is empty, requests are rejected. This allows controlled bursts while maintaining average limits.\n\n```python\n\"\"\"Token Bucket Rate Limiter with Redis Backend\n\nImplements a distributed token bucket algorithm for API rate limiting\nwith burst allowance and automatic refill.\n\"\"\"\n\nimport time\nimport redis\nimport json\nfrom typing import Tuple\n\nclass TokenBucketRateLimiter:\n    def __init__(self, redis_client: redis.Redis,\n                 max_tokens: int = 100,\n                 refill_rate: float = 10.0,\n                 key_prefix: str = \"ratelimit:tb\"):\n        self.redis = redis_client\n        self.max_tokens = max_tokens\n        self.refill_rate = refill_rate  # tokens per second\n        self.key_prefix = key_prefix\n\n    def _get_key(self, client_id: str) -> str:\n        return f\"{self.key_prefix}:{client_id}\"\n\n    def allow_request(self, client_id: str, tokens_required: int = 1) -> Tuple[bool, dict]:\n        \"\"\"Check if a request should be allowed under the rate limit.\n\n        Returns (allowed, info) where info contains remaining tokens\n        and retry-after seconds.\n        \"\"\"\n        key = self._get_key(client_id)\n        now = time.time()\n\n        # Atomic token bucket operation using Lua script\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_tokens = tonumber(ARGV[1])\n        local refill_rate = tonumber(ARGV[2])\n        local now = tonumber(ARGV[3])\n        local requested = 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        -- Initialize bucket if it doesn't exist\n        if tokens == nil then\n            tokens = max_tokens\n            last_refill = now\n        end\n\n        -- Calculate refilled tokens\n        local elapsed = now - last_refill\n        local refilled = elapsed * refill_rate\n        tokens = math.min(max_tokens, tokens + refilled)\n\n        -- Check if enough tokens available\n        local allowed = 0\n        if tokens >= requested then\n            tokens = tokens - requested\n            allowed = 1\n        end\n\n        -- Update bucket state\n        redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)\n        redis.call('EXPIRE', key, 3600)  -- TTL for cleanup\n\n        -- Calculate retry-after if denied\n        local retry_after = 0\n        if allowed == 0 then\n            retry_after = math.ceil((requested - tokens) \u002F refill_rate)\n        end\n\n        return {allowed, math.floor(tokens), retry_after}\n        \"\"\"\n        result = self.redis.eval(\n            lua_script, 1, key,\n            self.max_tokens, self.refill_rate, now, tokens_required\n        )\n\n        allowed = bool(result[0])\n        remaining = int(result[1])\n        retry_after = int(result[2])\n\n        return allowed, {\n            \"remaining\": remaining,\n            \"limit\": self.max_tokens,\n            \"retry_after\": retry_after,\n            \"reset\": int(now + (self.max_tokens - remaining) \u002F self.refill_rate)\n        }\n```\n\n### Sliding Window Rate Limiter\n\n```python\n\"\"\"Sliding Window Rate Limiter\n\nTracks requests over a continuously moving time window,\nproviding smoother rate limiting than fixed windows with\nonly a 2.3% false positive rate.\n\"\"\"\n\nclass SlidingWindowRateLimiter:\n    def __init__(self, redis_client: redis.Redis,\n                 window_seconds: int = 60,\n                 max_requests: int = 100,\n                 key_prefix: str = \"ratelimit:sw\"):\n        self.redis = redis_client\n        self.window = window_seconds\n        self.max_requests = max_requests\n        self.key_prefix = key_prefix\n\n    def allow_request(self, client_id: str) -> Tuple[bool, dict]:\n        key = f\"{self.key_prefix}:{client_id}\"\n        now = time.time()\n        window_start = now - self.window\n\n        # Atomic sliding window using sorted set\n        pipe = self.redis.pipeline()\n        # Remove expired entries\n        pipe.zremrangebyscore(key, 0, window_start)\n        # Add current request\n        pipe.zadd(key, {f\"{now}:{id(now)}\": now})\n        # Count requests in window\n        pipe.zcard(key)\n        # Set TTL\n        pipe.expire(key, self.window + 1)\n        results = pipe.execute()\n\n        current_count = results[2]\n        allowed = current_count \u003C= self.max_requests\n\n        if not allowed:\n            # Remove the request we just added since it's denied\n            self.redis.zremrangebyscore(key, now, now)\n\n        return allowed, {\n            \"remaining\": max(0, self.max_requests - current_count),\n            \"limit\": self.max_requests,\n            \"window\": self.window,\n            \"current_count\": current_count\n        }\n```\n\n### Adaptive Rate Limiter\n\n```python\n\"\"\"Adaptive Rate Limiter\n\nDynamically adjusts rate limits based on detected attack patterns.\nTightens limits during attacks and relaxes during normal operation.\n\"\"\"\n\nfrom enum import Enum\nfrom dataclasses import dataclass\n\nclass ThreatLevel(Enum):\n    NORMAL = \"normal\"\n    ELEVATED = \"elevated\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\n@dataclass\nclass AdaptiveLimits:\n    requests_per_minute: int\n    burst_size: int\n    block_duration_seconds: int\n\nTHREAT_LIMITS = {\n    ThreatLevel.NORMAL: AdaptiveLimits(100, 20, 0),\n    ThreatLevel.ELEVATED: AdaptiveLimits(50, 10, 60),\n    ThreatLevel.HIGH: AdaptiveLimits(20, 5, 300),\n    ThreatLevel.CRITICAL: AdaptiveLimits(5, 2, 3600),\n}\n\nclass AdaptiveRateLimiter:\n    def __init__(self, redis_client: redis.Redis):\n        self.redis = redis_client\n        self.token_bucket = TokenBucketRateLimiter(redis_client)\n        self.sliding_window = SlidingWindowRateLimiter(redis_client)\n\n    def assess_threat_level(self, client_id: str) -> ThreatLevel:\n        \"\"\"Assess the current threat level for a client based on behavior.\"\"\"\n        metrics_key = f\"metrics:{client_id}\"\n        metrics = self.redis.hgetall(metrics_key)\n\n        if not metrics:\n            return ThreatLevel.NORMAL\n\n        error_rate = float(metrics.get(b'error_rate', 0))\n        auth_failures = int(metrics.get(b'auth_failures_5m', 0))\n        unique_endpoints = int(metrics.get(b'unique_endpoints_5m', 0))\n        request_rate = float(metrics.get(b'requests_per_second', 0))\n\n        # Scoring-based threat assessment\n        score = 0\n        if auth_failures > 10:\n            score += 3\n        elif auth_failures > 5:\n            score += 2\n        elif auth_failures > 2:\n            score += 1\n\n        if error_rate > 0.8:\n            score += 3\n        elif error_rate > 0.5:\n            score += 2\n\n        if request_rate > 50:\n            score += 2\n        elif request_rate > 20:\n            score += 1\n\n        if unique_endpoints > 50:\n            score += 2  # Possible enumeration\n\n        if score >= 7:\n            return ThreatLevel.CRITICAL\n        elif score >= 5:\n            return ThreatLevel.HIGH\n        elif score >= 3:\n            return ThreatLevel.ELEVATED\n        return ThreatLevel.NORMAL\n\n    def allow_request(self, client_id: str, endpoint: str) -> Tuple[bool, dict]:\n        \"\"\"Rate limit with adaptive thresholds based on threat level.\"\"\"\n        threat_level = self.assess_threat_level(client_id)\n        limits = THREAT_LIMITS[threat_level]\n\n        # Check if client is currently blocked\n        block_key = f\"blocked:{client_id}\"\n        if self.redis.exists(block_key):\n            ttl = self.redis.ttl(block_key)\n            return False, {\n                \"blocked\": True,\n                \"threat_level\": threat_level.value,\n                \"retry_after\": ttl,\n                \"reason\": \"Temporarily blocked due to suspicious activity\"\n            }\n\n        # Apply rate limit with threat-adjusted parameters\n        self.token_bucket.max_tokens = limits.burst_size\n        self.token_bucket.refill_rate = limits.requests_per_minute \u002F 60.0\n\n        allowed, info = self.token_bucket.allow_request(client_id)\n\n        if not allowed and limits.block_duration_seconds > 0:\n            # Block the client for the threat-level duration\n            self.redis.setex(block_key, limits.block_duration_seconds, threat_level.value)\n\n        info[\"threat_level\"] = threat_level.value\n        return allowed, info\n\n    def record_request_outcome(self, client_id: str, status_code: int, endpoint: str):\n        \"\"\"Track request outcomes for threat assessment.\"\"\"\n        metrics_key = f\"metrics:{client_id}\"\n        pipe = self.redis.pipeline()\n\n        pipe.hincrby(metrics_key, 'total_requests', 1)\n        if status_code in (401, 403):\n            pipe.hincrby(metrics_key, 'auth_failures_5m', 1)\n        if status_code >= 400:\n            pipe.hincrby(metrics_key, 'errors_5m', 1)\n\n        # Track unique endpoints for enumeration detection\n        pipe.sadd(f\"endpoints:{client_id}\", endpoint)\n        pipe.expire(metrics_key, 300)  # 5-minute window\n        pipe.expire(f\"endpoints:{client_id}\", 300)\n        pipe.execute()\n```\n\n### NGINX Rate Limiting Configuration\n\n```nginx\n# Define rate limit zones\nlimit_req_zone $binary_remote_addr zone=api_general:10m rate=10r\u002Fs;\nlimit_req_zone $binary_remote_addr zone=api_auth:10m rate=3r\u002Fs;\nlimit_req_zone $binary_remote_addr zone=api_sensitive:10m rate=1r\u002Fs;\n\n# Apply rate limits to API routes\nserver {\n    listen 443 ssl;\n\n    # General API endpoints - 10 req\u002Fs with burst of 20\n    location \u002Fapi\u002Fv1\u002F {\n        limit_req zone=api_general burst=20 nodelay;\n        limit_req_status 429;\n        proxy_pass http:\u002F\u002Fapi_backend;\n    }\n\n    # Authentication endpoints - strict 3 req\u002Fs\n    location \u002Fapi\u002Fv1\u002Fauth\u002F {\n        limit_req zone=api_auth burst=5;\n        limit_req_status 429;\n        proxy_pass http:\u002F\u002Fapi_backend;\n    }\n\n    # Sensitive data endpoints - 1 req\u002Fs\n    location \u002Fapi\u002Fv1\u002Fadmin\u002F {\n        limit_req zone=api_sensitive burst=3;\n        limit_req_status 429;\n        proxy_pass http:\u002F\u002Fapi_backend;\n    }\n\n    # Custom 429 response with Retry-After header\n    error_page 429 = @rate_limited;\n    location @rate_limited {\n        add_header Retry-After 30;\n        add_header X-RateLimit-Limit $limit_req_status;\n        return 429 '{\"error\": \"rate_limit_exceeded\", \"retry_after\": 30}';\n    }\n}\n```\n\n## Response Headers\n\nAlways include standard rate limit headers:\n\n```\nHTTP\u002F1.1 429 Too Many Requests\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 0\nX-RateLimit-Reset: 1672531200\nRetry-After: 30\nContent-Type: application\u002Fjson\n\n{\"error\": \"rate_limit_exceeded\", \"retry_after\": 30}\n```\n\n## References\n\n- APIsec Rate Limiting Strategies: https:\u002F\u002Fwww.apisec.ai\u002Fblog\u002Fapi-rate-limiting-strategies-preventing\n- HackerOne Rate Limiting Best Practices: https:\u002F\u002Fwww.hackerone.com\u002Fblog\u002Frate-limiting-strategies-protecting-your-api-ddos-and-brute-force-attacks\n- API7.ai Rate Limiting Algorithms Guide: https:\u002F\u002Fapi7.ai\u002Fblog\u002Frate-limiting-guide-algorithms-best-practices\n- Redis Rate Limiting: https:\u002F\u002Fredis.io\u002Fglossary\u002Frate-limiting\u002F\n- Rakuten SixthSense API Rate Limiting: https:\u002F\u002Fsixthsense.rakuten.com\u002Fblog\u002FAPI-Rate-Limiting-A-Critical-Layer-for-API-Protection\n",{"name":5,"tags":44,"author":50,"domain":31,"license":15,"version":51,"nist_csf":52,"subdomain":35,"description":7,"mitre_attack":57},[35,45,46,47,48,49,33,32],"rate-limiting","token-bucket","sliding-window","ddos-protection","brute-force-prevention","mahipal","1.0",[53,54,55,56],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[58,59,60,61,62],"T1190","T1059.007","T1552.001","T1003","T1110","main","7925716f065257435fdb12e97f7e52842147d5ad",".claude\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude","https:\u002F\u002Fclaude.com\u002Fclaude-code","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho","Software · Applied AI · Quantitative Modeling · Building with Claude.","2026-06-10 12:24:46",{"source":8,"skillName":5,"commands":72,"prompt":82,"zipAvailable":83},[73,76,79],{"tool":74,"command":75},"npx","npx skills add henriquescastilho\u002Fmy-claude --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":77,"command":78},"bunx","bunx skills add henriquescastilho\u002Fmy-claude --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":80,"command":81},"pnpm","pnpm dlx skills add henriquescastilho\u002Fmy-claude --skill implementing-api-abuse-detection-with-rate-limiting","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FSKILL.md",true,[85,90,96],{"path":86,"resourceType":86,"resourceTypeDesc":87,"sizeBytes":88,"sourceHtmlUrl":89},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FLICENSE",{"path":91,"resourceType":92,"resourceTypeDesc":93,"sizeBytes":94,"sourceHtmlUrl":95},"references\u002Fapi-reference.md","REFERENCE","参考文档",2007,"https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002Freferences\u002Fapi-reference.md",{"path":97,"resourceType":98,"resourceTypeDesc":99,"sizeBytes":100,"sourceHtmlUrl":101},"scripts\u002Fagent.py","SCRIPT","脚本",7070,"https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002Fscripts\u002Fagent.py",[103,129,134,139,161,186],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":39},"01M6F0B6XPQ65AX2X0DWK8KT3E","markitdown","Convert files and office documents to Markdown. Supports PDF, DOCX, PPTX, XLSX, images (with OCR), audio (with transcription), HTML, CSV, JSON, XML, ZIP, YouTube URLs, EPubs and more.","MIT","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-writer\u002Fskills\u002Fmarkitdown\u002FSKILL.md",[],[105,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,19],"docx","PDF","pptx","xlsx","documents","csv","ocr","Audio","Bash","markdown","convert","read","write","edit","html","images","files","youtube",{"skillNo":130,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":131,"categories":132,"keywords":133,"publishedAt":39},"01M6F06SBHR9F0SDWE282Y8075","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-writer\u002Fscientific_writer\u002F.claude\u002Fskills\u002Fmarkitdown\u002FSKILL.md",[],[105,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,19],{"skillNo":135,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":39},"01M6F02D4R14EJAPBWVDF9J9VQ","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-writer\u002F.claude\u002Fskills\u002Fmarkitdown\u002FSKILL.md",[],[105,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,19],{"skillNo":140,"name":141,"nameZh":6,"description":142,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":143,"categories":144,"keywords":145,"publishedAt":39},"01M6F000KS6YB4MKS774G4R8ND","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-skills\u002Fscientific-skills\u002Fzarr-python\u002FSKILL.md",[],[146,147,148,149,150,151,152,153,154,155,156,157,158,159,160],"python","zarr python","storage","integration","s3","gcs","cloud","dask","parallel","pipelines","arrays","numpy","scientific computing","scale","scientific",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":165,"categories":166,"keywords":167,"publishedAt":39},"01M6EZZJWFXM1GR78KTW6J0DN8","what-if-oracle","Run structured What-If scenario analysis with multi-branch possibility exploration. Use this skill when the user asks speculative questions like \"what if...\", \"what would happen if...\", \"what are the possibilities\", \"explore scenarios\", \"scenario analysis\", \"possibility space\", \"what could go wrong\", \"best case \u002F worst case\", \"risk analysis\", \"contingency planning\", \"strategic options\", or any question about uncertain futures. Also trigger when the user faces a fork-in-the-road decision, wants to stress-test an idea, or needs to think through consequences before committing.","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-skills\u002Fscientific-skills\u002Fwhat-if-oracle\u002FSKILL.md",[],[168,169,170,171,172,173,174,175,176,177,178,122,123,179,180,181,182,183,184,185],"oracle","what if oracle","go","run","ux","futures","analysis","explore","decision","branch","question","idea","exploration","options","stress-test","strategies","scenario","stress",{"skillNo":187,"name":188,"nameZh":6,"description":189,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":190,"categories":191,"keywords":192,"publishedAt":39},"01M6EZZCXAEB49RXGQCJX5E8GB","venue-templates","Access comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-skills\u002Fscientific-skills\u002Fvenue-templates\u002FSKILL.md",[],[193,194,195,196,197,198,199,200,119,201,122,123,124,202,203,204,205,206,160,207],"templates","venue templates","research","guidelines","NeurIPS","ICML","LaTeX","science","access","proposals","Academic","requirements","formatting","journal","chi"]