본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)35k · #7985

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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/implementing-api-abuse-detection-with-rate-limiting/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

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.

repo: mukul975/Anthropic-Cybersecurity-Skills

인기도

GitHub 스타
35k
순위
#7985
라이선스
Apache-2.0
업데이트
2026. 8. 31.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬