Per-IP Rate Limiting Behind a Reverse Proxy in Django

Django AppSec

Per-IP rate limiting restricts how many requests a single client IP address can make to a sensitive endpoint within a fixed time window, returning HTTP 429 Too Many Requests once the threshold is exceeded. In Django, lightweight endpoint throttling can be implemented directly with django.core.cache without external dependencies, provided client IP extraction accounts for reverse proxies and executes in the right order relative to other defenses.

Extracting the Client IP Behind a Reverse Proxy

In production, Django applications almost always sit behind a reverse proxy (Nginx, Traefik, Cloudflare). Because the TCP connection to Gunicorn originates from the proxy, request.META["REMOTE_ADDR"] contains the proxy's internal IP address rather than the visitor's IP.

Instead, read the client IP from HTTP_X_FORWARDED_FOR, but only the entry written by a proxy you control. Each proxy appends the address it received the connection from (Nginx's $proxy_add_x_forwarded_for, Cloudflare), so the header looks like <whatever the client sent>, <client IP seen by your proxy>. Everything to the left of your proxy's entry is supplied by the client.

TRUSTED_PROXY_COUNT = 1  # reverse proxies you control in front of Django (Cloudflare + Nginx = 2)

def _get_client_ip(request):
    x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
    if x_forwarded_for:
        hops = [ip.strip() for ip in x_forwarded_for.split(",")]
        if len(hops) >= TRUSTED_PROXY_COUNT:
            # The entry appended by the outermost trusted proxy is the real client.
            return hops[-TRUSTED_PROXY_COUNT]
    return request.META.get("REMOTE_ADDR", "unknown")

A simpler alternative is a header the proxy sets rather than appends, which the client therefore can't influence: proxy_set_header X-Real-IP $remote_addr; in Nginx (read HTTP_X_REAL_IP), or CF-Connecting-IP behind Cloudflare (read HTTP_CF_CONNECTING_IP).

Either way, the Django container's port must not be reachable directly from the internet, or a client can bypass the proxy and forge the whole header (see Docker Port Binding and Host Firewall Bypass).

Cache-Backed Counter Implementation

Using django.core.cache, the view increments a key scoped to the client IP (contact_rate_limit:<ip>) before performing expensive work:

CONTACT_RATE_LIMIT = 5
CONTACT_RATE_LIMIT_TIMEOUT = 3600  # 1 hour in seconds

client_ip = _get_client_ip(request)
cache_key = f"contact_rate_limit:{client_ip}"

# add() only creates the key if it is missing, so the window starts at the first
# submission and later ones don't extend it. incr() is atomic on Redis/Memcached.
cache.add(cache_key, 0, timeout=CONTACT_RATE_LIMIT_TIMEOUT)
try:
    submissions = cache.incr(cache_key)
except ValueError:  # key expired between add() and incr()
    cache.set(cache_key, 1, timeout=CONTACT_RATE_LIMIT_TIMEOUT)
    submissions = 1

if submissions > CONTACT_RATE_LIMIT:
    form = ContactForm(request.POST)  # re-display what the visitor typed
    messages.error(request, "Trop de tentatives d'envoi. Veuillez réessayer plus tard.")
    return render(request, "crm/contacts_new.html", {"form": form}, status=429)

Defense Ordering: Rate Limit Before Honeypot

When combining per-IP rate limiting with Form Honeypot Design and Silent Rejection, the rate-limit check and counter increment must execute first—before the honeypot check, form validation, database writes, or send_mail():

POST /contact/
  │
  ├─► 1. Rate Limit (cache.add + cache.incr) ──► Over 5 this hour? ──► Return HTTP 429 Too Many Requests
  │         │
  │         ▼ (Within limit)
  ├─► 2. Honeypot Check on raw POST (`website` filled?) ──► Silent 302 Redirect to /contact/thanks/
  │         │
  │         ▼ (Trap empty)
  ├─► 3. Form Validation (`form.is_valid()`) ──► Invalid? ──► Re-render the form with errors
  │         │
  │         ▼ (Clean human submission)
  └─► 4. DB Insert (`Contact.objects.create`) + Synchronous SMTP (`send_mail`)

Evaluating the rate limit first ensures that an automated bot repeatedly hitting the honeypot still consumes its IP quota and gets throttled with 429 Too Many Requests after 5 attempts, rather than invoking Django's view and template pipeline indefinitely.

The cost of this order: submissions that fail form validation (a mistyped email address) also use up the quota, so a legitimate visitor who makes several mistakes can be throttled before their message goes through. At 5 per hour this is usually acceptable; raise the limit if real users hit it.

References

Review cards

Flashcard Why does rate-limiting on `REMOTE_ADDR` behind a reverse proxy lock everyone out?

REMOTE_ADDR is the proxy's address, so every visitor shares one counter, and a handful of submissions blocks all users.

Flashcard Which `X-Forwarded-For` entry identifies the real client?

The one appended by your outermost trusted proxy, found by counting the number of trusted proxies from the right. Everything to its left was sent by the client.

Flashcard How does a bot escape a rate limit keyed on the first `X-Forwarded-For` entry?

It sends a different fake X-Forwarded-For on each request, gets a fresh counter every time, and is never throttled.

Flashcard Why does the rate-limit check run before the honeypot check?

So bots that keep filling the honeypot still use up their per-IP quota and get a 429 after 5 tries, instead of fake successes forever.

Quiz What goes wrong if the view calls `cache.set(key, n + 1, timeout=3600)` on every submission?
  • Each hit restarts the hour, so the window slides instead of being fixed
  • The key never expires
  • The counter goes back to zero on each hit
  • Visitors are throttled after their first submission

Start the window once with cache.add() and count with cache.incr(), which is also atomic on Redis and Memcached.

Flashcard Why must the Django container's port not be reachable directly from the internet?

A client could skip the proxy and send any X-Forwarded-For or X-Real-IP it likes, defeating the IP-based rate limit.

Flashcard With `LocMemCache` and 4 Gunicorn workers, what is the real limit of a "5 per hour" rate limit?

20 per hour: each worker keeps its own counter, and every restart or deploy resets them all.

Flashcard Why is `X-Real-IP` easier to trust than `X-Forwarded-For`?

The proxy sets it (proxy_set_header X-Real-IP $remote_addr) instead of appending to what the client sent, so the client can't influence it.

Flashcard Why count submissions with `cache.incr()` rather than `cache.get()` then `cache.set()`?

get + set isn't atomic: concurrent requests read the same count and all get through. incr() is atomic on Redis and Memcached.