Sub topic 3
Where to Enforce: Client, Gateway, Middleware, or Service
This chapter assumes you know basic HTTP request and response concepts and can read Python. You should also know that production services usually run as several copies behind a load balancer. The previous chapters covered why limiters exist and what requirements shape them. This chapter covers where in the request path the check should run, because that choice decides what the limiter can see, what it protects, and how much it costs to operate.
The request path has several places to check
A request passes through several layers before it reaches business logic. A limiter can sit at any of them.
Each layer can reject a request. The earlier a request is rejected, the less work the system spends on it. The later the check runs, the more information it has about who is calling and what they are asking for.
Client-side limiting
A client-side limiter runs inside the caller, usually in an SDK or a batch job. The client throttles itself before it sends anything.
This is useful, but it is not a defense. You do not control the client, so a buggy, outdated, or hostile caller can ignore the limiter. Treat client-side limiting as good manners that you offer to well-behaved callers:
- Ship an SDK that queues or delays calls when the client approaches its quota.
- Have the SDK honor
Retry-Afterand back off with jitter after a 429. - Use it to protect your own downstream dependencies, such as a third-party API with a strict quota.
Never rely on it as the only layer. The server must enforce the limit on its own.
Edge and gateway limiting
An API gateway or reverse proxy sits in front of your services. Many gateways have built-in rate limiting, and managed edge products can also drop abusive traffic before it reaches your network.
Strengths:
- It rejects traffic before it consumes service CPU, database connections, or memory.
- It is one place to configure limits for many services.
- It protects services that have no limiter of their own, including legacy ones.
- It can see every request, so a global or per-customer cap is natural.
Weaknesses:
- It sees only what is in the request: headers, path, source address, and perhaps an API key or a validated token. It does not know what the request costs inside the service.
- Rules are usually coarse. "100 requests per second per API key" is easy. "Five report exports per hour, but unlimited reads" is harder to express.
- Gateway nodes are usually several instances, so you face the shared-state question covered in the distributed chapters.
- Traffic that bypasses the gateway, such as internal service-to-service calls, is not limited.
Service middleware
Middleware is code in the service's own request pipeline. It runs before the handler, extracts a key, asks a limiter whether to allow the request, and either continues or returns 429.
Strengths:
- It has full application context: the authenticated user, the plan they pay for, the endpoint, and the request body.
- Limits can follow business rules, and different routes can use different costs.
- It works the same in every environment, including local development and tests.
Weaknesses:
- Each service needs it, and each team can implement it differently. A shared library reduces this problem.
- Rejected requests have already used a connection and some parsing work. This is cheap compared with doing the real work, but it is not free.
- A per-process limiter in middleware only limits that one process. With ten instances, a limit of 100 per second can become up to 1,000 per second in total, depending on how the load balancer spreads traffic.
The following example is a small WSGI middleware. It is framework-free so you can run it as shown. The limiter is in memory and per process, which is enough to show the shape of the integration.
import time
class FixedWindowLimiter:
"""Allows at most `limit` requests per key in each window of `window` seconds."""
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.counters = {} # key -> (window_index, count)
def allow(self, key, now=None):
now = time.time() if now is None else now
index = int(now // self.window)
window_index, count = self.counters.get(key, (index, 0))
if window_index != index:
count = 0
if count >= self.limit:
self.counters[key] = (index, count)
return False
self.counters[key] = (index, count + 1)
return True
class RateLimitMiddleware:
def __init__(self, app, limiter, key_func, retry_after=1):
self.app = app
self.limiter = limiter
self.key_func = key_func
self.retry_after = retry_after
def __call__(self, environ, start_response):
key = self.key_func(environ)
if not self.limiter.allow(key):
body = b"Too Many Requests\n"
start_response("429 Too Many Requests", [
("Content-Type", "text/plain"),
("Content-Length", str(len(body))),
("Retry-After", str(self.retry_after)),
])
return [body]
return self.app(environ, start_response)
def hello(environ, start_response):
start_response("200 OK", [("Content-Type", "text/plain")])
return [b"ok\n"]
app = RateLimitMiddleware(
hello,
FixedWindowLimiter(limit=2, window=3600),
key_func=lambda environ: environ.get("REMOTE_ADDR", "unknown"),
)
def call(address):
result = {}
def start_response(status, headers):
result["status"] = status
b"".join(app({"REMOTE_ADDR": address}, start_response))
return result["status"]
print([call("10.0.0.1") for _ in range(3)])
print(call("10.0.0.2"))The first line prints two 200 OK statuses followed by 429 Too Many Requests. A different address has its own counter, so the second line prints 200 OK. The key function is a separate parameter on purpose. Choosing the key is a different decision from choosing where to run the check.
Comparing placements
| Placement | Sees | Protects against | Main risk |
|---|---|---|---|
| Client SDK | Its own calls only | Self-inflicted overload, third-party quota breaches | Can be bypassed |
| Edge / CDN | Source address, path, headers | Floods, scraping, crude abuse | Little identity or cost knowledge |
| API gateway | Headers, API key, token claims | Per-customer overuse across all services | Coarse rules, shared state needed |
| Service middleware | Full request and user context | Per-plan and per-endpoint abuse | Duplicated effort, per-process counts |
| Inside handler | Cost of the specific operation | Expensive operations, downstream limits | Work already started |
Combining layers
Most real systems use more than one layer, and each layer has a different job:
- The edge drops obvious floods by address with a generous limit.
- The gateway enforces per-API-key limits, which are the numbers you publish to customers.
- Service middleware enforces rules that need application context, such as per-endpoint costs.
- Handler code guards a scarce resource, such as a connection pool or a downstream API quota.
Set the outer limits looser than the inner ones. If the gateway allows 1,000 requests per second and a service allows 100, the gateway is only a safety net, and the service produces the errors callers see. Keep the 429 format the same across layers so clients handle every rejection the same way.
Avoid counting the same request twice against the same quota in two layers. If both the gateway and the service decrement a customer's budget, the customer's real limit is half of what you documented.
Choosing a placement
Ask these questions in order:
- Does the limit need information that exists only after authentication or inside the service? If yes, enforce in middleware or the handler.
- Is the goal to shed load before it costs you anything? If yes, add an edge or gateway layer.
- Do many services share one customer quota? If yes, enforce it in the gateway or a shared limiter service so one place owns the count.
- Can traffic reach a service without passing the gateway? If yes, the service needs its own limit.
Common mistakes
- Relying only on a client-side limiter.
- Running a per-process limiter behind a load balancer and publishing its number as a global limit.
- Limiting at the gateway but leaving internal routes open to direct calls.
- Setting inner limits higher than outer ones, so the inner layer never triggers.
- Returning a different error format from each layer.
Exercise
Your service runs as 8 identical instances behind a load balancer. Each instance has in-memory middleware that allows 100 requests per minute per API key. You document "100 requests per minute" to customers. What does a customer actually get, and what are two ways to fix the mismatch?
Show answer
With round-robin balancing, one key can send up to about 800 requests per minute in total (100 per instance), and the real number varies with how traffic is spread. One fix is to move the count to shared state, such as Redis, so all instances update the same counter. Another is to enforce the published limit in a gateway layer that holds the per-key count, and keep the instance limits only as a looser safety net. A third option is to divide the limit by the instance count (about 12 per instance), but this is inaccurate when traffic is uneven or when instances scale up and down.
Exercise
A team adds a rate limit of 500 requests per minute per customer at the gateway and the same 500 in service middleware. Both layers count each request. Customers report being cut off earlier than expected at times. Give one possible cause and a change that fixes it.
Show answer
The two layers count independently and with different window boundaries, so bursts that fit one layer's window can exceed the other's. Also, if the service key differs from the gateway key (for example, per user versus per API key), the service may reject a single user earlier. The fix is to give each layer a distinct job: set the gateway to the published customer limit and set the service limit higher, or make it a per-endpoint or per-cost rule, so it only fires for cases the gateway cannot see.