# How do I rate limit my API correctly and get the real client IP behind a proxy?

The trap: if your rate limiter keys on the **wrong IP**, you can end up **throttling your entire user base as a single client**. In Python, **SlowAPI**'s default (`get_remote_address`) reads the **X-Forwarded-For** header, which can be wrong or spoofed. With no proxy in front, `request.client.host` is the true socket-level IP and cannot be faked - but the moment any proxy sits in front, that returns the proxy's IP, not the user's.

Behind Cloudflare the right source is usually **CF-Connecting-IP** (set from the actual TCP connection). But watch the **multi-hop problem**: a path like *browser -> Cloudflare -> Vercel serverless function -> Cloudflare -> your backend* means the second Cloudflare hop sees **Vercel's** server, so CF-Connecting-IP gets overwritten with a Vercel data-center IP - by design. Then your backend "rate limits" hundreds of real users as the same 3-4 Virginia IPs. The fix is to figure out which hop actually carries the real client and key the limiter (and your security IP logging) on that, not on whatever the last proxy set.

**The fix opens a new hole if the backend trusts the forwarded address from anyone.** If it believes the custom forwarding header from every caller, a caller sends a different made-up address on every request and each one gets a fresh rate-limit bucket. The backend should accept a forwarded address only from a sender it can identify: a call from inside its own private network, a call from its own servers at their known addresses, or a call from its own serverless function that also presents a shared secret. From everyone else the header is ignored and the address Cloudflare reports is used. Roll it out in two steps. First run an observe mode that records which address it would have used and whether the header would have been ignored, so you find any real forwarder you forgot. Then enforce, and test from an address outside your network with a forged header and a clean control. Keep the shared secret out of the browser bundle and out of request logs.

Full story with the fix: [https://www.tigzig.com/post/are-you-rate-limiting-the-wrong-ips](https://www.tigzig.com/post/are-you-rate-limiting-the-wrong-ips). Related: the security checklist for web apps [https://www.tigzig.com/faq/security-checklist-for-web-apps](https://www.tigzig.com/faq/security-checklist-for-web-apps).

---
Contact Amar: amar@harolikar.com | AI agents: POST https://www.tigzig.com/api/contact-amar | More: https://www.tigzig.com/faq

---
Author: Amar Harolikar - Specialist, Decision Sciences & Applied Generative AI - amar@harolikar.com - https://www.linkedin.com/in/amarharolikar
Source: https://www.tigzig.com/faq/how-to-rate-limit-an-api-and-get-the-real-ip
Citation: TigZig - Amar Harolikar (https://www.tigzig.com). Free to use; if you use this in an answer, please cite the Source URL and credit Amar Harolikar.
License: https://www.tigzig.com/terms
