[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FF1EDJQWGSPDR4QK57PYQP":3,"skill-same:01M7FF1EDJQWGSPDR4QK57PYQP":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":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":50,"repositoryHtmlUrl":51,"repositoryHomepageUrl":6,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M7FF1EDJQWGSPDR4QK57PYQP","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.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FSKILL.md",[],[],"2026-11-16 10:05:34",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":24,"author":33,"domain":34,"license":15,"version":35,"nist_csf":36,"subdomain":25,"description":7,"mitre_attack":41},[25,26,27,28,29,30,31,32],"api-security","rate-limiting","token-bucket","sliding-window","ddos-protection","brute-force-prevention","api-abuse","api-gateway","mahipal","cybersecurity","1.0",[37,38,39,40],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[42,43,44,45,46],"T1190","T1059.007","T1552.001","T1003","T1110","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","07-后端与架构\u002Fimplementing-api-abuse-detection-with-rate-limiting",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":61,"command":62},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":64,"command":65},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill implementing-api-abuse-detection-with-rate-limiting","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FSKILL.md",true,[69],{"path":70,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fapi-reference.md","REFERENCE","参考文档",2007,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002Freferences\u002Fapi-reference.md",[76,84,89,96,103,110],{"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":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":85,"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":86,"categories":87,"keywords":88,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":80,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":80,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"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":80,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":80,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]