implementing-api-abuse-detection-with-rate-limiting
하는 일
이 스킬은 앱이 너무 많은 요청으로 과부하되지 않도록 돕습니다. 정해진 시간 안에 사용자가 앱에 접근하는 횟수를 제한하며, 서비스가 모두에게 계속 제공되도록 여러 방법을 사용합니다.
사용하는 경우
- ✓앱이 너무 많은 요청(DDoS)으로 공격받는 것을 막고 싶을 때.
- ✓짧은 시간에 반복되는 빠른 로그인 시도(무차별 대입)를 막아야 할 때.
- ✓데이터를 얼마나 자주 가져갈 수 있는지(스크래핑) 제한하고 싶은 경우.
스킬 링크
https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/implementing-api-abuse-detection-with-rate-limiting/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“무차별 대입 공격으로부터 제 애플리케이션을 보호해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
이 스킬은 ‘토큰 버킷’과 ‘슬라이딩 윈도우’ 같은 기법으로 요청 수를 셉니다. 너무 많은 요청이 짧은 시간에 들어오면 일부를 차단하거나 속도를 늦춰 시스템을 보호합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
Implementing API Abuse Detection with Rate Limiting
Overview
API 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.
When to Use
- When deploying or configuring implementing api abuse detection with rate limiting capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- API gateway (Kong, AWS API Gateway, Apigee) or reverse proxy (NGINX, Envoy)
- Redis or Memcached for distributed rate limit counters
- Monitoring and alerting infrastructure (Prometheus, Grafana, or SIEM)
- Understanding of normal API traffic patterns and baselines
- Python 3.8+ or Node.js for custom implementation
Rate Limiting Algorithms
Token Bucket Algorithm
The 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.
"""Token Bucket Rate Limiter with Redis Backend
Implements a distributed token bucket algorithm for API rate limiting
with burst allowance and automatic refill.
"""
import time
import redis
import json
from typing import Tuple
class TokenBucketRateLimiter:
def __init__(self, redis_client: redis.Redis,
max_tokens: int = 100,
refill_rate: float = 10.0,
key_prefix: str = "ratelimit:tb"):
self.redis = redis_client
self.max_tokens = max_tokens
self.refill_rate = refill_rate # tokens per second
self.key_prefix = key_prefix
def _get_key(self, client_id: str) -> str:
return f"{self.key_prefix}:{client_id}"
def allow_request(self, client_id: str, tokens_required: int = 1) -> Tuple[bool, dict]:
"""Check if a request should be allowed under the rate limit.
Returns (allowed, info) where info contains remaining tokens
and retry-after seconds.
"""
key = self._get_key(client_id)
now = time.time()
# Atomic token bucket operation using Lua script
lua_script = """
local key = KEYS[1]
local max_tokens = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])
local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
local tokens = tonumber(bucket[1])
local last_refill = tonumber(bucket[2])
-- Initialize bucket if it doesn't exist
if tokens == nil then
tokens = max_tokens
last_refill = now
end
-- Calculate refilled tokens
local elapsed = now - last_refill
local refilled = elapsed * refill_rate
tokens = math.min(max_tokens, tokens + refilled)
-- Check if enough tokens available
local allowed = 0
if tokens >= requested then
tokens = tokens - requested
allowed = 1
end
-- Update bucket state
redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)
redis.call('EXPIRE', key, 3600) -- TTL for cleanup
-- Calculate retry-after if denied
local retry_after = 0
if allowed == 0 then
retry_after = math.ceil((requested - tokens) / refill_rate)
end
return {allowed, math.floor(tokens), retry_after}
"""
result = self.redis.eval(
lua_script, 1, key,
self.max_tokens, self.refill_rate, now, tokens_required
)
allowed = bool(result[0])
remaining = int(result[1])
retry_after = int(result[2])
return allowed, {
"remaining": remaining,
…
자주 묻는 질문
‘속도 제한(rate limiting)’이란 무엇인가요?
특정 시간 안에 얼마나 많은 사람(요청)이 들어올 수 있는지 조절해 과밀을 막는 애플리케이션의 문지기와 같습니다.
‘DDoS 공격’이란 무엇인가요?
많은 가게에 한꺼번에 사람이 몰리듯, 엄청난 양의 요청을 보내 온라인 서비스를 마비시키려는 공격입니다.
왜 Redis를 사용하나요?
Redis는 여러 사용자의 요청을 동시에 빠르고 효율적으로 세는 데 도움을 주는 빠른 시스템입니다.
상세 정보
작성자의 원본 설명
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.
인기도
- GitHub 스타
- 35k
- 순위
- #7985
- 라이선스
- Apache-2.0
- 업데이트
- 2026. 8. 31.
댓글
- …
이 저장소의 다른 스킬
abusing-dpapi-for-credential-access
35kAI 에이전트에게 특정 작업을 위한 준비된 지침을 제공해, 더 잘하고 더 빠르게 처리하도록 합니다.
abusing-shadow-credentials-for-privesc
35kAI 에이전트가 명확하고 잘 구성된 텍스트를 쓰도록 가르칩니다.
achieving-cmmc-level-2-compliance
35kCMMC Level 2 규정 준수를 위한 환경을 준비하도록 돕습니다. 보안 요구 사항을 구현하고 필요한 문서를 관리합니다.
acquiring-disk-image-with-dd-and-dcfldd
35k에이전트가 하드 드라이브의 정확한 복사본을 만들도록 돕습니다. 조사 중 정보가 손실되거나 변경되지 않도록 하는 데 유용합니다.
비슷한 스킬
api-connector-builder
280k에이전트가 기존 패턴을 따라 새로운 API 연결을 만들도록 합니다. 새로운 방식을 도입하지 않고 연동을 하나 더 추가할 때 씁니다.
api-design
280k에이전트가 모범 사례에 따라 REST API를 설계하도록 돕습니다. API가 통신하는 방식, 오류를 보여 주는 방식, 데이터를 정리하는 방식을 정하는 데 유용합니다.
backend-patterns
280k에이전트가 서버 쪽 아키텍처 패턴과 데이터베이스 최적화를 다루도록 돕습니다. 서버에서 실행되는 코드를 만들거나 검토할 때 유용합니다.