Throttling giới hạn số request mỗi user/IP trong một khoảng thời gian — để chặn abuse, spam, brute-force login.
DRF có 3 class sẵn: AnonRateThrottle (theo IP, user chưa login), UserRateThrottle (theo user đã login), và ScopedRateThrottle (mỗi endpoint một scope riêng).
# settings.py
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'anon': '30/min',
'user': '200/min',
'login': '5/min', # cho ScopedRateThrottle
},
}
# views.py
class LoginView(APIView):
throttle_classes = [ScopedRateThrottle]
throttle_scope = 'login'Counter lưu ở Django cache (LocMem cho dev, Redis cho prod). Hệ thống nhiều process thì bắt buộc Redis/Memcached — LocMem không share counter giữa worker, throttling sẽ vô tác dụng.
Throttling DRF chỉ là tầng application-level cho UX gọn (response 429 + header Retry-After). Còn DDoS thực sự phải chống ở nginx/CloudFront/WAF, không thể dựa vào DRF. Và đừng đặt rate quá thấp cho anon mà chắn cả crawler hợp lệ (Googlebot) — phải có exception qua User-Agent header hoặc IP allowlist.