Why I Built My Own Rate Limiting Library for FastAPI
This was originally posted on my blog . I was not planning to build a rate limiting library. I had a FastAPI project, I needed rate limiting, I reached for SlowAPI, which is the most popular choice for FastAPI, and wired it up. Took maybe 20 minutes. Then I started actually using it. The request: Request problem The first thing that got to me was the request: Request requirement. SlowAPI's decorator needs access to the request to extract the client IP or user ID, and the only way it can get that is if your route function accepts it as a parameter. So every rate-limited route ends up looking like this: @app.get ( " /items " ) @limiter.limit ( " 10/minute " ) async def get_items ( request : Request ): return await fetch_items () That request: Request is not doing anything. fetch_items() does not use it. It's there purely because SlowAPI needs it. Small thing, but it bothered me — I like function signatures that say exactly what they need, and this one was lying. The header injection problem I could live with that. The thing I could not live with was the header injection. Rate limit headers are genuinely useful — X-RateLimit-Remaining tells clients when to back off, Retry-After tells them how long to wait. Standard stuff. So I enabled SlowAPI's header injection and immediately hit a wall: every rate-limited route now had to return a Response object directly. Not a dict. Not a Pydantic model. A Response . The moment you enable header injection, SlowAPI expects to work with an actual response object, and if your route returns anything else it just breaks. So I was suddenly doing this: @app.get ( " /items " ) @limiter.limit ( " 10/minute " ) async def get_items ( request : Request , response : Response ): items = await fetch_items () return JSONResponse ( content = jsonable_encoder ( items )) Which is annoying because one of the things I actually like about FastAPI is that you declare a return type, FastAPI handles the serialization, and your OpenAPI schema just works. Sl