-
Notifications
You must be signed in to change notification settings - Fork 5
Open
Description
🛡️ RATE LIMITING PROTECTION
Priority: HIGH - API Protection
Problem
No rate limiting protection against API abuse, DDoS attacks, or resource exhaustion.
Solution
Implement Redis-based rate limiting middleware with configurable limits per endpoint and client.
Rate Limiting Middleware
# app/middleware/rate_limit.py
from fastapi import Request, HTTPException
import redis
import asyncio
from typing import Dict, Optional
class RateLimiter:
def __init__(self, redis_client: redis.Redis):
self.redis = redis_client
async def check_rate_limit(
self,
key: str,
limit: int,
window: int,
burst: int = None
) -> bool:
"""
Check if request is within rate limits
key: unique identifier (IP, user ID, API key)
limit: requests per window
window: time window in seconds
burst: allowed burst requests
"""
current = self.redis.get(key)
if current is None:
self.redis.setex(key, window, 1)
return True
current_count = int(current)
if current_count >= limit:
return False
self.redis.incr(key)
return True
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
client_ip = get_client_ip(request)
endpoint = request.url.path
# Different limits for different endpoints
limits = {
"/api/analyze": (10, 60), # 10 requests per minute
"/api/auth": (5, 300), # 5 requests per 5 minutes
"default": (60, 60) # 60 requests per minute
}
limit, window = limits.get(endpoint, limits["default"])
if not await rate_limiter.check_rate_limit(
f"rate_limit:{client_ip}:{endpoint}",
limit,
window
):
raise HTTPException(
status_code=429,
detail="Rate limit exceeded"
)
return await call_next(request)Implementation Steps
- Setup Redis for rate limiting
- Implement rate limiting middleware
- Configure endpoint-specific limits
- Add burst protection
- Implement whitelist/blacklist
- Add monitoring and alerting
Acceptance Criteria
- Rate limiting active on all endpoints
- Configurable limits per endpoint
- Redis-based distributed rate limiting
- Proper HTTP 429 responses
- Rate limit monitoring dashboard
Effort: Low (1-2 days)