Sub topic 4
Choosing the Key: User, API Key, IP Address, or Endpoint
Prerequisites
This chapter assumes you know the limiter algorithms from the earlier chapters, especially the fixed window counter and the token bucket. It also assumes you understand HTTP headers and how a service sits behind a load balancer. Every algorithm so far answers "is this caller over the limit?" This chapter covers what "this caller" means.
What the key is
A limiter stores one piece of state per key, such as a counter or a bucket. All requests that map to the same key share one budget. Requests that map to different keys never affect each other.
The key therefore decides three things:
- Fairness. Who shares a budget with whom.
- Memory. How many counters you store. One per user is cheap. One per IP address per endpoint is larger, and attackers can inflate it.
- Resistance to abuse. How easily a caller can get a fresh budget by changing something.
Candidate identities
| Key | Strength | Weakness | Typical use |
|---|---|---|---|
| User ID | Matches billing and fairness. Hard to evade without new accounts. | Only known after authentication. | Logged-in product traffic |
| API key ID | Per-integration budgets. A leaked key can be revoked and limited alone. | One customer may hold many keys. | Public APIs |
| IP address | Available before authentication. | Shared by many users (NAT). One attacker can use many addresses. | Login, signup, anonymous traffic |
| Endpoint (route) | Protects expensive operations. | Says nothing about who is calling. | Combined with another key |
| Global (no identity) | Protects total capacity. | One abuser can starve everyone. | Backstop only |
No single choice works everywhere. Most systems use a combination, as the later sections show.
Authenticated identities
If you can identify the caller, prefer that identity over the IP address. Two details matter:
- Use the key's identifier, never the secret. Store
key_idin the limiter state. A raw API key in a Redis key name ends up in logs, monitoring dumps, andKEYSoutput. - Decide what an account owns. If a customer can create many API keys and each gets its own budget, the customer can multiply their quota. Limit by the owning account (tenant) when the budget is a commercial entitlement. Limit by key only when you want integrations isolated from each other.
Authentication has to run before the limiter for these keys to exist. That ordering has a cost. Unauthenticated floods still reach your authentication code, so you need an IP-based limit in front of it.
IP addresses: useful and unreliable
The IP address is the only identity you have for anonymous requests, but it has three well-known problems.
- Sharing. Offices, universities, and mobile carriers put thousands of users behind one public address (NAT). A tight per-IP limit blocks innocent users together.
- Rotation. An attacker with a botnet or a proxy pool sends one request from each of thousands of addresses. A per-IP limit alone never triggers.
- IPv6. A single customer often controls an entire
/64block, which is 2^64 addresses. Treating each address as a separate key gives that customer unlimited fresh budgets. Normalize IPv6 addresses to their/64prefix.
Reading the real client address
Behind a load balancer, the TCP peer is the balancer, not the client. The client address usually arrives in the X-Forwarded-For header. Each proxy appends the address of the peer it received the request from. A client can also send its own X-Forwarded-For value, so the leftmost entries are untrusted.
The reliable method is to count from the right. You know how many proxies you operate, so skip exactly that many entries from the end.
import ipaddress
def client_ip(remote_addr, forwarded_for, trusted_hops):
"""Return the client address as seen by the first proxy we operate.
remote_addr: the TCP peer of this process.
forwarded_for: the X-Forwarded-For header value, or None.
trusted_hops: number of proxies we run between the internet and this
process, including the immediate peer.
"""
entries = [e.strip() for e in forwarded_for.split(",")] if forwarded_for else []
chain = entries + [remote_addr]
index = len(chain) - 1 - trusted_hops
raw = chain[max(index, 0)]
try:
ip = ipaddress.ip_address(raw)
except ValueError:
return "unknown"
if ip.version == 6:
return str(ipaddress.ip_network(f"{ip}/64", strict=False))
return str(ip)
# The client lies in X-Forwarded-For; our load balancer appended the real peer.
print(client_ip("10.0.0.5", "203.0.113.7, 198.51.100.2", trusted_hops=1))
print(client_ip("10.0.0.5", None, trusted_hops=0))
print(client_ip("10.0.0.5", "2001:db8:1:2:aaaa:bbbb:cccc:dddd", trusted_hops=1))The first call prints 198.51.100.2, the address our balancer actually saw, and ignores the spoofed 203.0.113.7. The third call prints 2001:db8:1:2::/64.
The "unknown" fallback puts all malformed requests into one shared bucket. That is a deliberate choice. A garbage address should not earn a fresh budget.
The endpoint dimension
The endpoint is rarely a key on its own. It is a second part of a composite key, so one caller gets separate budgets for separate operations.
- A search endpoint that costs 50 ms of database time and a health check that costs microseconds should not share a budget.
- Login and password-reset routes need strict limits per IP and per target account. A global per-user limit of 1000 requests per minute would still allow thousands of password guesses.
Use the route template (/users/{id}), not the raw path (/users/8841). Raw paths create one key per resource ID, which wastes memory and gives callers a new budget for every ID they try.
Another option is to keep one budget per caller and charge different costs per endpoint. The token bucket supports this through its cost argument. This is simpler to explain to customers ("1000 units per minute"), but it makes the per-endpoint protection less direct.
Choosing the identity per request
A common design picks the strongest identity available and falls back in order, then adds the route.
def limiter_key(req, trusted_hops=1):
"""Build a namespaced key from the strongest identity available."""
route = req["route"] # a template such as "/orders/{id}", not a raw path
if req.get("account_id"):
return f"rl:acct:{req['account_id']}:{route}"
if req.get("user_id"):
return f"rl:user:{req['user_id']}:{route}"
ip = client_ip(req["remote_addr"], req.get("xff"), trusted_hops)
return f"rl:ip:{ip}:{route}"
print(limiter_key({"account_id": "a17", "route": "/search"}))
print(limiter_key({"remote_addr": "10.0.0.5", "xff": "198.51.100.2", "route": "/login"}))This prints rl:acct:a17:/search and rl:ip:198.51.100.2:/login. The prefix (acct, user, ip) keeps the namespaces apart, so a user ID can never collide with an IP string.
Common errors
- Trusting a client-controlled value. Headers such as
X-Forwarded-For, a user-suppliedX-Client-Id, or an unauthenticated JSON field let callers choose their own key. - Unbounded key cardinality. Raw URLs, query strings, and user-agent strings as key parts produce millions of one-use keys. Set a TTL on every key and use route templates.
- Switching identity mid-session. A caller sends 100 anonymous requests under their IP, then logs in and gets a new, empty user budget. Decide whether the anonymous budget carries over, and apply a separate IP limit to login itself.
- One IP limit for everything. A limit tight enough to stop scrapers will block a university campus. Allow higher per-IP limits for authenticated traffic and keep strict IP limits for sensitive routes.
- Penalizing the wrong party. A limit keyed by target account (for login attempts) lets an attacker lock a victim out. Pair it with a per-IP limit and consider a delay instead of a hard lock.
Exercise
Your API sits behind one load balancer you operate. A request arrives with TCP peer 10.0.0.9 and the header X-Forwarded-For: 1.2.3.4, 198.51.100.20. Which address should the limiter use as the client, and why? What would change if there were two proxies you operate in front of the service?
Show answer
Use 198.51.100.20. With one trusted hop, the chain is [1.2.3.4, 198.51.100.20, 10.0.0.9], and the client is the entry just before the immediate peer, which is the address our load balancer saw. The entry 1.2.3.4 was supplied by the client and cannot be trusted. With two trusted proxies, skip two entries from the right, so the chain would be read at index len(chain) - 1 - 2, giving 1.2.3.4. That is correct only if both proxies appended entries and 1.2.3.4 was added by the first of them.
Exercise
A customer on your public API creates 50 API keys and each key has its own limit of 100 requests per minute. What is the problem, and how do you fix it?
Show answer
The customer can use 5,000 requests per minute, so the per-key limit no longer reflects their entitlement. Key the limiter on the owning account instead of the key ID. If you still want isolation between integrations, keep a smaller per-key limit in addition to the account limit.