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.
Throttling limits how many requests a user/IP can make in a window — to block abuse, spam, and brute-force login.
DRF provides three classes out of the box: AnonRateThrottle (IP-based for unauthenticated), UserRateThrottle (per-user), ScopedRateThrottle (per-endpoint scope).
# 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', # for ScopedRateThrottle
},
}
# views.py
class LoginView(APIView):
throttle_classes = [ScopedRateThrottle]
throttle_scope = 'login'The default backend stores counters in Django's cache (LocMem in dev, Redis in prod). Multiple processes → Redis/Memcached is mandatory; LocMem does not share counters across workers.
Pitfall: DRF throttling is application-level — it gives clear UX (429 response + Retry-After header). Real DDoS defense belongs at nginx/CloudFront/WAF, not DRF. Also do not set anon too low and block legitimate crawlers (Googlebot) — leave an exception via header or IP allowlist.