implementing-api-abuse-detection-with-rate-limiting
Skill này làm gì
Skill này giúp bảo vệ ứng dụng của bạn khỏi bị quá tải bởi quá nhiều yêu cầu. Nó giới hạn số lần một người dùng truy cập ứng dụng trong một khoảng thời gian nhất định, bằng nhiều phương pháp khác nhau để dịch vụ luôn sẵn sàng cho mọi người.
Khi nào nên dùng
- ✓Khi bạn muốn ngăn ứng dụng bị tấn công bằng quá nhiều yêu cầu (DDoS).
- ✓Khi bạn cần chặn các lần thử đăng nhập liên tục, nhanh chóng (brute force).
- ✓Khi bạn muốn giới hạn số lần ai đó truy cập dữ liệu của bạn (scraping).
Liên kết skill
https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/implementing-api-abuse-detection-with-rate-limiting/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Hãy bảo vệ ứng dụng của tôi khỏi các cuộc tấn công brute force.”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Skill này dùng các kỹ thuật như “token bucket” và “sliding window” để đếm yêu cầu. Nếu quá nhiều yêu cầu đến quá nhanh, nó có thể chặn hoặc làm chậm một số yêu cầu để bảo vệ hệ thống.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
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,
…
Câu hỏi thường gặp
“Rate limiting” là gì?
Đó giống như người gác cửa cho ứng dụng của bạn, kiểm soát số lượng người (yêu cầu) có thể vào trong một khoảng thời gian để tránh quá tải.
“DDoS attacks” là gì?
Đây là các cuộc tấn công cố làm sập một dịch vụ trực tuyến bằng cách gửi một khối lượng yêu cầu khổng lồ, giống như đám đông cùng lúc đổ xô vào một cửa hàng.
Vì sao dùng Redis?
Redis là hệ thống nhanh, giúp đếm yêu cầu từ nhiều người dùng cùng lúc một cách hiệu quả.
Chi tiết
Mô tả gốc của tác giả
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.
Độ phổ biến
- Sao GitHub
- 35k
- Vị trí xếp hạng
- #7985
- Giấy phép
- Apache-2.0
- Cập nhật
- 31/8/2026
Bình luận
- …
Thêm skill từ kho mã này
abusing-dpapi-for-credential-access
35kCung cấp cho agent AI của bạn hướng dẫn có sẵn cho một tác vụ cụ thể, giúp nó làm việc tốt hơn và nhanh hơn.
abusing-shadow-credentials-for-privesc
35kDạy agent AI của bạn viết văn bản rõ ràng và có cấu trúc tốt.
achieving-cmmc-level-2-compliance
35kGiúp agent của bạn chuẩn bị môi trường để tuân thủ CMMC Level 2. Triển khai các yêu cầu bảo mật và quản lý tài liệu cần thiết.
acquiring-disk-image-with-dd-and-dcfldd
35kGiúp agent của bạn tạo bản sao chính xác của ổ đĩa. Cách này đảm bảo không mất hay thay đổi thông tin trong quá trình điều tra.
Skill tương tự
api-connector-builder
280kGiúp agent của bạn xây dựng kết nối API mới theo đúng mẫu đã có, dùng khi bạn cần thêm một tích hợp mà không tạo cách làm mới.
api-design
280kGiúp agent của bạn thiết kế REST API theo các thực hành tốt nhất, hữu ích để định nghĩa cách API giao tiếp, hiển thị lỗi và tổ chức dữ liệu.
backend-patterns
280kGiúp agent của bạn với các mẫu kiến trúc phía máy chủ và tối ưu cơ sở dữ liệu, hữu ích khi xây dựng hoặc rà soát code chạy trên máy chủ.