[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7B6YSNT2D61NA8Z7C7M1VD4":3,"skill-same:01M7B6YSNT2D61NA8Z7C7M1VD4":83},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":15,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":13,"repositoryHtmlUrl":50,"repositoryHomepageUrl":6,"ownerHtmlUrl":51,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":52,"install":53,"resources":66},"01M7B6YSNT2D61NA8Z7C7M1VD4","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.","vikasvardhanv\u002Fjerry_skills","vikasvardhanv","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99010657?v=4","01M7B2B0VN78W7529RQX5BR6DZ","01M7B2B0WDNTXJHRK3QNPNWRP6",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\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":24,"author":33,"domain":34,"license":14,"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","1eb986d0b0ecc180291597e08eb5a58288843536","skills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv","2026-08-25 13:16:33",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add vikasvardhanv\u002Fjerry_skills --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":59,"command":60},"bunx","bunx skills add vikasvardhanv\u002Fjerry_skills --skill implementing-api-abuse-detection-with-rate-limiting",{"tool":62,"command":63},"pnpm","pnpm dlx skills add vikasvardhanv\u002Fjerry_skills --skill implementing-api-abuse-detection-with-rate-limiting","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002FSKILL.md",true,[67,71,77],{"path":68,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":15},"LICENSE","许可证",11255,{"path":72,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":76},"references\u002Fapi-reference.md","REFERENCE","参考文档",2007,"https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002Freferences\u002Fapi-reference.md",{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"scripts\u002Fagent.py","SCRIPT","脚本",7070,"https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-abuse-detection-with-rate-limiting\u002Fscripts\u002Fagent.py",[84,92,99,106,113,120],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7BESR1CJ3H5SP9XM8KYJZ9W","syllabus","Generates a curated supplementary reading list from any course syllabus using Consensus academic search. Grill-me intake (syllabus input format + course audience + year range) plus a grouping forcing-options checkpoint before any search runs — so the reading list matches the course's level and recency need. Parses the syllabus to extract topics and learning outcomes, searches Consensus for recent peer-reviewed papers per topic, and produces a professionally formatted .docx with clickable Consensus links, plain-language summaries calibrated to audience level, and Bloom-higher-order discussion questions tied to course learning goals. Use when the user uploads a syllabus, course outline, or curriculum document and wants supplementary readings (e.g., 'create a reading list from this syllabus', 'find recent papers for my course') — even casual mentions with a syllabus attached should trigger this skill.","MIT","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fsyllabus\u002Fskills\u002Fsyllabus\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M7BES1YA6R97W7QPMFFM1PED","pulse","Multi-source recency research skill that takes the pulse of any topic across Reddit, Hacker News, the open web, and optionally X\u002FTwitter within a configurable recent window (default 30 days). Forcing intake clarifies topic specificity, angle (trend\u002Fsentiment\u002Fproblems\u002Fopportunities\u002Fcomparison), time window, and platform scope before searching. Returns a synthesized briefing with citations, engagement metrics, and cross-platform pattern analysis. Use when the user requests multi-source recency intelligence on a topic (e.g., 'pulse on [topic]', 'what's happening with [topic]', 'what are people saying about [topic]', 'current conversation about [topic]', 'take the pulse of [topic]', 'trending: [topic]', 'find me info on [topic]'), and for competitor research, trend discovery, tool comparisons, and audience sentiment analysis.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fpulse\u002Fskills\u002Fpulse\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M7BERNHYGY035AR00VRT03KE","patent","Patent prior-art and landscape intelligence skill — not generic patent help. Commits to one of five sub-use-cases via forcing intake (novelty search \u002F freedom-to-operate \u002F competitive landscape \u002F acquisition diligence \u002F litigation prior-art) before any search runs. Searches Google Patents, Espacenet, USPTO, and optionally Lens.org for citation-graph signals. Output is an editable Word document (.docx) with verdict, ranked closest art (claim-text extracted), CPC-class-aware landscape, family-resolved hits, geographic coverage, FTO flags where applicable, strategy recommendations, and full audit log. Use when the user asks for patent searching or analysis (e.g., 'prior art search for [invention]', 'freedom to operate analysis for [product]'). Produces search signal, not legal advice — always recommends consulting a patent attorney before filing or licensing decisions. Trademark, copyright, and trade-secret questions are out of scope.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fpatent\u002Fskills\u002Fpatent\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M7BERCK1EAKTWW7R436WAR0J","notebooklm","Browser automation skill for controlling Google's NotebookLM. Use when the user wants anything done in NotebookLM (e.g., 'open NotebookLM', 'check my [name] notebook', 'ask my notebook about X', 'add [source] to NotebookLM', 'generate a Video Overview from my notebook', 'use NotebookLM Studio'). Handles reading and querying notebooks, adding sources (URLs, text, files, YouTube links, synthesized content), generating Studio outputs (Audio\u002FVideo Overviews, Mind Maps, Reports incl. Briefing Doc\u002FStudy Guide\u002FFAQ, Flashcards, Quiz, slide decks, infographics — discover the exact set from the live Studio panel; the UI evolves fast), and creating new notebooks. Requires browser automation environment — fails gracefully when unavailable.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fnotebooklm\u002Fskills\u002Fnotebooklm\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":19},"01M7BEQZAZAQRTXFJRY7RHV3TY","litreview","Academic literature orientation skill that searches papers via free keyless APIs (PubMed E-utilities + OpenAlex) by default — with the Consensus MCP as an optional enhancement lane when connected — builds a strategic search plan using PICO (default) or SPIDER \u002F Decomposition \u002F hybrid as fallbacks, and synthesizes findings into a formatted Word (.docx) research guide. Grill-me intake (research question specificity + framework hint + tentative depth) before the recon search; a second forcing checkpoint after Phase 2 confirms framework + sub-areas + depth before searches consume budget. Configurable depth (5\u002F10\u002F20 queries) controls coverage vs. speed. Output is a 'launching pad' — an orientation guide that lets a researcher dive in confidently, not a finished review. Use when the user starts literature-oriented research (e.g., 'litreview on [topic]', 'literature review on [topic]', 'I'm starting a literature review on X', 'I'm writing a paper on X', 'help me research X', 'I'm doing research on X', 'can you help me research X'). Do NOT use for single one-off paper searches wanting a quick list — that's a plain PubMed\u002FOpenAlex (or Consensus) query.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Flitreview\u002Fskills\u002Flitreview\u002FSKILL.md",[],[],{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":19},"01M7BEQKJ45K31QK5VRAQSVJCJ","grants","NIH grant research skill for clinical researchers. Grill-me intake (research idea + career stage + preliminary data + environment + submission posture + known institute targets) locks down the funding strategy before any search runs. Runs a 5-facet Consensus positioning analysis (with draft Significance\u002FInnovation language), maps the research to the right NIH institutes and study sections via RePORTER, finds NOSIs and funded overlap, and produces an editable Word document (.docx) with budget\u002Fscope-aware mechanism recommendations, submission timelines, and a mandatory program officer recommendation. Use when the user asks about research funding or makes any grant-related request (e.g., 'grants for [topic]', 'find grants for my research idea', 'what grants match my research', 'help me find NIH funding', 'grant opportunities for my research'). NIH-only scope — non-NIH funders (PCORI, DOD CDMRP, VA, foundations) are out of scope and flagged at intake.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fgrants\u002Fskills\u002Fgrants\u002FSKILL.md",[],[]]