197 lines
5.9 KiB
Markdown
197 lines
5.9 KiB
Markdown
# Subtask: Rate Limiting Implementation
|
|
|
|
**Parent Task**: Decomp/001
|
|
**Subtask ID**: Decomp/001-10
|
|
**Dependencies**: Decomp/001-09 (Redis Cache) - uses Redis for distributed rate limiting
|
|
|
|
## Description
|
|
Implement rate limiting to prevent abuse of the URL shortening service. Support different limits for different actions (create vs. redirect).
|
|
|
|
## Requirements
|
|
- Rate limit URL creation (10 per minute per IP)
|
|
- Rate limit redirects (100 per second per IP)
|
|
- Support API key-based rate limiting (higher limits)
|
|
- Distributed (works across multiple instances)
|
|
- Sliding window algorithm
|
|
- Return proper HTTP headers (X-RateLimit-*)
|
|
|
|
## Technical Specifications
|
|
|
|
### Rate Limiting Configuration
|
|
|
|
```python
|
|
from dataclasses import dataclass
|
|
from enum import Enum
|
|
|
|
class Action(Enum):
|
|
CREATE = "create"
|
|
REDIRECT = "redirect"
|
|
|
|
@dataclass
|
|
class RateLimit:
|
|
requests: int
|
|
window: int # seconds
|
|
|
|
RATE_LIMITS = {
|
|
Action.CREATE: RateLimit(requests=10, window=60), # 10/min
|
|
Action.REDIRECT: RateLimit(requests=100, window=1), # 100/sec
|
|
}
|
|
|
|
API_KEY_LIMITS = {
|
|
Action.CREATE: RateLimit(requests=100, window=60), # 100/min
|
|
Action.REDIRECT: RateLimit(requests=1000, window=1), # 1000/sec
|
|
}
|
|
```
|
|
|
|
### Sliding Window Implementation
|
|
|
|
```python
|
|
class RateLimiter:
|
|
def __init__(self, redis: redis.Redis):
|
|
self.redis = redis
|
|
|
|
async def check_rate_limit(
|
|
self,
|
|
identifier: str, # IP address or API key
|
|
action: Action,
|
|
api_key: str = None
|
|
) -> tuple[bool, dict]:
|
|
"""
|
|
Check if request is within rate limit.
|
|
Returns (allowed, rate_limit_info)
|
|
"""
|
|
|
|
# Get limits
|
|
limits = API_KEY_LIMITS if api_key else RATE_LIMITS
|
|
limit = limits[action]
|
|
|
|
# Sliding window key
|
|
key = f"ratelimit:{action.value}:{identifier}"
|
|
now = time.time()
|
|
window_start = now - limit.window
|
|
|
|
# Clean up old entries and count current window
|
|
pipe = self.redis.pipeline()
|
|
pipe.zremrangebyscore(key, 0, window_start)
|
|
pipe.zcard(key)
|
|
pipe.zadd(key, {str(now): now})
|
|
pipe.expire(key, limit.window)
|
|
results = await pipe.execute()
|
|
|
|
current_count = results[1]
|
|
remaining = max(0, limit.requests - current_count - 1)
|
|
reset_at = now + limit.window
|
|
|
|
allowed = current_count < limit.requests
|
|
|
|
return allowed, {
|
|
"limit": limit.requests,
|
|
"remaining": remaining,
|
|
"reset": int(reset_at)
|
|
}
|
|
|
|
async def is_allowed(self, identifier: str, action: Action, api_key: str = None) -> bool:
|
|
"""Simple check without returning info."""
|
|
allowed, _ = await self.check_rate_limit(identifier, action, api_key)
|
|
return allowed
|
|
```
|
|
|
|
### Middleware Integration
|
|
|
|
```python
|
|
from fastapi import Request, HTTPException
|
|
from fastapi.responses import JSONResponse
|
|
|
|
async def rate_limit_middleware(request: Request, call_next):
|
|
"""Rate limiting middleware."""
|
|
|
|
# Extract identifier
|
|
api_key = request.headers.get("X-API-Key")
|
|
identifier = api_key or request.client.host
|
|
|
|
# Determine action based on path
|
|
if request.url.path == "/api/v1/shorten" and request.method == "POST":
|
|
action = Action.CREATE
|
|
elif request.url.path.startswith("/api/v1/"):
|
|
action = Action.REDIRECT # Analytics, stats, etc.
|
|
else:
|
|
# Redirect paths (/{short_code}) - no rate limiting
|
|
return await call_next(request)
|
|
|
|
# Check rate limit
|
|
limiter = request.app.state.rate_limiter
|
|
allowed, info = await limiter.check_rate_limit(identifier, action, api_key)
|
|
|
|
# Add rate limit headers
|
|
headers = {
|
|
"X-RateLimit-Limit": str(info["limit"]),
|
|
"X-RateLimit-Remaining": str(info["remaining"]),
|
|
"X-RateLimit-Reset": str(info["reset"])
|
|
}
|
|
|
|
if not allowed:
|
|
return JSONResponse(
|
|
status_code=429,
|
|
content={"error": "Rate limit exceeded", "retry_after": info["reset"]},
|
|
headers=headers
|
|
)
|
|
|
|
response = await call_next(request)
|
|
response.headers.update(headers)
|
|
return response
|
|
```
|
|
|
|
### Request Extraction Helper
|
|
|
|
```python
|
|
def extract_identifier(request: Request) -> tuple[str, str | None]:
|
|
"""
|
|
Extract rate limit identifier from request.
|
|
Returns (identifier, api_key)
|
|
"""
|
|
# Check for API key first
|
|
api_key = request.headers.get("X-API-Key")
|
|
if api_key:
|
|
return api_key, api_key
|
|
|
|
# Fall back to IP address
|
|
# Check for forwarded headers (behind proxy)
|
|
forwarded_for = request.headers.get("X-Forwarded-For")
|
|
if forwarded_for:
|
|
return forwarded_for.split(",")[0].strip(), None
|
|
|
|
return request.client.host, None
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
- [ ] RateLimiter class with sliding window algorithm
|
|
- [ ] CREATE action limited to 10/min per IP (100/min with API key)
|
|
- [ ] REDIRECT action limited to 100/sec per IP (1000/sec with API key)
|
|
- [ ] X-RateLimit-* headers returned on all responses
|
|
- [ ] 429 status code when limit exceeded
|
|
- [ ] Works across multiple instances (Redis-backed)
|
|
- [ ] Unit tests for rate limit logic
|
|
|
|
## Notes
|
|
- **Why sliding window**: More accurate than fixed window, simpler than token bucket
|
|
- **Why Redis sorted sets**: Efficient for time-series data, ZREM range for cleanup
|
|
- **API key support**: Allows premium users higher limits
|
|
- **Trade-off**: Exact vs. approximate (sliding window is exact but more expensive)
|
|
|
|
## Edge Cases
|
|
- Clock skew → use Redis time, not client time
|
|
- Distributed systems → Redis provides single source of truth
|
|
- Burst traffic → sliding window handles better than fixed window
|
|
- API key leaking → consider adding HMAC signature
|
|
|
|
## Alternative Algorithms
|
|
- **Token Bucket**: Allows burst, more complex
|
|
- **Fixed Window**: Simpler but allows double requests at boundary
|
|
- **Leaky Bucket**: Smooths traffic, harder to implement
|
|
|
|
## Monitoring
|
|
- Rate limit hit rate (percentage of requests limited)
|
|
- API key usage distribution
|
|
- Top offenders by IP
|
|
- Redis sorted set size
|