Rate Limiting Behind a Load Balancer: Trust Proxy Is Not a Boolean

Rate Limiting Behind a Load Balancer: Trust Proxy Is Not a Boolean

#rate-limiting#security#nodejs#redis#compliance

Seventh post from the compliance-ready backend kit, after database-per-tenant and the permission catalogue.

I have already written about the algorithms: token bucket versus sliding window, and why the check has to be atomic. This post is the half that decides whether any of that works in production: who the client is, and what the limiter does when its store is gone.

Writing it, I found a bug in my own kit. It is in the first section, because it is the most useful thing here.

A rate limit is only as good as its key

Every limiter counts something per client. Behind a load balancer, the socket address is the balancer’s, so you read the client from X-Forwarded-For. That header is a list, built up hop by hop:

X-Forwarded-For: <what the client sent>, <what each proxy appended>

The leftmost entry is whatever the client typed. A proxy that appends adds the real address on the right and passes the rest through untouched. AWS’s Application Load Balancer does exactly that by default: its X-Forwarded-For processing mode defaults to append.

So the safe way to read it is from the right: skip every address that belongs to a proxy you trust, and the first one you do not trust is the client. Fastify does this for you, through its trustProxy option. The catch is what you tell it to trust.

The kit exposes that option as a boolean, TRUST_PROXY, and its docs describe the trade like this:

SettingDeploymentResult
falsebehind a load balancerevery request appears to come from the balancer, one shared bucket, the first busy client throttles everyone
truenothing trusted in fronta caller sends X-Forwarded-For: anything and gets a fresh bucket per request

The default is false, and the reasoning holds: that failure is loud, everyone gets 429s within minutes. The other failure is silent, the limiter reports healthy and enforces nothing.

Here is what the table gets wrong. true does not mean “trust my proxy”. It means “trust every address in the header”. Walk the list from the right trusting everything, and you arrive at the leftmost entry, the one the client wrote. Behind an appending balancer, true is just as spoofable as it is with nothing in front.

I checked it rather than reasoned about it. Fastify 5.12.7, a request arriving from the balancer at 10.0.0.5, a real client at 198.51.100.7 who forged a header, and an appending balancer:

const res = await app.inject({
  method: "GET",
  url: "/",
  remoteAddress: "10.0.0.5",
  headers: { "x-forwarded-for": "1.2.3.4, 198.51.100.7" },
});
trustProxyrequest.ipVerdict
false10.0.0.5the balancer, everyone shares a bucket
true1.2.3.4the forged value, a fresh bucket per request
1 (hop count)10.0.0.5disabled in this Fastify version, see below
"10.0.0.0/8"198.51.100.7the real client

Only the last row is right, and it is not a boolean. Trust is a list of proxy addresses, typically the CIDR your load balancers live in.

The hop count row is worth a sentence. Fastify 5.12.7 refuses hop-count trust outright and treats every hop as untrusted, because “trust the nearest hop” cannot tell a real proxy from a client connecting directly and pretending to be one. Its documentation now says to use an IP or CIDR list, or a function that checks the proxy’s address.

So this is a bug in the kit. TRUST_PROXY=true behind a default ALB lets any caller pick its own bucket, which defeats the request limits and the per-address login counter. The per-account login counter does not depend on the address and still holds. The fix is in review as PR #87: TRUST_PROXY becomes a list of trusted proxy addresses, and true and hop counts are refused at boot with an explanation of why. Whatever you run, pass Fastify the CIDR, never true.

IPv6 clients are counted by /64

Once you have the right address, there is one more way to lose the key. A single IPv6 host is routinely given a whole /64, so the last 64 bits cost an attacker nothing to rotate. Keyed on the full address, every request can come from a fresh address with a fresh budget.

The kit keys every per-address limit on the /64 prefix, and folds IPv4-mapped addresses back to IPv4 so one client is not counted in two buckets:

export function rateLimitIdentity(address: string): string {
  if (isIPv4(address)) return address;
  if (!isIPv6(address)) return address;
  const groups = expandIPv6(address.split("%")[0]);
  // ::ffff:203.0.113.7, ::ffff:cb00:7107 and 0:0:0:0:0:ffff:203.0.113.7 are one address
  if (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff) {
    return [groups[6] >> 8, groups[6] & 0xff, groups[7] >> 8, groups[7] & 0xff].join(".");
  }
  return `${groups.slice(0, 4).map((g) => g.toString(16)).join(":")}::/64`;
}

That comment hides a real bug. The first version matched only the ::ffff:a.b.c.d spelling. A proxy that wrote the hex form put every IPv4 client into one 0:0:0:0::/64 bucket, so the busiest of them throttled all the rest.

The cost of /64 keying is that clients sharing a /64 share a budget. Audit events still record the full address, because evidence should say what arrived.

Two controls, not one

A request rate limit and a login throttle look alike and defend different things.

Request rate limitLogin throttle
Protectsthe service, from loadan account, from guessing
Countsevery requestfailed logins only
Keyed onclient addressthe account and the address
Kit default100 per minute10 failures per 15 minutes
On successnothingthe account counter is cleared

Keying the throttle on both matters. Account-only lets one host spray guesses across many accounts. Address-only lets a botnet hammer one account. And only the account counter clears on success: if the address counter cleared too, anyone holding one valid account could log into it to reset their address budget on demand.

The numbers come from NIST SP 800-63B-4, section 3.2.2. It says a verifier shall limit consecutive failed attempts on one account to no more than 100, and should disregard earlier failures once the subscriber authenticates successfully. The kit’s ten is well inside that, and counting only failures is what lets the limit be tight without generating support tickets.

PCI DSS Requirement 8.3.4 is usually read as a lockout of at least 30 minutes. The kit deliberately implements a throttle, not a lockout, because an unauthenticated way to lock a named user out indefinitely is a denial of service anyone can aim at anyone. Set the window to 30 minutes if your assessor reads it that way. The kit’s own mapping marks that citation unverified, since the standard sits behind a registration wall.

The PID 1 bug

The sliding window is a Redis sorted set per key: drop entries older than the window, count what is left, add the new attempt if it is allowed, all in one Lua script so two concurrent requests cannot both read the old count.

A sorted set is keyed by member. ZADD with a member that already exists updates its score instead of adding a second entry. So every counted event needs a unique member id, and the first version built it from process.pid.

In a container, every process is PID 1. Every replica, every restart, the same id. Two pods counting the same client produced colliding members, and two requests counted as one. The limiter undercounted, quietly, in exactly the multi-instance deployment it was built for.

Hostname fails the same way behind a scheduler that reuses names, and a start timestamp collides when replicas boot together, which is what a rolling deploy does. The fix is randomness plus a counter:

export function newMemberIdFactory(): () => string {
  const instanceId = randomBytes(8).toString("base64url");
  let counter = 0;
  return () => `${instanceId}:${++counter}`;
}

64 random bits separate processes; the counter makes a collision within one process impossible rather than unlikely.

Two smaller choices in the same script:

  • A rejected attempt is not recorded. No ZADD on the reject path, so hammering an already-throttled key cannot keep pushing the window forward and hold a real user out for as long as the attacker likes.
  • Retry-After is computed from the oldest surviving entry, not the whole window, so a client is told when a slot actually frees up.

Details that are cheap to get right

  • Run the limiter first. It is registered globally, before anything that touches the database. The smoke test asserts that a request rejected by the control-plane auth guard still carries rate-limit headers. If the limiter ran after authentication, failed attempts would be unlimited.
  • Exempt the health check. A 429 on a liveness probe gets your container killed in the middle of an incident, turning a load spike into an outage.
  • Round Retry-After up, and never send 0. RFC 9110 defines delay-seconds as 1*DIGIT, so Retry-After: 0.4 is malformed, and a rounded-down 0 tells the client to retry immediately.
  • Say nothing in a 429 body. Not which limit, not how many attempts remain. On the login route that would confirm an account exists and is worth continuing against.

When Redis is gone

This is the decision people skip, and the kit makes it twice, in opposite directions.

The login throttle fails closed, always. If either counter cannot be read, the attempt is refused before any password work: a 429 with Retry-After: 1, an error-level log line, and an audit event with reason: throttle_unavailable (as opposed to limit_exceeded for real guessing). Logging in is unavailable for the length of the outage. Every other route, and every token already issued, keeps working. An attempt nobody counted is unlimited guessing, and the throttle is the only thing preventing it.

The request limits fail open by default. Failing closed there turns a Redis blip into an outage of the whole API, which is a larger incident than the one being prevented. It is configurable, RATE_LIMIT_FAIL_OPEN=false, for deployments where unmetered access is the greater risk and Redis can be a hard dependency.

Failing open is the worse compliance outcome of the two, so it is made loud:

  • every occurrence is logged at error level;
  • the response carries x-ratelimit-degraded: true;
  • the x-ratelimit-limit and x-ratelimit-remaining headers are omitted rather than filled in, because a budget header on an unchecked request tells the client something was verified when it was not.

The test for the throttle’s fail-closed path is pinned the honest way: the stub store reports an unreadable counter as allowed, which is what a real outage returns, and the tests require a refusal anyway. Remove the check and they fail.

The general rule: fail open on request limits for availability, fail closed on authentication limits, and make the degradation loud either way. A limiter that silently stops limiting is the worst outcome for a control you are claiming.

What the kit does not do

  • No network-layer DoS protection. It bounds requests, not bandwidth, and cannot stop traffic before it reaches the process. That row is marked Not implemented here; it belongs to a CDN or WAF.
  • No per-tenant quotas. Limits are per client.
  • One Redis is a single point of failure for the control. The fail-open policy is how that is handled, not solved.
  • The trusted-proxy bug above, until PR #87 is merged.

The part worth taking with you

  1. trustProxy: true trusts the client’s own header. Trust your proxies by address, a CIDR list, and test it with a forged X-Forwarded-For behind your real balancer.
  2. Key IPv6 on the /64, and fold every spelling of an IPv4-mapped address back to IPv4.
  3. Never build a unique id from the PID. In a container it is 1 everywhere.
  4. Decide what each limiter does without its store. Fail closed for login, open for everything else, and loud in both cases.

The code is in services/auth/src/ratelimit/ in the kit repo. Next in this series: the compliance mapping itself, and why a list of controls should lead with the ones it does not implement.

Get new posts by email

Backend, auth, and shipping compliant systems. No spam, unsubscribe anytime.