implementing-api-rate-limiting-and-throttling
Skill này làm gì
Công cụ này giúp kiểm soát số lần một người dùng có thể truy cập một phần của hệ thống (API) trong một khoảng thời gian nhất định. Điều này ngăn hệ thống bị quá tải hoặc bị lạm dụng.
Khi nào nên dùng
- ✓Bảo vệ đăng nhập khỏi các cuộc tấn công brute-force.
- ✓Ngăn bot gửi quá nhiều yêu cầu trong thời gian ngắn.
- ✓Đảm bảo mọi người dùng đều được truy cập tài nguyên một cách công bằng.
Liên kết skill
https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/implementing-api-rate-limiting-and-throttling/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
“Đặt giới hạn 100 yêu cầu mỗi phút cho người dùng thường và 10 yêu cầu mỗi phút cho người dùng miễn phí trên API tìm kiếm.”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Công cụ hoạt động bằng cách đặt quy tắc về số lượng yêu cầu được phép. Nếu ai đó cố gửi nhiều yêu cầu hơn mức cho phép, hệ thống sẽ yêu cầu họ chờ một chút trước khi thử lại.
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 Rate Limiting and Throttling
When to Use
- Protecting authentication endpoints against brute force and credential stuffing attacks
- Preventing API abuse and resource exhaustion from automated scripts and bots
- Implementing fair usage quotas for different API consumer tiers (free, premium, enterprise)
- Defending against denial-of-service attacks at the application layer
- Meeting compliance requirements that mandate API abuse prevention controls
Do not use rate limiting as the sole defense against attacks. Combine with authentication, authorization, and WAF rules.
Prerequisites
- Redis 6.0+ for distributed rate limit counters (or in-memory for single-instance deployments)
- API framework (Express.js, FastAPI, Spring Boot, or Django REST Framework)
- Monitoring system for rate limit metrics (Prometheus, CloudWatch, Datadog)
- Understanding of the API's normal traffic patterns and peak usage
- Load testing tool (k6, Gatling, or Locust) for validating rate limit behavior
Workflow
Step 1: Rate Limiting Strategy Design
Define rate limits per endpoint category and user tier:
# Rate limit configuration
RATE_LIMITS = {
# Authentication endpoints (most restrictive)
"auth": {
"login": {"requests": 5, "window_seconds": 60, "by": "ip"},
"register": {"requests": 3, "window_seconds": 300, "by": "ip"},
"forgot_password": {"requests": 3, "window_seconds": 3600, "by": "ip"},
"verify_mfa": {"requests": 5, "window_seconds": 300, "by": "user"},
},
# Standard API endpoints
"api": {
"free": {"requests": 60, "window_seconds": 60, "by": "user"},
"premium": {"requests": 300, "window_seconds": 60, "by": "user"},
"enterprise": {"requests": 1000, "window_seconds": 60, "by": "user"},
},
# Resource-intensive endpoints
"expensive": {
"search": {"requests": 10, "window_seconds": 60, "by": "user"},
"export": {"requests": 5, "window_seconds": 3600, "by": "user"},
"bulk_import": {"requests": 2, "window_seconds": 3600, "by": "user"},
},
# Global limits
"global": {
"per_ip": {"requests": 1000, "window_seconds": 60, "by": "ip"},
"per_user": {"requests": 5000, "window_seconds": 3600, "by": "user"},
},
}
Step 2: Sliding Window Rate Limiter (Redis)
import redis
import time
import hashlib
from functools import wraps
from flask import Flask, request, jsonify, g
app = Flask(__name__)
redis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
class SlidingWindowRateLimiter:
"""Sliding window rate limiter using Redis sorted sets."""
def __init__(self, redis_conn):
self.redis = redis_conn
def is_allowed(self, key, max_requests, window_seconds):
"""Check if request is allowed and record it."""
now = time.time()
window_start = now - window_seconds
pipe = self.redis.pipeline()
# Remove expired entries
pipe.zremrangebyscore(key, 0, window_start)
# Count requests in current window
pipe.zcard(key)
# Add current request
pipe.zadd(key, {f"{now}:{hashlib.md5(str(now).encode()).hexdigest()[:8]}": now})
# Set TTL on the key
pipe.expire(key, window_seconds + 1)
results = pipe.execute()
current_count = results[1]
if current_count >= max_requests:
# Calculate retry-after
oldest = self.redis.zrange(key, 0, 0, withscores=True)
if oldest:
retry_after = int(oldest[0][1] + window_seconds - now) + 1
else:
retry_after = window_seconds
return False, current_count, max_requests, retry_after
return True, current_count + 1, max_requests, 0
rate_limiter = SlidingWindowRateLimiter(redis_client)
def rate_limit(max_requests, window_seconds, key_func=None):
"""Decorator for rate limiting API endpoints."""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
# Determine the rate limit key
if key_func:
identifier = key_func()
elif hasattr(g, 'user_id'):
identifier = f"user:{g.user_id}"
else:
identifier = f"ip:{request.remote_addr}"
key = f"ratelimit:{request.endpoint}:{identifier}"
allowed, current, limit, retry_after = rate_limiter.is_allowed(
…
Câu hỏi thường gặp
“Rate limiting” là gì?
“Rate limiting” là việc kiểm soát tốc độ yêu cầu mà người dùng có thể gửi tới một dịch vụ trong một khoảng thời gian nhất định.
“Throttling” là gì?
“Throttling” là hành động giảm hoặc giới hạn tốc độ yêu cầu khi đã đạt đến ngưỡng.
Vì sao cần giới hạn yêu cầu?
Để bảo vệ hệ thống khỏi quá tải và tấn công, đồng thời đảm bảo mọi người dùng đều được sử dụng công bằng.
Chi tiết
Mô tả gốc của tác giả
Implements API rate limiting and throttling with token bucket, sliding window, and fixed window algorithms, configuring per-user, per-IP, and per-endpoint limits via Redis-backed counters, API gateway plugins, or middleware, and returning proper HTTP 429 responses with Retry-After headers. Use when setting up request quota management or preventing brute force, credential stuffing, and resource exh
Độ phổ biến
- Sao GitHub
- 35k
- Vị trí xếp hạng
- #7988
- 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ủ.