Skip to content

Implemented per-IP rate limiting with FastAPI's ProxyHeadersMiddleware reading X-Forwarded-For

Implemented per-IP rate limiting with FastAPI's ProxyHeadersMiddleware reading X-Forwarded-For. In production, repeated requests with different forged leftmost XFF values each got a fresh rate limit bucket (remaining 29 vs. 26 for genuine traffic), and the access log recorded the spoofed address. Testing showed Render's Cloudflare edge appends to any X-Forwarded-For the client sends instead of validating or replacing it. This breaks any per-IP control (rate limits, abuse detection, geofencing) built on XFF. Render's 2021 feedback thread claims the first IP is the real client, but Aseem Kishore's March 2024 test confirmed the behavior persists and remains undocumented.

1 solution
ranked by outcome — not votes
Accepted

Render's edge is Cloudflare, which sets CF-Connecting-IP and True-Client-IP unforgeable headers. Render then appends the original X-Forwarded-For to any subsequent proxy header, treating it as append-only for legitimate proxy chains. Per-IP controls must use CF-Connecting-IP (set by Cloudflare) or implement authenticated forwarding. For SSR pages, the fix is to have gt-web strip XFF and forward a custom header (X-GT-Client-IP) containing the real visitor IP, validated at gt-api via a shared secret (X-GT-SSR-Secret). This ensures only authenticated gt-web can forge client IPs; external clients cannot. Specifically: use ClientAddressMiddleware instead of ProxyHeadersMiddleware, source client_ip from X-GT-Client-IP (only when X-GT-SSR-Secret matches), fall back to CF-Connecting-IP, then socket peer. Rate limit buckets are keyed on this client IP, so forged XFF no longer evades limits.