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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A three-level nested function turns a decorator into one that accepts configuration arguments.
- 2Atomic cache increments let you count requests across processes without a race condition.
- 3Signalling limits with a 429 status and Retry-After header lets clients back off gracefully.
Related explainers
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-rate-limit-decorator-in-django-explained-python-f4f5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.