Wire it into FastAPI
A dependency, not middleware
You met Depends back in module 24 for pulling a DB session into a route. A rate limiter fits the same shape: a small async function that runs before the route body, has the request available (to read an API key or the client's IP), and can short-circuit the request by raising before the route ever executes.
Middleware is the alternative โ it wraps every request to the app, which is right for something truly global (logging, CORS). A Depends limiter is right when different routes need different limits, or some routes need no limit at all (a health check shouldn't be rate-limited alongside a search endpoint). Route-scoped control is why most FastAPI rate limiters, including this one, are dependencies.
The key you rate-limit on matters: an API key if clients authenticate with one, request.client.host (their IP) if they don't. Either way, that key is what goes into the Redis counter key from lesson 3 โ one counter per client, not one global counter for the whole API.