- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Authentication, Authorization and Security
- API Security Best Practices
- Rate Limiting
On this page
Rate Limiting in FastAPI with SlowAPI
Published on August 14, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Without any limit on how often a client can call an endpoint, a single script can hammer a /login route thousands of times a minute trying passwords, scrape an entire dataset through repeated calls, or simply overwhelm the server until it stops responding to anyone. Rate limiting caps how many requests a client can make within a given time window and returns 429 Too Many Requests once that cap is exceeded — a small piece of middleware that closes off several of the most common ways an API gets abused. FastAPI doesn't include this out of the box, and SlowAPI is the library most commonly reached for to add it, though getting a production-correct setup means going a bit further than a bare @limiter.limit() decorator.
Why Rate Limiting Matters​
An API with no rate limiting at all is exposed to several distinct forms of abuse at once. Brute-force attacks repeatedly try passwords against a login endpoint until one works. Credential stuffing tests username/password pairs stolen from other breaches at scale, hoping for password reuse. Denial-of-service floods the server with requests until it can no longer serve legitimate users. Resource exhaustion drives up infrastructure cost through automated scraping or bulk API abuse, even without malicious intent behind it. Each of these looks different in its motivation, but all of them share the same underlying weakness: nothing stops a single client from sending requests as fast as it possibly can.
Installing SlowAPI​
pip install slowapi
SlowAPI wraps the limits library — a general-purpose rate-limiting toolkit not specific to any web framework — and adapts it specifically for Starlette and FastAPI applications.
Basic Setup​
from fastapi import FastAPI, Request
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
get_remote_address extracts the client's IP from the request and is what SlowAPI uses by default to identify which client a given request belongs to — every rate limit is enforced per distinct value this function returns. app.state.limiter = limiter attaches the limiter to the app so SlowAPI's internals can reach it from anywhere in the request-handling pipeline, and the exception handler is what actually converts a limit being hit into an HTTP 429 response.
Applying Limits to Individual Endpoints​
@app.post("/auth/login")
@limiter.limit("5/minute")
async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
return {"message": "Login attempt"}
@app.get("/items")
@limiter.limit("100/minute")
async def get_items(request: Request):
return {"items": []}
Two requirements are easy to miss and both cause the limit to silently not apply if skipped. The endpoint function needs request: Request declared as a parameter — SlowAPI reads the request object directly to identify the caller and track the count, and without it present, the decorator has nothing to hook into. @limiter.limit(...) needs to sit below the route decorator (@app.post, @router.get, and so on), not above it — decorator order in Python determines the order operations actually apply in, and reversing it breaks the limiter's ability to wrap the route correctly.
Global Default Limits​
Applying a baseline limit to every route without decorating each one individually:
from slowapi.middleware import SlowAPIMiddleware
limiter = Limiter(
key_func=get_remote_address,
default_limits=["200/minute"],
)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)
default_limits applies automatically to any route without its own explicit @limiter.limit(). A route that does declare its own limit overrides the global one entirely rather than stacking with it, and @limiter.exempt opts a specific route out of the global limit altogether when it genuinely needs no cap at all.
Writing an Accurate Custom 429 Response​
The default handler returns a plain-text body, which doesn't fit a JSON API well. Writing a custom one correctly requires understanding where a genuinely accurate Retry-After value actually comes from — it isn't something read off the incoming request, since a client has no reason to send that header on a request it's making for the first time. SlowAPI computes the correct countdown internally and exposes it through request.state.view_rate_limit, which the limiter's own internal _inject_headers method turns into the correct X-RateLimit-* and Retry-After headers:
from fastapi import Request
from fastapi.responses import JSONResponse
from slowapi.errors import RateLimitExceeded
async def rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded) -> JSONResponse:
response = JSONResponse(
status_code=429,
content={
"error": "Too many requests",
"detail": f"Rate limit exceeded: {exc.detail}",
},
)
# Reuses SlowAPI's own accurate Retry-After calculation
return request.app.state.limiter._inject_headers(response, request.state.view_rate_limit)
app.add_exception_handler(RateLimitExceeded, rate_limit_exceeded_handler)
Reusing _inject_headers this way means the custom handler gets a genuinely accurate Retry-After value — computed from the actual rate-limit window state SlowAPI is already tracking — rather than a hardcoded fallback that doesn't reflect how much time is actually left. Including Retry-After at all matters beyond just correctness: it's part of the HTTP specification for 429 responses under RFC 6585, and well-behaved clients read it to back off automatically rather than retrying immediately and hitting the same limit again.
Scaling Rate Limits Across Multiple Workers with Redis​
By default, SlowAPI tracks request counts in memory, which works for a single development process and breaks down the moment an API runs across more than one worker or server instance — each process keeps its own separate counter, with no shared view of the total request count between them. A production deployment running four Gunicorn workers with in-memory tracking is effectively four independent rate limiters, each only ever seeing a quarter of the real traffic, which means the actual enforced limit ends up roughly four times higher than configured.
pip install slowapi redis
limiter = Limiter(
key_func=get_remote_address,
default_limits=["200/minute"],
storage_uri="redis://localhost:6379", # shared across all workers and instances
)
With a Redis backend, every worker process reads and writes the same shared counters, so a limit configured as 200/minute is actually enforced as 200/minute across the whole deployment, regardless of how many processes are serving traffic.
Getting the Real Client IP Behind a Reverse Proxy​
get_remote_address reads its value from request.client.host. Behind a reverse proxy like NGINX, that value is the proxy's own IP address — typically 127.0.0.1 — not the real client's, since the proxy is what actually connects to the FastAPI process. Left unaddressed, every distinct client ends up sharing the exact same rate-limit counter, since they all appear to be the same "client" as far as SlowAPI can tell — which makes the limit either far too strict for legitimate traffic sharing that one counter, or effectively meaningless depending on how the numbers land.
The fix is making Uvicorn trust the proxy's forwarded headers, not TrustedHostMiddleware — that middleware validates the Host header specifically to guard against Host header injection attacks, and has nothing to do with client IP resolution. The correct tool is Uvicorn's own proxy-header handling:
uvicorn main:app --proxy-headers --forwarded-allow-ips="127.0.0.1"
This trusts X-Forwarded-For from a proxy running on 127.0.0.1 — the same host as the application — and updates the client address FastAPI sees accordingly, which is what get_remote_address reads from. For a reverse proxy running in a separate container or on a separate host, that proxy's actual address needs to be listed in --forwarded-allow-ips instead of the default. The NGINX side of this needs the matching headers actually being sent:
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
}
With both sides configured, get_remote_address correctly resolves to each distinct client's real IP again, and rate limits apply per actual client rather than collapsing everyone behind the proxy into one shared counter.
Applying Stricter Limits to Authentication Endpoints​
/auth/login and /auth/signup are the primary targets for brute-force and credential-stuffing attempts specifically, which makes a blanket application-wide limit insufficient protection for these two routes on its own — a limit generous enough for normal API usage elsewhere is usually far too generous for a login attempt:
@app.post("/auth/login")
@limiter.limit("5/minute")
async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
...
@app.post("/auth/signup")
@limiter.limit("3/minute")
async def signup(request: Request, user_data: UserRegisterSchema):
...
A limit an order of magnitude tighter than general endpoints — five attempts a minute rather than a hundred — still allows a legitimate user who mistypes a password a couple of times, while making automated credential-guessing at any meaningful scale impractical.
A Note on SlowAPI's Maturity​
SlowAPI's own documentation describes itself candidly as "alpha quality code" where "the API may change, and things may fall apart" — despite that, it's confirmed to run in various production setups handling meaningful traffic, and remains the most commonly reached-for rate-limiting library in the FastAPI ecosystem. fastapi-limiter, a Redis-backed alternative built specifically around FastAPI's dependency injection system rather than adapted from a Flask library, is worth knowing about as an alternative — some in the community consider its design a better fit for FastAPI specifically. SlowAPI's broad adoption and the patterns covered above remain a reasonable, well-tested default; being aware that a maintained alternative exists is worth knowing before committing to either one for a large, long-lived project.
Key Takeaways​
SlowAPI closes a real gap FastAPI leaves open by design, but a correct production setup requires more than the bare decorator: request: Request has to be present in every rate-limited endpoint's signature, @limiter.limit() has to sit below the route decorator, and an in-memory backend needs replacing with Redis the moment more than one worker process is involved, or the configured limit silently becomes far looser than intended. A custom 429 handler is only genuinely accurate when its Retry-After value comes from SlowAPI's own tracked rate-limit state — reusing _inject_headers — rather than being read from a request header that a client would never actually send. And getting the real client IP behind a reverse proxy is a Uvicorn proxy-header trust problem, solved with --proxy-headers and --forwarded-allow-ips, not a TrustedHostMiddleware problem, since that middleware serves a completely different purpose.
Practice: Building the Full Configuration​
Combining every piece covered above into one working setup:
from fastapi import FastAPI, Request, Depends
from fastapi.responses import JSONResponse
from slowapi import Limiter
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
limiter = Limiter(
key_func=get_remote_address,
default_limits=["200/minute"],
# storage_uri="redis://localhost:6379", # uncomment for production
)
app = FastAPI()
app.state.limiter = limiter
async def rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded) -> JSONResponse:
response = JSONResponse(
status_code=429,
content={
"error": "Too many requests",
"detail": f"Rate limit exceeded: {exc.detail}",
},
)
return request.app.state.limiter._inject_headers(response, request.state.view_rate_limit)
app.add_exception_handler(RateLimitExceeded, rate_limit_exceeded_handler)
@app.post("/auth/login")
@limiter.limit("5/minute")
async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
return {"message": "Login attempt"}
@app.post("/auth/signup")
@limiter.limit("3/minute")
async def signup(request: Request, user_data: UserRegisterSchema):
return {"message": "Signup attempt"}
default_limits=["200/minute"] covers every route that doesn't declare its own limit, while /auth/login and /auth/signup override that default with their own, deliberately tighter values. rate_limit_exceeded_handler replaces SlowAPI's plain-text default with a JSON body while still reusing its accurate header calculation underneath.
Testing the login limit directly confirms the behavior end to end:
for i in {1..6}; do
curl -i -X POST http://127.0.0.1:8000/auth/login \
-d "username=test&password=wrong"
echo "---"
done
The first five requests return normally; the sixth returns 429 Too Many Requests with the custom JSON body and an accurate Retry-After header reflecting the actual remaining time on the one-minute window — not a fixed placeholder value.
Frequently Asked Questions​
I added @limiter.limit() to my route but it doesn't seem to do anything. Why?
The two most common causes are the endpoint missing request: Request as a parameter, or @limiter.limit() being placed above the route decorator instead of below it. SlowAPI needs direct access to the request object to track and identify the caller, and decorator order determines whether the limiter actually wraps the route correctly — both mistakes cause the limit to silently not apply, with no error raised.
Why does my rate limit seem much looser in production than it was during local testing?
This almost always means the app is running with multiple worker processes (e.g. several Gunicorn workers) while still using SlowAPI's default in-memory storage. Each worker keeps its own separate counter with no shared state, so a configured 200/minute limit across four workers behaves closer to 800/minute in practice. Switching to a Redis-backed storage_uri gives every worker a single shared counter.
All my users are hitting the same rate limit at the same time. Why?
This happens when the app runs behind a reverse proxy and request.client.host resolves to the proxy's own IP rather than each real client's IP — every request looks like it's coming from the same source, so they all share one counter. Configuring Uvicorn with --proxy-headers and the correct --forwarded-allow-ips value, alongside the proxy actually sending X-Forwarded-For, resolves this.
Should I use TrustedHostMiddleware to fix the client IP issue behind my reverse proxy?
No — TrustedHostMiddleware validates the Host header to prevent Host header injection attacks and has nothing to do with resolving the real client IP. The correct fix is Uvicorn's own proxy-header handling, enabled with --proxy-headers and configured with --forwarded-allow-ips set to the proxy's actual address.
Why is the Retry-After value in my custom 429 response always the same fixed number?
This happens when Retry-After is read from the incoming request's headers or hardcoded as a fallback, rather than computed from SlowAPI's actual tracked rate-limit state. Reusing the limiter's own _inject_headers method with request.state.view_rate_limit produces an accurate, dynamically calculated value instead of a static placeholder.
Can I apply more than one rate limit to the same endpoint?
Yes — stacking multiple @limiter.limit() decorators on the same route applies all of them simultaneously, and whichever limit is reached first is the one that triggers the 429 response. This is useful for combining a short burst limit with a longer sustained-usage limit on the same endpoint.
Does a route-specific @limiter.limit() add to the global default_limits, or replace it?
It replaces it for that specific route. A route with its own @limiter.limit() decorator no longer applies the global default at all — the two don't stack together. A route needs @limiter.exempt if it should be excluded from rate limiting entirely.
Is SlowAPI safe to use in a serious production application given it describes itself as 'alpha quality'?
It's confirmed to run in various production setups handling substantial traffic, and remains the most widely used rate-limiting library in the FastAPI ecosystem despite that description. It's a reasonable, well-tested default for most projects; for a large, long-lived system, it's still worth being aware that actively maintained alternatives like fastapi-limiter exist and are considered by some to be a better architectural fit for FastAPI specifically.
My limit is set to 5/minute but a client got a 429 after only 3 requests. Why?
Check whether default_limits is also configured on the Limiter and whether SlowAPIMiddleware is added to the app — in some SlowAPI versions, combining a route-specific limit with an active global default through the middleware has caused duplicated or conflicting rate-limit headers and counting. Removing SlowAPIMiddleware when only per-route decorators are used, or verifying header values directly in a response, helps isolate which limit is actually being triggered.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
HTTPS
Next
Input Sanitization
- Why Rate Limiting Matters
- Installing SlowAPI
- Basic Setup
- Applying Limits to Individual Endpoints
- Global Default Limits
- Writing an Accurate Custom 429 Response
- Scaling Rate Limits Across Multiple Workers with Redis
- Getting the Real Client IP Behind a Reverse Proxy
- Applying Stricter Limits to Authentication Endpoints
- A Note on SlowAPI's Maturity
- Key Takeaways
- Practice: Building the Full Configuration
- Frequently Asked Questions
