skip to content

An Express 5 API behind a load balancer mounts express-rate-limit, and soon all users get 429 together; why, and what is the right fix?

level: seniorimportance: must knowfreq 52%

answer

  1. the key is req.ip
  2. whose address is the socket peer
  3. a validation error in the logs
  4. one hop trusted, never true

basics

~20 s

express-rate-limit keys clients by req.ip, and with Express's default trust proxy false that is the load balancer's address, so every user shares one bucket. Set app.set('trust proxy', 1) or the balancer's subnet, never true, which lets clients forge X-Forwarded-For.

solid answer

~40 s

The limiter's default `keyGenerator` uses `req.ip`. With `trust proxy` at its default `false`, `req.ip` is the socket peer, the load balancer, so all traffic lands in **one counter** and the limiter behaves as a global limit. express-rate-limit says so: it logs `ERR_ERL_UNEXPECTED_X_FORWARDED_FOR` when the first request it counts carries `X-Forwarded-For` while trust proxy is false, and keeps serving. The fix is `app.set('trust proxy', 1)` for one balancer, or its subnet. Do not use `true`: `req.ip` becomes the leftmost, client-written entry, the limiter logs `ERR_ERL_PERMISSIVE_TRUST_PROXY`, and a client escapes by changing the header. Then check the rest: the defaults are only 5 requests per 60 s, the memory store is per process, and the health route should be skipped.

code

javascript · 20 lines
javascript
import express from 'express';
import { rateLimit } from 'express-rate-limit';

const app = express();
app.set('trust proxy', 1); // one load balancer in front

app.get('/healthz', (req, res) => res.sendStatus(200));

app.use(
  rateLimit({
    windowMs: 15 * 60 * 1000,
    limit: 300,
    standardHeaders: 'draft-8',
    legacyHeaders: false,
  }),
);

app.get('/ip', (req, res) => res.json({ ip: req.ip }));

export default app;

go deeper

for a junior

Recall that express-rate-limit keys clients by req.ip and answers 429 when the limit is reached.

for a middle

Explain why req.ip is the balancer under the default trust proxy false, and what the defaults windowMs 60000 and limit 5 mean.

for a senior

Diagnose the shared-bucket outage from the ERR_ERL_UNEXPECTED_X_FORWARDED_FOR log, fix it with one trusted hop rather than true, and cover the per-process store and the health route.

for a principal

Decide which limits live in the app, keyed by user or API key, and which belong at the edge, and who owns the shared store.

## The symptom and the mechanism **express-rate-limit** counts hits per **key** inside a time window. The default `keyGenerator` builds the key from `req.ip`, applying `ipKeyGenerator` so that an IPv6 client is keyed by its `/56` network (the `ipv6Subnet` default) rather than one address it can rotate. `req.ip` is Express's, not the limiter's. With the `trust proxy` setting at its default `false`, Express reports the **socket peer**, `req.socket.remoteAddress`, and behind a load balancer every connection comes from the balancer. Every user therefore gets the same key, the counter fills with everyone's traffic, and once the limit is reached the whole user base receives `429 Too Many Requests` together: the limiter docs call this the **global limiter problem**. The library can notice. Its default key generator runs a set of validation checks once, on the first request the limiter counts; if that request carries `X-Forwarded-For` while `trust proxy` is `false`, it logs a `ValidationError` with code **`ERR_ERL_UNEXPECTED_X_FORWARDED_FOR`**. The check does not stop the request and is not repeated, so the app keeps running in its broken state unless someone reads the logs, and if the very first counted request had no `X-Forwarded-For`, say a probe straight from the balancer, no warning appears at all. ## The fix, and the fix that makes it worse | Setting | `req.ip` behind one balancer | Effect on the limiter | |---|---|---| | `false` (default) | the balancer | one shared bucket for everyone | | `true` | leftmost `X-Forwarded-For` entry, written by the client | a client can send a new value per request and never be limited; the library logs `ERR_ERL_PERMISSIVE_TRUST_PROXY` | | `1`, or the balancer's subnet | the address the balancer appended | one bucket per real client | Set it right after creating the app: ```js app.set('trust proxy', 1); // one balancer between users and the app ``` Then verify with a temporary route that returns `req.ip`. If a CDN sits in front of the balancer, the count is `2`. Some proxies append `IP:port`; their troubleshooting guide suggests a `keyGenerator` that strips the port, otherwise every new source port becomes a fresh key. ## Defaults worth re-checking at the same time The bug review is a good moment to read the options, because several defaults surprise people: - **`windowMs` defaults to `60000`** (one minute) and **`limit` to `5`**; the README example of 100 per 15 minutes is an example, not the default; - **`statusCode`** is `429` and **`message`** is `'Too many requests, please try again later.'`; a `handler` replaces both; - **`legacyHeaders`** defaults to `true` (`X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`) and **`standardHeaders`** to `false`; most services set `standardHeaders: 'draft-8'` and `legacyHeaders: false`, and a blocked response carries `Retry-After` whenever either is on; - the built-in **memory store** lives in one process: counts are lost on restart and are not shared between instances, so with several instances behind the balancer each keeps its own count; the `store` option takes a shared store for that case; - **`passOnStoreError`** defaults to `false`, so if that store fails the limiter calls the Express error handler and blocks traffic ("fail closed"); `true` lets requests through and logs the error. ## Keys other than the address A `keyGenerator` can key by API key or user id for authenticated traffic. Two cautions apply: 1. Fall back with `ipKeyGenerator(req.ip)` rather than raw `req.ip`, so IPv6 clients are still grouped by subnet. 2. Supplying any custom `keyGenerator` switches off the proxy validation checks above, so a wrong `trust proxy` stops being reported. ## Keep the health route out A load balancer probes a health route constantly. Register a cheap `app.get('/healthz', ...)` before the limiter, or pass `skip: (req) => req.path === '/healthz'`, so probes neither consume a bucket nor get a 429 that takes the instance out of rotation. ## Confirming the fix After deploying the change, call a temporary route that returns `req.ip` from two different networks and check that each sees its own address, then send a burst from one of them and check that only that client receives 429 while the other is unaffected. The `RateLimit` response header from `standardHeaders` shows each client's remaining quota, which makes the check quick. Which algorithm to use, and how to share counters across regions, is the subject of the system-design material on rate limiting; this question is about how Express's `req.ip` feeds the library.

  • What changes when the same API runs as four instances behind the balancer?
    The default memory store keeps counts inside each process, so every instance limits independently and a client spread across instances can get up to about four times the configured allowance; restarts also reset the counts. Pass a shared store through the `store` option, and decide with `passOnStoreError` whether an unavailable store should block traffic (the default) or let it through.
  • Why might a team stop seeing the ERR_ERL_UNEXPECTED_X_FORWARDED_FOR warning without having fixed trust proxy?
    The proxy validations run inside the default key generator, so supplying a custom `keyGenerator`, for example to key by API key, skips them and a wrong `trust proxy` no longer shows up. They also run only once, on the first request the limiter counts: if that request had no `X-Forwarded-For`, such as a probe straight from the balancer, the warning never appears.
  • How would you protect a login route differently from the general API limit?
    Mount a second, stricter `rateLimit` instance on the login route only, with a longer `windowMs` and a small `limit`, and consider `skipSuccessfulRequests: true` so that only failed attempts, status 400 or above, count. Express's security guide also suggests counting consecutive failed attempts per user name and IP address, which a plain per-address window does not capture.

  • Setting trust proxy to true is how you fix a rate limiter behind a proxy.
  • express-rate-limit parses X-Forwarded-For itself, so trust proxy does not matter.
  • The default memory store shares hit counts across every instance.
  • The ERR_ERL_UNEXPECTED_X_FORWARDED_FOR error stops the app from starting.
  • With no options, express-rate-limit allows 100 requests per 15 minutes.