Sub topic 4
Choosing the key: user, API key, IP address, or endpoint
This chapter assumes you know the limiter algorithms from earlier chapters and basic HTTP headers. A limiter counts requests per key. The key decides who shares a budget, so a poor key blocks innocent clients or lets abusers through.
What a key identifies
The key is a string built from the request, such as user:42 or ip:203.0.113.9. Each distinct key gets its own counter or bucket. Pick the most specific identity you can trust.
| Key | Strength | Weakness |
|---|---|---|
| User ID | Follows a person across devices | Only known after authentication |
| API key | Easy to meter per customer or app | One leaked key shares one budget, and one customer may use many keys |
| IP address | Available before login | Shared by offices and mobile carriers (NAT), and attackers can rotate IPs |
| Endpoint | Protects expensive routes | Does not identify who is calling |
Combine identity and endpoint
Real limiters usually join two parts: who is calling and what they call. A login route might allow 5 requests a minute per IP, while a read route allows 1000 a minute per API key. Including the route in the key keeps a cheap endpoint from using the budget of an expensive one.
import hashlib
def rate_limit_key(headers, remote_ip, route):
"""Build a limiter key from the best available identity plus the route."""
user_id = headers.get("X-User-Id") # set by your auth layer, never by the client
api_key = headers.get("X-Api-Key")
if user_id:
identity = f"user:{user_id}"
elif api_key:
digest = hashlib.sha256(api_key.encode()).hexdigest()[:16]
identity = f"key:{digest}" # hash so the secret never lands in Redis
else:
identity = f"ip:{remote_ip}" # fallback for anonymous traffic
return f"{identity}:{route}"
print(rate_limit_key({"X-Api-Key": "secret-123"}, "203.0.113.9", "/search"))
print(rate_limit_key({}, "203.0.113.9", "/login"))The function falls back from strongest to weakest identity.
Pitfalls with IP addresses
Behind a load balancer, the TCP peer address is the balancer, not the client. If you key on it, all users share one budget. Read the client address from X-Forwarded-For, but only trust the entries added by your own proxies. A client can send a fake header, and if you trust it, they pick their own key and escape the limit.
Other points to check:
- Shared IPs. Set IP limits higher than per-user limits, because one address may be a whole company.
- IPv6. One user can hold a whole /64 range. Key on the /64 prefix, not the full address.
- Key cardinality. Every distinct key costs memory in the store. Attackers can create millions of keys with spoofed identities, so set an expiry on each key, as the Redis script in this tutorial does.
- Anonymous traffic. Limit it more tightly than authenticated traffic, since it is the cheapest to abuse.
Exercise
Your API sits behind a load balancer. After you key the limiter on the TCP peer address, users report that they are rejected after only a few requests, and the rejections hit many different users at once. What is the likely cause, and what is the fix?
Show answer
The TCP peer address is the load balancer, so every user shares one key and one budget. Read the client IP from X-Forwarded-For, trusting only the entries added by your own proxies. Better, use the authenticated user ID or API key when one exists and use the IP only as a fallback for anonymous traffic.