Rate Limiting & Throttling
DRF Throttling: AnonRate, UserRate, and Scoped Throttles
Unrestricted APIs are vulnerable to brute-force attacks, scraping, and Denial of Service (DoS) outages. Throttling (Rate Limiting) restricts the number of requests a client can issue within a given time window. Django REST Framework includes a robust, cache-backed throttling engine supporting anonymous rate limits, authenticated user tiers, and scoped endpoint limits.
1. How Throttling Operates in DRF
DRF tracks request counts in Django's cache backend (typically Redis or Memcached). On every incoming request:
- 1DRF identifies the client: by IP address for anonymous users, or by
user_idfor authenticated users. - 2It checks request history in the cache against the configured rate.
- 3If the threshold is exceeded, DRF raises
Throttled, returning HTTP 429 Too Many Requests with aRetry-Afterheader.
2. Built-in Throttle Classes
AnonRateThrottle: Limits unauthenticated users based on their IP address (REMOTE_ADDRorX-Forwarded-For).UserRateThrottle: Limits authenticated users based on their uniqueuser.pk.ScopedRateThrottle: Applies custom limits to specific sensitive views via athrottle_scopeattribute (e.g. login, checkout, password reset).
3. Global Configuration in settings.py
Allowed rate time periods: second, minute, hour, day (e.g. "100/day", "5/sec").
4. Applying ScopedRateThrottle to Sensitive Endpoints
Guarding authentication endpoints against credential stuffing and brute-force attacks:
5. Tiered Subscription Rate Limiting (SaaS Plans)
For SaaS platforms with Free, Pro, and Enterprise pricing tiers, create a custom throttle class:
Practice Quiz
Best Practices
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| API Versioning Strategies | Best Practices |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.