---
title: "Rate Limiting Behind a Load Balancer: Real Client IP | CloudGuys Blog"
description: "Which IP should a rate limiter count? Why X-Forwarded-For is spoofable, why counting from the right is safe, and how to configure it in Tollgate."
url: "https://cloudguys.io/blog/rate-limit-client-ip-x-forwarded-for-krakend"
language: "en"
image: "https://cloudguys.io/_astro/cover.BEHhCe7Z.jpg"
published: "2026-11-16T00:00:00.000Z"
modified: "2026-11-16T00:00:00.000Z"
---

ENGINEERING NOTES / API GATEWAYS

# Rate Limiting Behind a Load Balancer: Which IP Is the Real Client?

A rate limiter that reads the wrong IP either blocks your own load balancer or lets one client dodge every limit. How X-Forwarded-For works, why counting from the right is safe, and how to set it up in Tollgate on KrakenD CE.

Sabbir Ahmed · · · November 16, 2026 · · · 6 min read · · · About Tollgate

![Rate Limiting Behind a Load Balancer: Which IP Is the Real Client?](https://cloudguys.io/_astro/cover.BEHhCe7Z_lwEns.webp)

Behind a load balancer, count the address that your outermost trusted proxy saw. That is the second-to-last entry in `X-Forwarded-For` when one proxy sits in front of you, and you reach it by counting from the right, never the left. Read the left side and anyone can pick their own IP. Read the connection address and you rate-limit your own load balancer.

This post explains why, with one example you can follow line by line. Then it shows the setting in Tollgate, the rate-limiting plugin CloudGuys builds for KrakenD Community Edition (CE).

## The problem in one request

Your gateway needs to know who is calling so it can say “this caller has used 100 requests this minute.” If callers have no API key, the best identifier is the IP address.

But there is a load balancer in front of your gateway. The TCP connection your gateway sees comes from the balancer, not from the user. Every request appears to come from one address.

So proxies pass the original address along in a header, `X-Forwarded-For`. Each proxy that handles the request **adds** the address it received the connection from, at the end of the list.

## What the header looks like

Take a user at `203.0.113.7`, one load balancer, and your gateway. The gateway receives this:

```plaintext
X-Forwarded-For: 203.0.113.7
```

The balancer added the user’s address. That is the whole header, and the right-most entry is the one your own proxy wrote.

Now a user who is up to something. They send their own header with the request:

```plaintext
X-Forwarded-For: 6.6.6.6
```

The balancer does not replace it. It adds to it:

```plaintext
X-Forwarded-For: 6.6.6.6, 203.0.113.7
```

The left entry, `6.6.6.6`, was written by the client. The right entry, `203.0.113.7`, was written by your balancer, and it is true.

## Why the left side is a trap

If the limiter takes the first entry, the attacker controls their identity. They send a different made-up address on every request and get a new, empty bucket each time. The limit never fires.

It gets worse with IP bans. A limiter that bans an address after repeated abuse can be tricked into banning an innocent one. The attacker just writes someone else’s IP on the left.

Tollgate’s docs make the same point: everything to the left of what your own proxies appended was written by the client.

## Count from the right

The safe rule is to trust only the entries your own proxies wrote. Those are at the right end. Tollgate’s `forwarded-for:N` source takes the N-th entry from the right, where N is the number of proxies you run in front of the gateway.

| Your setup | Source | Header the gateway sees | IP used |
| --- | --- | --- | --- |
| Clients connect straight to KrakenD | `remote-addr` | none | the TCP peer |
| One load balancer in front | `forwarded-for:1` | `6.6.6.6, 203.0.113.7` | `203.0.113.7` |
| CDN, then load balancer | `forwarded-for:2` | `6.6.6.6, 203.0.113.7, 10.0.0.5` | `203.0.113.7` |

In the last row, the CDN appended `203.0.113.7` (the user) and the load balancer appended `10.0.0.5` (the CDN). Counting two from the right lands on the user. Count only proxies that really append to the header.

## The setting

Put the sources in order. Tollgate tries each one and uses the first that gives an answer:

```json
"identity": {
  "sources": ["header:X-Client-ID", "forwarded-for:1", "remote-addr"]
}
```

Read it as: use the `X-Client-ID` header if the request has one, otherwise the real client IP from one trusted proxy, otherwise the connection address.

The last entry matters. If the header has fewer entries than N, the request did not come through your proxies, so Tollgate does not guess. It moves to the next source. Without `remote-addr` at the end, a request that matches nothing is called `unknown`, and all unknown requests share a single bucket.

## Three mistakes to avoid

1.  **Setting N too low.** With `forwarded-for:1` behind two proxies you get the inner proxy’s address. Every user shares it, and your own proxy gets rate-limited.
2.  **Setting N too high.** You step into the part of the header the client wrote, and spoofing works again.
3.  **Leaving the gateway reachable without the proxy.** If someone can connect to KrakenD directly, they can send any header they like. Close that path with network rules. Counting from the right also assumes your proxies append to the header and do not overwrite it.

One more case. Some proxies add a new header line instead of extending the existing one. Tollgate joins all `X-Forwarded-For` lines into one list before it counts, so this still works.

## Test it before you trust it

Send a request with a fake leftmost address and check which identity the limiter used:

```bash
curl -H 'X-Forwarded-For: 6.6.6.6' https://your-gateway.example/v1/ping
```

Your load balancer will append the real address. The limiter must count it against that address and not against `6.6.6.6`. Send a different fake address each time. If the limit still fires, counting works.

The same setting drives Tollgate’s IP filter, geo-IP rules and maintenance bypass. Each takes a `sources` list with the same syntax, so you set the rule once and reuse it.

## FAQ

**Which `X-Forwarded-For` entry should a rate limiter use?** The one your outermost trusted proxy appended. Count N entries from the right, where N is the number of proxies you run in front of the gateway.

**Why not use the first entry?** The first entry can be written by the client. Anyone can send a random address and get a new rate-limit bucket on every request.

**What if the header has too few entries?** In Tollgate, the request is treated as not having come through the expected chain. The source gives no answer and the next source is tried. End the list with `remote-addr`.

**Does this work with an API key?** Keys are better when you have them. With API keys enabled, Tollgate identifies callers by key ID first and uses the IP sources for requests without a key.

## Where to go next

If your gateway sits behind Istio, [this guide to the real client IP in Istio ambient](https://cloudguys.io/blog/real-client-ip-behind-istio-ambient-gateway-secure-x-forwarded-for-in-go) covers the mesh side. To see everything else Tollgate adds to KrakenD CE, such as API keys, plans, quotas and limits that hold across nodes, visit the [Tollgate page](https://cloudguys.io/products/tollgate).

To license Tollgate for KrakenD CE 2.13, email [hello@cloudguys.io](mailto:hello@cloudguys.io?subject=Tollgate%20licence) with the subject “Tollgate licence”.

#Rate Limiting · #X-Forwarded-For · #API Gateway · #KrakenD · #Security · #Tollgate

Share this article

-   [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcloudguys.io%2Fblog%2Frate-limit-client-ip-x-forwarded-for-krakend%3Futm_source%3Dlinkedin%26utm_medium%3Dsocial "Share on LinkedIn")
-   [X](https://twitter.com/intent/tweet?text=Rate%20Limiting%20Behind%20a%20Load%20Balancer%3A%20Which%20IP%20Is%20the%20Real%20Client%3F&url=https%3A%2F%2Fcloudguys.io%2Fblog%2Frate-limit-client-ip-x-forwarded-for-krakend%3Futm_source%3Dx%26utm_medium%3Dsocial "Share on X")
-   [Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fcloudguys.io%2Fblog%2Frate-limit-client-ip-x-forwarded-for-krakend%3Futm_source%3Dreddit%26utm_medium%3Dsocial&title=Rate%20Limiting%20Behind%20a%20Load%20Balancer%3A%20Which%20IP%20Is%20the%20Real%20Client%3F "Share on Reddit")
-   [Hacker News](https://news.ycombinator.com/submitlink?u=https%3A%2F%2Fcloudguys.io%2Fblog%2Frate-limit-client-ip-x-forwarded-for-krakend%3Futm_source%3Dhackernews%26utm_medium%3Dsocial&t=Rate%20Limiting%20Behind%20a%20Load%20Balancer%3A%20Which%20IP%20Is%20the%20Real%20Client%3F "Share on Hacker News")
-   [Email](mailto:?subject=Rate%20Limiting%20Behind%20a%20Load%20Balancer%3A%20Which%20IP%20Is%20the%20Real%20Client%3F&body=Rate%20Limiting%20Behind%20a%20Load%20Balancer%3A%20Which%20IP%20Is%20the%20Real%20Client%3F%0A%0Ahttps%3A%2F%2Fcloudguys.io%2Fblog%2Frate-limit-client-ip-x-forwarded-for-krakend%3Futm_source%3Demail%26utm_medium%3Dsocial "Share on Email")

BUILT AND OPERATED BY CLOUDGUYS

## Tollgate: api gateway plugin  
API keys, quotas and cluster-wide rate limits for KrakenD Community Edition.

A KrakenD CE plugin that adds the edge features the Community Edition lacks: hashed API keys with plans and quotas, token-bucket or sliding-window rate limits and concurrency caps that hold across every gateway node, IP and geo-IP filtering, a maintenance switch, an audit log and Prometheus metrics. Valkey keeps the shared state.

[Ask about a licence ↗](mailto:hello@cloudguys.io?subject=Tollgate%20licence) [About Tollgate ↗](https://cloudguys.io/products/tollgate)

## Structured data

```json
[
  {
    "@context": "https://schema.org",
    "@type": [
      "ProfessionalService",
      "Organization"
    ],
    "@id": "https://cloudguys.io/#organization",
    "name": "CloudGuys",
    "url": "https://cloudguys.io/",
    "logo": {
      "@type": "ImageObject",
      "url": "https://cloudguys.io/assets/logo.png",
      "width": 512,
      "height": 512
    },
    "image": "https://cloudguys.io/assets/og-image.png",
    "description": "Self-hosted software products, senior engineers embedded in client teams, and cloud security and architecture advisory across AWS, Google Cloud, Azure, Kubernetes, and infrastructure as code.",
    "email": "hello@cloudguys.io",
    "founder": {
      "@type": "Person",
      "@id": "https://cloudguys.io/authors/sabbir-ahmed#person",
      "name": "Sabbir Ahmed",
      "url": "https://cloudguys.io/authors/sabbir-ahmed"
    },
    "slogan": "Ship with confidence. Keep control.",
    "areaServed": "Worldwide",
    "hasOfferCatalog": {
      "@type": "OfferCatalog",
      "name": "CloudGuys engagements",
      "itemListElement": [
        {
          "@type": "Offer",
          "itemOffered": {
            "@type": "Service",
            "name": "Embedded engineers",
            "url": "https://cloudguys.io/services/embedded-engineers",
            "provider": {
              "@id": "https://cloudguys.io/#organization"
            }
          }
        },
        {
          "@type": "Offer",
          "itemOffered": {
            "@type": "Service",
            "name": "Cloud security assessment",
            "url": "https://cloudguys.io/services/cloud-security-assessment",
            "provider": {
              "@id": "https://cloudguys.io/#organization"
            }
          }
        },
        {
          "@type": "Offer",
          "itemOffered": {
            "@type": "Service",
            "name": "Cloud architecture review",
            "url": "https://cloudguys.io/services/cloud-architecture-review",
            "provider": {
              "@id": "https://cloudguys.io/#organization"
            }
          }
        },
        {
          "@type": "Offer",
          "itemOffered": {
            "@type": "Service",
            "name": "Security remediation",
            "url": "https://cloudguys.io/services/security-remediation",
            "provider": {
              "@id": "https://cloudguys.io/#organization"
            }
          }
        }
      ]
    },
    "knowsAbout": [
      "DevOps",
      "Kubernetes",
      "Terraform",
      "Cloud migration",
      "Cloud cost optimization",
      "GitOps",
      "Site reliability engineering",
      "Kubernetes dashboard",
      "AI SRE",
      "Kubernetes troubleshooting",
      "AWS",
      "Google Cloud",
      "Azure"
    ],
    "contactPoint": {
      "@type": "ContactPoint",
      "contactType": "sales",
      "email": "hello@cloudguys.io",
      "availableLanguage": [
        "English"
      ],
      "areaServed": "Worldwide"
    },
    "sameAs": [
      "https://www.linkedin.com/company/agrohitech",
      "https://berth.cloudguys.io",
      "https://tele.cloudguys.io"
    ],
    "owns": [
      {
        "@type": "SoftwareApplication",
        "@id": "https://berth.cloudguys.io/#software",
        "name": "Berth",
        "applicationCategory": "DeveloperApplication",
        "operatingSystem": "Kubernetes",
        "url": "https://berth.cloudguys.io",
        "description": "Berth is a self-hosted Kubernetes dashboard with a read-only AI SRE: endpoint health, capacity planning, guided app exposure, and evidence-based troubleshooting, run in your own cluster."
      },
      {
        "@type": "SoftwareApplication",
        "@id": "https://tele.cloudguys.io/#software",
        "name": "Tele",
        "applicationCategory": "CommunicationApplication",
        "operatingSystem": "Web",
        "url": "https://tele.cloudguys.io",
        "description": "Tele is real-time audio and video call infrastructure: a meeting API for embedding calls in your own application and a managed workspace for teams, deployable in your own cloud or private environment."
      }
    ]
  },
  {
    "@context": "https://schema.org",
    "@type": "WebSite",
    "@id": "https://cloudguys.io/#website",
    "url": "https://cloudguys.io/",
    "name": "CloudGuys",
    "description": "Self-hosted software, embedded engineers and cloud security advisory for teams that run their own platform.",
    "publisher": {
      "@id": "https://cloudguys.io/#organization"
    },
    "inLanguage": "en"
  },
  {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    "@id": "https://cloudguys.io/blog/rate-limit-client-ip-x-forwarded-for-krakend#article",
    "headline": "Rate Limiting Behind a Load Balancer: Which IP Is the Real Client?",
    "description": "Which IP should a rate limiter count? Why X-Forwarded-For is spoofable, why counting from the right is safe, and how to configure it in Tollgate.",
    "image": "https://cloudguys.io/_astro/cover.BEHhCe7Z.jpg",
    "datePublished": "2026-11-16T00:00:00.000Z",
    "dateModified": "2026-11-16T00:00:00.000Z",
    "author": {
      "@type": "Person",
      "@id": "https://cloudguys.io/authors/sabbir-ahmed#person",
      "name": "Sabbir Ahmed",
      "jobTitle": "Founder",
      "url": "https://cloudguys.io/authors/sabbir-ahmed",
      "worksFor": {
        "@id": "https://cloudguys.io/#organization"
      },
      "sameAs": [
        "https://github.com/by-sabbir"
      ]
    },
    "publisher": {
      "@id": "https://cloudguys.io/#organization"
    },
    "mainEntityOfPage": {
      "@type": "WebPage",
      "@id": "https://cloudguys.io/blog/rate-limit-client-ip-x-forwarded-for-krakend"
    },
    "articleSection": "API Gateways",
    "keywords": "Rate Limiting, X-Forwarded-For, API Gateway, KrakenD, Security, Tollgate",
    "inLanguage": "en",
    "about": {
      "@type": "SoftwareApplication",
      "@id": "https://cloudguys.io/products/tollgate/#software",
      "name": "Tollgate",
      "url": "https://cloudguys.io/products/tollgate"
    }
  },
  {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": [
      {
        "@type": "ListItem",
        "position": 1,
        "name": "Home",
        "item": "https://cloudguys.io/"
      },
      {
        "@type": "ListItem",
        "position": 2,
        "name": "Blog",
        "item": "https://cloudguys.io/blog"
      },
      {
        "@type": "ListItem",
        "position": 3,
        "name": "Rate Limiting Behind a Load Balancer: Which IP Is the Real Client?",
        "item": "https://cloudguys.io/blog/rate-limit-client-ip-x-forwarded-for-krakend"
      }
    ]
  },
  {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    "@id": "https://cloudguys.io/blog/rate-limit-client-ip-x-forwarded-for-krakend#faq",
    "mainEntity": [
      {
        "@type": "Question",
        "name": "Which X-Forwarded-For entry should a rate limiter use?",
        "acceptedAnswer": {
          "@type": "Answer",
          "text": "The one your outermost trusted proxy appended. Count N entries from the right, where N is the number of proxies you run in front of the gateway."
        }
      },
      {
        "@type": "Question",
        "name": "Why not use the first entry?",
        "acceptedAnswer": {
          "@type": "Answer",
          "text": "The first entry can be written by the client. Anyone can send a random address and get a new rate-limit bucket on every request."
        }
      },
      {
        "@type": "Question",
        "name": "What if the header has too few entries?",
        "acceptedAnswer": {
          "@type": "Answer",
          "text": "In Tollgate, the request is treated as not having come through the expected chain. The source gives no answer and the next source is tried. End the list with remote-addr."
        }
      },
      {
        "@type": "Question",
        "name": "Does this work with an API key?",
        "acceptedAnswer": {
          "@type": "Answer",
          "text": "Keys are better when you have them. With API keys enabled, Tollgate identifies callers by key ID first and uses the IP sources for requests without a key."
        }
      }
    ]
  }
]
```
