Throttling
El throttling limita la cantidad de requests que un cliente puede hacer en un período de tiempo. Es esencial para evitar abusos, proteger recursos del servidor, y garantizar que la API se mantenga respondiendo para todos los usuarios.
Throttling global
Aplica el mismo límite a todas las vistas. Ideal para reglas generales:
# settings.py
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '20/minute',
'user': '100/minute',
},
}
Throttling por vista
Cuando se necesitan límites diferentes por endpoint:
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from rest_framework.generics import ListAPIView
class SearchView(ListAPIView):
"""Endpoint de búsqueda con throttling más restrictivo."""
throttle_classes = [AnonRateThrottle, UserRateThrottle]
throttle_scope = 'search' # scope opcional personalizado
Custom Throttle
Para reglas de negocio específicas:
from rest_framework.throttling import SimpleRateThrottle
class BurstRateThrottle(SimpleRateThrottle):
"""
Límite estricto para ráfagas de requests.
Útil para endpoints costosos (reportes, exportaciones).
"""
scope = 'burst'
def get_cache_key(self, request, view):
ident = request.user.pk if request.user else self.get_ident(request)
return self.cache_format % {
'scope': self.scope,
'ident': ident
}
def get_rate(self):
return '5/minute'
Throttling por acción en ViewSet
from rest_framework.viewsets import ModelViewSet
class PostViewSet(ModelViewSet):
def get_throttles(self):
if self.action == 'create':
return [BurstRateThrottle()] # Crear posts es más restrictivo
return [UserRateThrottle()]
Estrategias recomendadas
| Tipo | Rate sugerido | Para qué |
|---|---|---|
Anónimos (anon) |
20/min | Evitar scraping y ataques básicos |
Usuarios autenticados (user) |
100/min | Uso normal de la API |
| Login / Register | 5/min | Prevenir brute force |
| Endpoints pesados (burst) | 5/min | Exportaciones, reportes, búsquedas complejas |
Siempre tener un throttle para anónimos. Son los que más abusan. Los custom throttles con scopes descriptivos (
burst,search,login) dan control granular sin complicar el código.
Cómo probarlo
Si excedés el límite, DRF devuelve automáticamente un 429 Too Many Requests:
{
"detail": "Solicitud rechazada por límite de tasa."
}