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 fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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.