Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Filtering, Pagination and Throttling

Throttling and Rate Limits in DRF

Protect a Django REST Framework API from abuse with throttling: AnonRateThrottle, UserRateThrottle, ScopedRateThrottle, custom throttle classes, 429 responses, Retry-After and cache backends.

Without limits, one misbehaving client can use all your capacity: a script stuck in a loop, a scraper, or a password-guessing attack on the login endpoint. Throttling limits how many requests a client may make in a period of time. When the limit is reached, DRF stops running your view and answers 429 Too Many Requests with a Retry-After header that says how many seconds to wait.

Throttling is similar to permissions, and the code looks alike: a list of classes, checked before the view runs. The difference is that permissions answer "may you?" while throttles answer "may you again, right now?". Throttles remember past requests, so they need a cache to keep their counters.

How DRF throttling works

For every request, each throttle class builds a cache key that identifies the client. It loads the list of recent request timestamps from the cache, drops those older than the period, and compares the length with the allowed number. If the request is allowed, its timestamp is added.

One request, one check

Build a key User id, or IP address for guests
Read the cache Timestamps of recent requests
Count Drop old ones, compare to the rate
Allow or 429 Retry-After says when to come back

No database tables: only the cache

1 / 2

The built-in classes are:

Class Identifies the client by Rate comes from
AnonRateThrottle IP address (only for unauthenticated users) DEFAULT_THROTTLE_RATES["anon"]
UserRateThrottle user id (IP address for guests) DEFAULT_THROTTLE_RATES["user"]
ScopedRateThrottle user id or IP, per scope the view's throttle_scope

Rates are strings of the form number/period, where the period starts with s, m, h or d ("5/min", "1000/day", "10/second"). Only the first letter matters.

Configure them globally in settings.py:

Python
# settings.py (read-only)
REST_FRAMEWORK = {
    "DEFAULT_THROTTLE_CLASSES": [
        "rest_framework.throttling.AnonRateThrottle",
        "rest_framework.throttling.UserRateThrottle",
    ],
    "DEFAULT_THROTTLE_RATES": {
        "anon": "100/day",
        "user": "1000/day",
    },
}

Or set throttle_classes on one view. Waiting a real minute inside a lesson would be tedious, so the examples below replace the clock. DRF's SimpleRateThrottle reads the time through a timer attribute; a subclass can point it at a variable we control. You never do this in production code, but it is exactly how DRF's own tests work.

Anonymous and user rates

A guest gets 3 requests per minute, a logged-in user gets 5. The same view serves both.

Python AnonRateThrottle and UserRateThrottle with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
guest    [200, 200, 200] | next: 429 60 {'detail': 'Request was throttled. Expected available in 60 seconds.'}
member   [200, 200, 200, 200, 200] | next: 429 60 {'detail': 'Request was throttled. Expected available in 60 seconds.'}
... 61 seconds pass ...
guest again: 200 | member again: 200

Points to remember:

  • Guests are counted per IP address. Behind a proxy or load balancer every request seems to come from the proxy, so set NUM_PROXIES in REST_FRAMEWORK (the number of proxies in front of your app) so DRF reads the real client from X-Forwarded-For.
  • UserRateThrottle and AnonRateThrottle do not share counters: a user who logs out gets a fresh, smaller allowance, and one who logs in gets the user allowance.
  • A throttled response is an ordinary DRF error: {"detail": "Request was throttled. Expected available in N seconds."} with status 429.

Different limits for different endpoints

A global rate treats a cheap GET and an expensive report export the same. ScopedRateThrottle lets each view declare a scope, and the rate for that scope comes from settings. Views without throttle_scope are not limited by it. In a ViewSet you can set throttle_scope per action using @action(..., throttle_scope="exports") or by overriding get_throttles().

Python ScopedRateThrottle: uploads are stricter than reads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
uploads: [201, 201, 429, 429]
reads:   [200, 200, 200, 200, 200, 200, 429, 429]
30 s later, upload -> 429 30 seconds left
61 s later, upload -> 201

The two scopes keep separate counters even for the same client, so exhausting uploads leaves reads untouched.

Writing your own throttle

Subclass BaseThrottle and implement allow_request(request, view); optionally wait() to return the seconds to wait. Usually it is easier to subclass SimpleRateThrottle, which already manages the cache, and implement only get_cache_key(request, view). Return None to skip throttling for a request, or any string to count it. The cache key decides who shares a bucket.

A typical example is "staff are never throttled, everyone else gets a rate by plan":

Python A custom throttle with exemptions and per-plan rates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
free_ann  [200, 200, 429, 429, 429, 429]
pro_bob   [200, 200, 200, 200, 429, 429]
admin_cy  [200, 200, 200, 200, 200, 200]

Production concerns

  • The cache backend matters. The default LocMemCache is per process, so with four worker processes a "5 per minute" limit effectively becomes 20. Use a shared cache (Redis or Memcached) in production: CACHES = {"default": {"BACKEND": "django.core.cache.backends.redis.RedisCache", ...}}.
  • Throttling is best-effort. DRF reads and writes the history without a lock, so under heavy concurrency a client can slip a few extra requests through. It is good for fairness and abuse reduction, not for precise billing counters.
  • Protect login routes first. A strict scoped throttle on the token or JWT login endpoint is a cheap defence against password guessing.
  • Also limit at the edge. A reverse proxy or CDN can reject floods before they reach Python. Use DRF throttles for per-user and per-endpoint rules.
  • Tell clients. Document the limits and encourage clients to honor Retry-After.

Common mistakes

  • Setting DEFAULT_THROTTLE_CLASSES but forgetting DEFAULT_THROTTLE_RATES: the app fails with ImproperlyConfigured the first time a throttled view runs.
  • Using a scope name in a view that does not exist in DEFAULT_THROTTLE_RATES.
  • Forgetting NUM_PROXIES, so all guests share one counter, or trusting a spoofable X-Forwarded-For header.
  • Expecting throttles to survive a cache flush: clearing the cache resets every counter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which status code does DRF return when a request is throttled?

    A throttled request gets 429 with a Retry-After header telling the client how long to wait.
  2. 2. Where does DRF keep the request history for throttling?

    Throttles read and write timestamps through the Django cache framework, so a shared cache is needed across processes.
  3. 3. What does ScopedRateThrottle do?

    Each view names a scope, and DEFAULT_THROTTLE_RATES maps that scope to a rate such as 2/min.
  4. 4. Four server processes each use LocMemCache and the rate is 10/min. What is the real limit per client?

    Each process counts separately, so the effective limit is multiplied by the number of processes. Use Redis or Memcached.
  5. 5. What should get_cache_key() return to skip throttling for a request?

    Returning None means the request is not throttled; any other string chooses the bucket that is counted.

Summary

  • Throttles limit requests per period and answer 429 with Retry-After; counters live in the cache.
  • AnonRateThrottle counts by IP, UserRateThrottle by user, ScopedRateThrottle by scope per view; rates look like "100/day".
  • Subclass SimpleRateThrottle and implement get_cache_key() for custom rules; return None to exempt a request.
  • Use a shared cache in production, set NUM_PROXIES behind proxies, and treat throttling as best-effort protection.
  • Throttle login endpoints first.

Next: API Versioning