Keys¶
A limit counts requests for someone. The key decides who. It is a function
that looks at a request and returns a string naming the caller, such as
"ip:203.0.113.7" or "user:42". Requests with the same key share one
allowance.
The caller's address¶
With no key, a limit uses client_ip: the address
that connected to your server. That is the real caller only when nothing sits
between the two.
Behind a proxy or load balancer¶
Behind a proxy every connection comes from the proxy, so every caller would
share one allowance. The proxy passes the caller's address on in the
X-Forwarded-For header. Anyone can send that header, though, and a limiter
that believed it would let a caller choose a new identity for every request.
So ClientIP ignores the header unless the connection
comes from an address you have named as your own proxy:
# The addresses of your own load balancer. Only connections that come from
# these are trusted to say who the real caller is.
caller = ClientIP(trusted_proxies=["10.0.0.0/8"])
@app.get("/search", dependencies=[Depends(limiter.limit("5/minute", key=caller))])
async def search(q: str = "") -> dict[str, str]:
return {"query": q}
The header is read from right to left, skipping your proxies. The first address that is not yours is the caller. Anything further left is only what the caller claimed.
If your server rewrites the address itself
Some servers replace the connection's address with the forwarded one before
your app sees it. uvicorn does this for the proxies listed in
--forwarded-allow-ips, which is 127.0.0.1 unless you change it. The
address is then already the caller's, and plain client_ip is enough.
List your proxies' addresses there. Do not use * unless nothing can reach
the app except through the proxy: with *, uvicorn believes any connection
and takes the first address in the header, which is the one the caller
wrote.
Over a Unix socket¶
When a proxy talks to your app through a socket file, the server has no address
for the other end, and client_ip cannot name anyone. A limit keyed on it
fails each request and says why.
Tell ClientIP that the socket is your proxy, with
key=ClientIP(trust_unix_socket=True). The caller is then read from
X-Forwarded-For, as it is behind any proxy you trust. Only a process on the
same machine can connect to a socket file, which is what makes this safe to
say. If there are more proxies in front of that one, name them in
trusted_proxies as well.
IPv6 callers¶
An IPv6 subscriber usually controls a whole /64, which is more addresses than
a limiter could ever count. Callers on IPv6 are therefore grouped by their
/64. ClientIP(ipv6_prefix=56) groups more widely, and ipv6_prefix=128
counts exact addresses.
A request header¶
RequestHeader("X-Tenant") names the caller by
the value of a header. The store holds a digest of the value, never the value
itself, so nothing sensitive ends up in the store or in logs.
Only for values the caller cannot choose
A key is only as good as the caller's inability to change it. If a header can hold anything, every new value is a new caller with a fresh allowance. That includes an API key header on a route that does not check the key first: someone guessing keys would never be limited.
Use RequestHeader for a header your own gateway sets, such as one that
carries the tenant. For credentials, key on what your authentication found,
as Limiting by user does.
A function of your own¶
A key can be any function that returns a string. In FastAPI it is resolved as a dependency, which means it can use the signed-in user. Limiting by user shows how.
Write keys with async def unless they do blocking work. FastAPI runs a
dependency written with a plain def on a worker thread, which costs more than
a small function is worth. The built-in keys are async for the same reason,
so a key of your own that uses one awaits it: await client_ip(request).
In a Starlette app without FastAPI, a key is called with the request and
nothing else. authenticated_user is a
ready-made one for Starlette's own authentication.
Without FastAPI says more.
When a key has no answer¶
A key may return None, or an empty string, meaning it cannot tell who the
caller is. RequestHeader("X-Tenant") does when the header is missing, and
client_ip does over a Unix socket.
By default the request then fails with
MissingKeyError, which reaches the caller as
a 500 and names the route in your logs. This is loud on purpose. A key that
quietly named nobody would switch the limit off, or put every such caller in
one shared bucket, and you would find out during an incident.
There are two ways to say what you want instead:
- Fall back to another key.
first_of(user_key, client_ip)counts a signed-in caller by account and anyone else by address. Limiting by user shows it. - Say the limit does not apply.
limiter.limit("5/minute", key=..., on_missing_key="skip")lets such requests through without counting them.