Sub topic 3
Where to enforce: client, gateway, middleware, or service
This chapter assumes you know basic HTTP, can read Python, and know that services usually run as several instances behind a load balancer. Where you enforce a limit decides what the limiter can see, what it can protect, and how much shared state it needs.
The four enforcement points
A request can pass through up to four places before it reaches your business logic.
- Client. An SDK throttles its own calls. This is polite and saves round trips. You cannot rely on it, because anyone can bypass the SDK.
- Gateway. A reverse proxy or API gateway rejects requests before they reach your servers. It protects every service behind it and handles the highest volume. It sees only what is in the request: headers, path, IP address, and API key.
- Middleware. Code inside your application runs before the handler. It can use parsed data such as the authenticated user or the account plan.
- Service logic. A handler checks a limit itself, for example "5 password resets per hour per account" or "10 exports per day". Only the handler knows the cost of the operation.
Comparing them
| Point | Sees | Protects | Trade-off |
|---|---|---|---|
| Client | Own traffic only | Server from honest clients | Not enforceable |
| Gateway | Raw request | All backends, cheaply | Little business context |
| Middleware | Authenticated identity | One service | Request already reached the app |
| Service logic | Full business context | Expensive operations | Limit rules spread through the code |
A middleware example
This WSGI middleware limits each IP address to a fixed number of requests per window. It keeps counters in process memory, so each instance counts separately.
import time
class RateLimitMiddleware:
def __init__(self, app, limit, window):
self.app = app
self.limit = limit
self.window = window
self.counters = {} # key -> (window_index, count)
def __call__(self, environ, start_response):
key = environ.get("REMOTE_ADDR", "unknown")
index = int(time.time() // self.window)
window_index, count = self.counters.get(key, (index, 0))
if window_index != index:
count = 0
if count >= self.limit:
start_response(
"429 Too Many Requests",
[("Content-Type", "text/plain"), ("Retry-After", str(self.window))],
)
return [b"rate limit exceeded\n"]
self.counters[key] = (index, count + 1)
return self.app(environ, start_response)
def app(environ, start_response):
start_response("200 OK", [("Content-Type", "text/plain")])
return [b"ok\n"]
limited = RateLimitMiddleware(app, limit=2, window=60)
def call():
status = []
limited({"REMOTE_ADDR": "203.0.113.7"}, lambda s, h: status.append(s))
return status[0]
print([call() for _ in range(3)]) # ['200 OK', '200 OK', '429 Too Many Requests']With three instances behind a load balancer, a client could get up to three times the limit. Fixing that needs shared state, which a later chapter covers.
Choosing in practice
Layer the points instead of picking one. A common setup uses a coarse per-IP limit at the gateway to absorb floods. Middleware applies per-user or per-API-key limits. Handlers guard a few costly operations.
Reject as early as you can, because a rejected request that never reaches the app costs almost nothing. Move the check later only when the rule needs information that earlier layers do not have.
Exercise
Your API allows 100 requests per minute per authenticated user, but the gateway only sees an opaque bearer token and the client IP. Where should the per-user limit live, and what limit would you still put at the gateway?
Show answer
Put the per-user limit in middleware (or at a gateway that can validate the token and extract the user ID), because it needs the authenticated identity. At the gateway, keep a coarse per-IP limit to absorb floods before they reach the application.