[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7A7P35RGWH1SHJNYXRMMXAC":3,"skill-same:01M7A7P35RGWH1SHJNYXRMMXAC":85},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":14,"repositoryHtmlUrl":51,"repositoryHomepageUrl":6,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M7A7P35RGWH1SHJNYXRMMXAC","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.","NeelakshSaxena\u002FVayu","NeelakshSaxena","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F87892838?v=4","01M7A3B9YFS6F6N9DD1787DT86","Neelaksh Saxena","01M7A3B9ZKBT09MNMPX2XN69BY",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FSKILL.md",[],[],"2026-11-15 14:19:17",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":25,"author":34,"domain":35,"license":15,"version":36,"nist_csf":37,"subdomain":26,"description":7,"mitre_attack":42},[26,27,28,29,30,31,32,33],"api-security","rate-limiting","token-bucket","sliding-window","ddos-protection","brute-force-prevention","api-abuse","api-gateway","mahipal","cybersecurity","1.0",[38,39,40,41],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[43,44,45,46,47],"T1190","T1059.007","T1552.001","T1003","T1110","main","7540bbccf0c1ded6156a467b02c95b61ad62413f",".agents\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena","Currently exploring the intersection of tech","2026-09-11 03:02:31",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add NeelakshSaxena\u002FVayu --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":61,"command":62},"bunx","bunx skills add NeelakshSaxena\u002FVayu --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":64,"command":65},"pnpm","pnpm dlx skills add NeelakshSaxena\u002FVayu --skill implementing-api-abuse-detection-with-rate-limiting","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FSKILL.md",true,[69,73,79],{"path":70,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":72,"sourceHtmlUrl":16},"LICENSE","许可证",11255,{"path":74,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":77,"sourceHtmlUrl":78},"references\u002Fapi-reference.md","REFERENCE","参考文档",2007,"https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002Freferences\u002Fapi-reference.md",{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"scripts\u002Fagent.py","SCRIPT","脚本",7070,"https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002Fscripts\u002Fagent.py",[86,93,100,107,114,121],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":20},"01M7ACCCVNCFKMA9X6D15X6G98","runpodctl","Runpod CLI for managing GPU\u002FCPU workloads from the terminal — pods, serverless endpoints, templates, network volumes, Hub deploys, models, SSH, and file transfer (send\u002Freceive). Use for terminal\u002FCI\u002Fscripting, Hub browse\u002Fdeploy, SSH setup, `doctor`, or when the Runpod MCP tools are not connected. For structured tool calls in an MCP-enabled session, prefer runpod-mcp.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpodctl\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":20},"01M7ACC63SRHEA5KMCHSMZK2TC","runpod","Start here for any Runpod task — running GPU\u002FCPU pods, deploying serverless endpoints, templates, network volumes, building images, or understanding how Runpod works. Routes to the right skill (runpod-mcp, runpodctl, flash, companion-clis, runpod-usage, runpod-templates, runpod-migrate) and indexes two dozen live-verified end-to-end examples (golden paths) — use it when the lane is unclear, and for any multi-step or provisioning task even when it is not.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":20},"01M7ACC0Q1C89N9BZBV91CTQTF","runpod-usage","How Runpod works and how to work it — pods vs serverless, GPU\u002FVRAM selection, storage, building a container, networking, plus the agentic pod development loop (provision → ssh-exec → set up → poll readiness) and on-pod install hygiene (uv\u002Fapt). Use to answer \"how does X work\", \"which GPU\", \"how do I build a container\", or \"how do I stand up a workload on a pod\". Guidance, not a tool — execute with runpodctl, runpod-mcp, or flash.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod-usage\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":20},"01M7ACBRPE345GF5GM5B8P8RRC","runpod-templates","Runpod's official prebuilt pod templates (ComfyUI, PyTorch, and others): what each image ships, which ports and paths it uses, how to pick one, how to pin a version, and what is missing on first boot. Use when a task says \"run \u003CX> on a pod\" and an official template already covers it, instead of building an image — and when a user needs help with or wants to fix something about a Runpod template they are already running (won't boot, can't reach the UI, missing models, wrong CUDA line, broken ComfyUI workflow metadata on imported workflows): start here and route onward. Deploy with runpodctl or runpod-mcp; end-to-end walkthroughs live in the runpod router's golden paths.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod-templates\u002FSKILL.md",[],[],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":20},"01M7ACBJATHKVX1TWES2F44GY8","runpod-migrate","Migrate a codebase from the Runpod GraphQL API or REST v1 to REST v2 — inventory which parts use which API version, rewrite the call sites, flag breaking changes, and verify. Use when someone asks to move to v2, asks what v2 would change, or asks which Runpod API their code is on. For managing infrastructure rather than migrating code, use runpod-mcp or runpodctl.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod-migrate\u002FSKILL.md",[],[],{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":20},"01M7ACBC7GHVH6T9YEAPCG2AP8","runpod-mcp","Manage Runpod infrastructure — pods, serverless endpoints, jobs, templates, network volumes, container-registry auth, GPU\u002FCPU catalog, and billing — via the Runpod MCP server's structured tool calls. Use when the Runpod MCP tools (create-pod, list-endpoints, …) are connected in this session, or to connect them (hosted OAuth or local npx). Prefer this over runpodctl for plain infra CRUD when MCP is available; use runpodctl for the terminal, file transfer, or SSH setup.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod-mcp\u002FSKILL.md",[],[]]