[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6AEYH1NM63VT3J5D7MSNVYX":3,"skill-same:01M6AEYH1NM63VT3J5D7MSNVYX":108},{"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":28,"publishedAt":48,"linkOnly":49,"markdownContent":50,"markdownBody":51,"frontMatter":52,"refName":67,"commitSha":68,"skillDirectory":69,"forksCount":70,"repositoryHtmlUrl":71,"repositoryHomepageUrl":72,"ownerHtmlUrl":73,"ownerBlogUrl":74,"ownerDescription":75,"updatedAt":76,"install":77,"resources":90},"01M6AEYH1NM63VT3J5D7MSNVYX","implementing-api-abuse-detection-with-rate-limiting",null,"Implements API abuse detection using token bucket, sliding window, and fixed window rate-limiting algorithms backed by Redis, including adaptive limits that tighten during detected attacks and relax during normal traffic. Use when defending APIs against DDoS, brute force login attempts, credential stuffing, or scraping abuse and you need to design or tune rate-limiting logic.","mukul975\u002FAnthropic-Cybersecurity-Skills","mukul975","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42860185?v=4","01M6ADEQR8T5M4EEG6C67BQCWF","Mahipal","01M6ADJPMYWG1E5GM1FWBE3128",35990,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47],"implementing api abuse detection with rate limiting","detection","rate-limiting","api-gateway","api-abuse","brute-force-prevention","ddos-protection","sliding-window","token-bucket","t1059","t1003","design","brute-force","api-security","redis","gateway","pr","cybersecurity","security","2026-11-10 10:12:30",false,"---\nname: implementing-api-abuse-detection-with-rate-limiting\ndescription: Implements API abuse detection using token bucket, sliding window, and\n  fixed window rate-limiting algorithms backed by Redis, including adaptive limits\n  that tighten during detected attacks and relax during normal traffic. Use when\n  defending APIs against DDoS, brute force login attempts, credential stuffing, or\n  scraping abuse and you need to design or tune rate-limiting logic.\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":53,"author":54,"domain":46,"license":15,"version":55,"nist_csf":56,"subdomain":42,"description":7,"mitre_attack":61},[42,31,37,36,35,34,33,32],"mahipal","1.0",[57,58,59,60],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[62,63,64,65,66],"T1190","T1059.007","T1552.001","T1003","T1110","main","54a798831d2266a3ca61ce68a7acb80b81160d57","skills\u002Fimplementing-api-abuse-detection-with-rate-limiting",4395,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills","https:\u002F\u002Fmahipal.engineer\u002FAnthropic-Cybersecurity-Skills\u002F","https:\u002F\u002Fgithub.com\u002Fmukul975","Mahipal.engineer","🔐 Cybersecurity | 💻 Dev | 📷 Street Photographer\r\n🎓 MSc | 📚 Research & AI Security","2026-08-31 12:32:44",{"source":8,"skillName":5,"commands":78,"prompt":88,"zipAvailable":89},[79,82,85],{"tool":80,"command":81},"npx","npx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":83,"command":84},"bunx","bunx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":86,"command":87},"pnpm","pnpm dlx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-abuse-detection-with-rate-limiting","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FSKILL.md",true,[91,96,102],{"path":92,"resourceType":92,"resourceTypeDesc":93,"sizeBytes":94,"sourceHtmlUrl":95},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FLICENSE",{"path":97,"resourceType":98,"resourceTypeDesc":99,"sizeBytes":100,"sourceHtmlUrl":101},"references\u002Fapi-reference.md","REFERENCE","参考文档",2007,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002Freferences\u002Fapi-reference.md",{"path":103,"resourceType":104,"resourceTypeDesc":105,"sizeBytes":106,"sourceHtmlUrl":107},"scripts\u002Fagent.py","SCRIPT","脚本",7070,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002Fscripts\u002Fagent.py",[109,136,160,187,213,240],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":118,"publishedAt":48},"01M6AGDM3HJXTKXX15ZZ0ZVCJ3","verifying-build-provenance-with-slsa-sigstore","Verifies artifact signatures and SLSA provenance using Sigstore's cosign (verify, verify-attestation, verify-blob-attestation) and slsa-verifier (verify-artifact), enforcing keyless OIDC builder identity and source repo against SLSA Build levels. Use in CI\u002FCD before deploying artifacts, when consuming third-party attestations, establishing a SLSA Build L3 pipeline, or confirming provenance during incident response or admission control.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fverifying-build-provenance-with-slsa-sigstore\u002FSKILL.md",[115],{"categoryNo":116,"categoryName":117,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[119,120,121,122,47,46,123,124,45,125,126,127,128,129,130,131,132,133,134,135],"sigstore","provenance","slsa","verifying build provenance with slsa sigstore","incident response","identity","code","artifacts","ci","supply-chain","pipeline","supply-chain-security","t1195","attestation","code-signing","cosign","keyless",{"skillNo":137,"name":138,"nameZh":6,"description":139,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":140,"categories":141,"keywords":143,"publishedAt":48},"01M6AGDGBPWYVZ2F11GFKJ4HZ9","validating-tpm-measured-boot-attestation","Verifies TPM 2.0 measured-boot integrity and remote attestation with tpm2-tools -- reading PCRs (tpm2_pcrread), replaying the boot event log, generating and checking signed quotes (tpm2_quote\u002Ftpm2_checkquote), and sealing secrets to a PCR policy. Use to confirm a system booted trusted firmware\u002Fkernel for Zero Trust device posture, detect boot-chain tampering via PCR drift, or build a golden-value baseline for fleet attestation.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-tpm-measured-boot-attestation\u002FSKILL.md",[142],{"categoryNo":116,"categoryName":117,"taxonomyType":21,"taxonomyTypeDesc":22},[144,132,145,146,47,147,46,45,148,149,150,151,152,153,154,155,156,157,158,159],"boot","TPM","validating tpm measured boot attestation","policy","verification","ZeRO","firmware","Tools","measured-boot","PCR","integrity","secrets","remote-attestation","tpm2-tools","integrity-verification","trusted-computing",{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":170,"publishedAt":48},"01M6AGDCW0Y4FXZ3362GT1941M","validating-backup-integrity-for-recovery","Validates backup integrity through cryptographic hash verification, automated restore testing, corruption detection, and recoverability checks to confirm backups are reliable for disaster recovery and ransomware response. Use before relying on backups for recovery, when building post-backup validation pipelines, auditing backup infrastructure for compliance, or checking immutable\u002Fair-gapped backups for silent corruption or tampering.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-backup-integrity-for-recovery\u002FSKILL.md",[166,169],{"categoryNo":167,"categoryName":168,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":116,"categoryName":117,"taxonomyType":21,"taxonomyTypeDesc":22},[154,171,172,173,174,46,175,176,148,177,178,179,180,181,30,182,183,184,185,186],"backup","recovery","validating backup integrity for recovery","testing","infrastructure","validation","compliance","hash-verification","incident-response","ransomware","cryptocurrency","t1078","t1490","immutable","disaster-recovery","restore-testing",{"skillNo":188,"name":189,"nameZh":6,"description":190,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":191,"categories":192,"keywords":194,"publishedAt":48},"01M6AGD9GBG2KZ336AE763J3WH","triaging-windows-with-kape","Runs KAPE (Kroll Artifact Parser and Extractor) to collect targeted forensic artifacts (registry hives, $MFT, event logs, prefetch, browser data) via Targets and parse them with Modules wrapping Eric Zimmerman's EZ Tools (PECmd, MFTECmd, RECmd). Use during early incident containment\u002Ftriage when full disk imaging is impractical but a defensible, parseable Windows artifact set is needed quickly, including at-scale remote collection.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-windows-with-kape\u002FSKILL.md",[193],{"categoryNo":116,"categoryName":117,"taxonomyType":21,"taxonomyTypeDesc":22},[195,196,197,46,198,199,200,201,202,203,204,205,206,207,208,209,151,210,211,212],"windows","kape","triaging windows with kape","registry","browser","logs","windows-forensics","dfir","mft","mftecmd","data","prefetch","eric-zimmerman","digital-forensics","SET","collection","pecmd","artifact-collection",{"skillNo":214,"name":215,"nameZh":6,"description":216,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":217,"categories":218,"keywords":220,"publishedAt":48},"01M6AGD5PW5J4EVZM958WD74ZQ","triaging-vulnerabilities-with-ssvc-framework","Triages and prioritizes vulnerabilities with CISA's Stakeholder-Specific Vulnerability Categorization (SSVC) decision tree, weighing exploitation status (via the CISA KEV catalog and FIRST EPSS API), technical impact, automatability, and mission prevalence to output Track\u002FTrack*\u002FAttend\u002FAct decisions. Use when prioritizing vulnerability scan results (OpenVAS, Nessus, Qualys) for remediation planning beyond raw CVSS scores.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-vulnerabilities-with-ssvc-framework\u002FSKILL.md",[219],{"categoryNo":116,"categoryName":117,"taxonomyType":21,"taxonomyTypeDesc":22},[221,222,223,46,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239],"vulnerabilities","framework","triaging vulnerabilities with ssvc framework","status","planning","CISA","vulnerability-management","risk-management","nessus","qualys","openvas","cvss","remediation","risk","vulnerability","api","prioritization","ssvc","decision-tree",{"skillNo":241,"name":242,"nameZh":6,"description":243,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":244,"categories":245,"keywords":247,"publishedAt":48},"01M6AGD24TTQQM4CXG69E3B9TJ","triaging-security-incident","Performs initial triage of security incidents using the NIST SP 800-61r3 and SANS PICERL frameworks, classifying incident type, assigning priority by business impact, and routing to the appropriate response team. Use when a SIEM\u002FEDR alert needs human classification, concurrent alerts must be prioritized, or a user report or threat-intel IOC match requires initial incident categorization.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-security-incident\u002FSKILL.md",[246],{"categoryNo":116,"categoryName":117,"taxonomyType":21,"taxonomyTypeDesc":22},[47,248,46,249,250,251,252,253,254,255,256,182,257,183,258,259,260,261,262,263],"triaging security incident","siem","file","ioc","soc","NIST-800-61","NIST","severity","edr","execution","analysis","classification","severity-classification","incident-triage","SANS-PICERL","SOC-operations"]