Performance: Throttling for rate limiting
MEDIUM IMPACT
Throttling controls how often users can send requests, impacting server response time and page load speed under heavy traffic.
from rest_framework.throttling import UserRateThrottle class CustomRateThrottle(UserRateThrottle): rate = '10/minute' # In settings.py REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ['path.to.CustomRateThrottle'], 'DEFAULT_THROTTLE_RATES': {'user': '10/minute'}, } # Uses cache backend for counting with expiration and async support
from django.utils.decorators import decorator_from_middleware class SimpleThrottleMiddleware: def __init__(self, get_response): self.get_response = get_response self.requests = {} def __call__(self, request): user_ip = request.META.get('REMOTE_ADDR') count = self.requests.get(user_ip, 0) if count >= 10: from django.http import HttpResponseTooManyRequests return HttpResponseTooManyRequests('Too many requests') self.requests[user_ip] = count + 1 return self.get_response(request) # Middleware stores counts in memory without expiration or persistence
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| In-memory synchronous throttling | N/A | N/A | Increases server response delay | [X] Bad |
| Cache-backed async throttling (DRF) | N/A | N/A | Minimal server delay, faster response | [OK] Good |