python 40 lines · 7 steps

Building a rate-limit decorator in Django

A configurable decorator that throttles requests per client using Django's cache backend and returns 429s when limits are hit.

Explained by highlit
1from functools import wraps
2 
3from django.core.cache import cache
4from django.http import JsonResponse
5 
6 
7def rate_limit(max_requests=60, window=60, scope="default"):
8 def decorator(view_func):
9 @wraps(view_func)
10 def wrapper(request, *args, **kwargs):
11 ident = _client_ip(request)
12 key = f"ratelimit:{scope}:{ident}"
13 
14 count = cache.get_or_set(key, 0, timeout=window)
15 count = cache.incr(key)
16 
17 if count > max_requests:
18 ttl = cache.ttl(key) or window
19 response = JsonResponse(
20 {"detail": "Rate limit exceeded. Try again later."},
21 status=429,
22 )
23 response["Retry-After"] = str(ttl)
24 return response
25 
26 response = view_func(request, *args, **kwargs)
27 response["X-RateLimit-Limit"] = str(max_requests)
28 response["X-RateLimit-Remaining"] = str(max(0, max_requests - count))
29 return response
30 
31 return wrapper
32 
33 return decorator
34 
35 
36def _client_ip(request):
37 forwarded = request.META.get("HTTP_X_FORWARDED_FOR")
38 if forwarded:
39 return forwarded.split(",")[0].strip()
40 return request.META.get("REMOTE_ADDR", "unknown")
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A three-level nested function turns a decorator into one that accepts configuration arguments.
  2. 2Atomic cache increments let you count requests across processes without a race condition.
  3. 3Signalling limits with a 429 status and Retry-After header lets clients back off gracefully.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a rate-limit decorator in Django — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code