A FastAPI endpoint can be hammered by a script firing thousands of requests within minutes, slowing your server down or taking it offline completely. Rate limiting caps the number of requests from each IP over a time window and returns a 429 error when the limit is exceeded. With FastAPI, the SlowAPI library lets you attach rate limits with a single decorator — @limiter.limit("5/minute") — no complex middleware, no Redis needed at small scale.
The Problem
A “natural” FastAPI login endpoint like the one below has zero protection against brute-force attacks: an attacker can try as many passwords as they want, and every request runs the full password-hashing logic, burning your server’s CPU.
from fastapi import FastAPI, HTTPExceptionapp = FastAPI()@app.post("/login")async def login(username: str, password: str): # No rate limit: an attacker can try # thousands of passwords per minute if not check_password(username, password): raise HTTPException(status_code=401) return {"token": "..."}
The “count requests in a dict” approach sounds simple but quickly turns into spaghetti: expiring counters, resetting per time window, and counts that don’t match across multiple workers. SlowAPI packages all of that into a few lines.
The Solution
Install SlowAPI:
pip install slowapi
Declare the limiter once, then attach per-endpoint limits with the decorator:
from fastapi import FastAPI, Request, HTTPException from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address from slowapi.errors import RateLimitExceeded def check_password(username: str, password: str) -> bool: # Demo: in practice use secrets.compare_digest # to compare securely against a hashed password return password == "correct-password" # Default limit for the whole app: 100 requests/minute/IP limiter = Limiter(key_func=get_remote_address, default_limits=["100/minute"]) app = FastAPI() app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) @app.post("/login") @limiter.limit("5/minute") # login limited to 5 attempts/minute/IP async def login(request: Request, username: str, password: str): if not check_password(username, password): raise HTTPException(status_code=401) return {"token": "..."} @app.get("/health") @limiter.exempt # health check endpoint is exempt from limits async def health(request: Request): return {"status": "ok"}
Why is this better than rolling your own? First, default_limits sets a baseline for every endpoint, while @limiter.limit lets you tighten sensitive routes like /login and /register. Second, SlowAPI returns a standard 429 with the message “Rate limit exceeded: 5 per 1 minute”, so clients know to wait. Third, internal endpoints like health checks are exempted with @limiter.exempt instead of special-case conditionals.
The code above was tested for real with TestClient: the first 5 wrong logins returned 401, the 6th was blocked with 429 (“Rate limit exceeded: 5 per 1 minute”), while /health stayed wide open.
Apply It to Your Project
In a real project, tighten money- and auth-related routes (/login, /register, /forgot-password) to 5–10 requests/minute, and relax read-heavy endpoints to 100–300 requests/minute. SlowAPI counts in memory by default — fine for a single worker; with multiple workers or in production, configure Redis as the counter backend so all workers share the same counts. And do log IPs that keep hitting 429: that’s usually a bot or someone probing your system.
Related Posts
- FastAPI: Protect Routes with a Reusable JWT/OAuth2 Dependency — No Repeated Auth Code
- FastAPI: Write Custom Middleware to Measure Request Time and Log in 5 Minutes
- Django REST Framework: Permissions and Anti-Spam API with Permission + Throttling in 5 Minutes
Frequently Asked Questions
Does a 429 rate limit annoy real users?
No, as long as you set sensible limits. Real users rarely send more than 100 requests/minute; only bots and attack scripts hit the ceiling. Five login attempts per minute is still plenty for a real person.
Where does SlowAPI store its counters?
In memory of the running process by default — simple, but each worker counts separately. When you scale to multiple workers, configure Redis as the storage backend so all workers share one counter.
My app runs behind Nginx — which IP does SlowAPI count?
get_remote_address reads the IP from the direct connection, so behind a proxy it sees Nginx’s IP instead of the client’s real IP. You need to read the X-Forwarded-For header sent by your proxy (trust only your own proxy, never the header from an untrusted client) to limit the right user IP.
Does SlowAPI slow down requests?
Barely. Incrementing an in-memory counter costs well under a millisecond. Overhead only becomes noticeable with a remote Redis backend — and that’s still far cheaper than one brute-force request hitting your password-hashing logic.
Can SlowAPI limit WebSockets?
No — SlowAPI applies to HTTP requests only. A WebSocket is a long-lived connection, so you must limit it yourself (e.g. concurrent connections per IP, or messages per second) with custom logic in the handler.
References
- SlowAPI documentation — slowapi.readthedocs.io
- SlowAPI GitHub repository — github.com/laurentS/slowapi
