Lesson 37 of 59Product features
Rate Limits, Quotas and Request Limits in FastAPI
Implement limits in FastAPI: pick the right key, trust proxies correctly, use SlowAPI or a Redis GCRA script, send good 429s, and meter plan quotas.
On Monday a credential-stuffing attack hits /login from 3,000 different IP addresses, a few attempts each, and your per-IP limit of 100 a minute never fires. On Tuesday a whole university shares one NAT address, and the same limit locks out 400 legitimate students. On Wednesday one customer's batch job hammers /search, the most expensive endpoint, and everyone else's searches time out. All three are rate limiting problems, and none of them is solved by picking a better algorithm. The algorithms are in the Rate Limiting lesson of the System Design course. This lesson is about the implementation and the policy in a FastAPI service: what to count, how to identify who is calling, which library or Redis script to use, what to send back, and the other limits (quotas, body size, timeouts, concurrency) that protect a real API.
Choosing the key
A limit is "N units per window, per something". The something is the key, and it is the most important decision.
| Key | Good for | Weakness |
|---|---|---|
| IP address | Anonymous endpoints, sign-up, abuse at the edge | NAT and mobile carriers put thousands of users behind one address; attackers rotate IPs cheaply |
| User id | Logged-in features | Useless before login; one attacker can create many accounts |
| API key | Public APIs, partner integrations | Leaked keys; a customer with ten keys gets ten times the limit |
| Tenant / organisation | B2B fairness, plan limits | One noisy user can exhaust the whole team's budget |
| Target account | Login, password reset, OTP checks | Must count attempts against non-existent accounts too |
Real systems combine keys. A login endpoint checks per target account (stops guessing one person's password from many IPs) and per IP (stops one machine trying many accounts). A B2B API checks per API key for bursts and per tenant for the monthly quota.
Routes also differ in cost. A search that fans out to Elasticsearch is not the same as GET /me. Either give expensive routes their own tighter limit, or give each route a cost and spend it from one shared budget (search costs 5 units, a read costs 1). The GraphQL APIs of GitHub and Shopify work this way, charging each query a calculated cost.
For IPv6, limit by the /64 prefix rather than the full address. A single home connection is usually given a whole /64 (about 18 quintillion addresses), so per-address limits on IPv6 are trivially bypassed.
Getting the real client IP
Behind a load balancer, every request reaches FastAPI from the balancer's address. The real client is in X-Forwarded-For, a comma-separated list where each proxy appends the address it received the connection from. The catch: the client can send that header too, with any value. The left-most entry is whatever the client chose to write. Only the entries added by your proxies are trustworthy, so you walk the list from the right and take the first address that is not one of your proxies:
Press Run (⌘ Enter) to see what happens.The forged 1.2.3.4 never wins. An app that naively takes the first entry would let an attacker pick a fresh "IP" for every request and walk straight past the limit.
You rarely write this yourself. Uvicorn does it: --proxy-headers is on by default, and it rewrites request.client.host from X-Forwarded-For, but only for connections from addresses in --forwarded-allow-ips, which defaults to 127.0.0.1. So behind a real load balancer, set --forwarded-allow-ips (or the FORWARDED_ALLOW_IPS environment variable) to the balancer's addresses or subnet. Setting it to * is safe only when nothing can reach the app except through your proxy. Behind Cloudflare, use CF-Connecting-IP, and only if your origin accepts traffic from Cloudflare's ranges alone.
request.client.host as the rate limit key. Uvicorn starts with default settings. What key does every request get?SlowAPI and the limits library
SlowAPI is the common FastAPI rate limiter. It is a port of Flask-Limiter, and both sit on the limits library, which implements fixed window, moving window and sliding window counter strategies over memory, Redis, Memcached or MongoDB storage.
from fastapi import FastAPI, Request, Response
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
def user_or_ip(request: Request) -> str:
user_id = getattr(request.state, "user_id", None) # set by your auth middleware
return f"user:{user_id}" if user_id else f"ip:{request.client.host}"
limiter = Limiter(
key_func=user_or_ip,
storage_uri=settings.redis_url, # shared by every worker and every server
headers_enabled=True, # X-RateLimit-* and Retry-After
)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@app.post("/login")
@limiter.limit("5/minute")
async def login(request: Request, response: Response, body: LoginIn): ...Three gotchas catch everyone. The route must take a request: Request parameter, or SlowAPI cannot find the request. With headers_enabled=True, it must also take response: Response, or SlowAPI raises an exception when it tries to add the headers. And without storage_uri, limits live in process memory: run four Uvicorn workers and each has its own counter, so the real limit is four times what you wrote, and it resets on every deploy.
If you prefer FastAPI's dependency style, call limits directly. Its async API takes several identifiers and a per-hit cost, which makes weighted routes easy:
import math
import time
from fastapi import Depends, HTTPException, Request
from limits import parse
from limits.aio.strategies import SlidingWindowCounterRateLimiter
from limits.storage import storage_from_string
storage = storage_from_string(settings.limits_url, implementation="redispy") # "async+redis://..."
limiter = SlidingWindowCounterRateLimiter(storage)
def rate_limit(limit: str, scope: str, cost: int = 1):
item = parse(limit)
async def dependency(request: Request) -> None:
who = getattr(request.state, "user_id", None) or request.client.host
if not await limiter.hit(item, scope, str(who), cost=cost):
stats = await limiter.get_window_stats(item, scope, str(who))
retry = max(1, math.ceil(stats.reset_time - time.time()))
raise HTTPException(429, "Rate limit exceeded", headers={"Retry-After": str(retry)})
return Depends(dependency)
@router.get("/search", dependencies=[rate_limit("300/minute", "search", cost=5)])
async def search(q: str): ...Atomic limits in Redis
The Redis and Caching lesson built a fixed window with INCR and EXPIRE sent together in a MULTI pipeline. That detail matters. Sent as two separate commands, a crash or timeout between them leaves a counter with no expiry, and that user stays rate limited forever. The other classic bug is check-then-act: GET the count, compare in Python, then SET it. Two workers both read 99, both allow, both write 100, and bursts slip through under exactly the load you were protecting against.
Anything smarter than a fixed window has to read, compute and write as one step, and the way to do that in Redis is a Lua script, which Redis runs atomically. A popular choice is GCRA (the generic cell rate algorithm). It behaves like a token bucket but stores a single number per key: the theoretical arrival time (TAT), the moment the next request would be due if the client sent at exactly the steady rate. A request is allowed if the client is not too far ahead of schedule:
Press Run (⌘ Enter) to see what happens.Three requests at t=0 use the burst, the fourth is told to come back in exactly 6 seconds, and after a quiet spell the full burst is available again. The retry_after is precise, which makes an honest Retry-After header free. Here is the same logic as a Lua script, using Redis's own clock so servers with skewed clocks agree:
GCRA_LUA = """
local key = KEYS[1]
local interval = tonumber(ARGV[1]) -- ms between requests at the steady rate
local burst = tonumber(ARGV[2])
local t = redis.call("TIME")
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local tolerance = interval * (burst - 1)
local tat = tonumber(redis.call("GET", key)) or now
if tat < now then tat = now end
local allow_at = tat - tolerance
if now < allow_at then
return {0, allow_at - now} -- denied, retry after this many ms
end
local new_tat = tat + interval
redis.call("SET", key, new_tat, "PX", new_tat - now)
return {1, 0}
"""
gcra = redis_client.register_script(GCRA_LUA) # redis.asyncio client
async def check(key: str, per_minute: int, burst: int) -> tuple[bool, int]:
allowed, retry_ms = await gcra(keys=[key], args=[60_000 // per_minute, burst])
return bool(allowed), retry_msregister_script loads it once and calls it by hash with EVALSHA afterwards. The key expires by itself once the client is back on schedule, so idle users cost no memory. In Redis Cluster, a script may only touch keys in one hash slot, which is fine here because it uses one key.
Using the GCRA class above, what does this print?
l = GCRA(rate=60, period=60, burst=2)
print([l.hit("k", now=t) for t in [0, 0, 0, 1]])Telling clients what happened
Reject with 429 Too Many Requests and a Retry-After header in seconds, as the Rate Limiting lesson showed, and put a useful body on it (a problem details JSON with the limit that was hit is ideal). Do not use 403, which tells clients retrying is pointless, or 503, which blames your server.
For the "how much is left" headers there is no finished standard yet. Many APIs send the legacy X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset, but they disagree on whether Reset is a Unix timestamp or a number of seconds. The IETF HTTPAPI working group's draft defines RateLimit-Policy and RateLimit fields using structured field syntax, along these lines:
RateLimit-Policy: "default";q=100;w=60
RateLimit: "default";r=42;t=21Here the policy is 100 units (q) per 60-second window (w), and the client has 42 remaining (r) with 21 seconds until reset (t). It is still an Internet-Draft, not an RFC, and its syntax has changed between versions, so check the current draft before you implement it, and document whichever headers you send.
Layers: edge, app and outbound
Rate limiting is not one check in one place. Each layer sees different information and stops different traffic.
The edge (Cloudflare, AWS WAF) drops floods and obvious bots before they cost you anything. It knows IPs and headers, not users.
For outbound limits, a shared Redis limiter keyed by the partner works across workers, and a library such as aiolimiter paces calls within one process. Pair it with an asyncio.Semaphore capping concurrent calls, because partners often limit concurrency as well as rate.
Order the layers from the first to see a request to the last.
- Tap the steps below in the right order.
Quotas are a product feature
A rate limit protects the system over seconds or minutes. A quota is a business allowance over a billing period: 10,000 API calls a month on the Pro plan, 5 GB of storage, 3 seats. They are enforced differently.
- Metering must be accurate, because it may become an invoice. Record usage as events (or increment Redis counters and flush them to Postgres every minute), keyed by tenant and billing period, not calendar month. Make recording idempotent, so a retried request is not billed twice.
- Soft limits warn: at 80% and 100%, email the account owner (an outbox job, as in Sending Email from a Backend) and show a banner. Many products let customers run over and bill the overage.
- Hard limits block: return 429 (or 402 if your API treats it as a payment issue) with a body that says which quota, the current usage and when it resets. Check the hard limit before doing expensive work, not after.
- Read quotas from the tenant's plan at request time (cached briefly), so an upgrade takes effect immediately rather than at the next deploy.
Other limits that keep you up
Rate limits are one tool in a set. A production API also needs:
- Body size limits at the proxy and in the app, as File Uploads and Object Storage showed. A 2 GB JSON body is an attack whatever its rate.
- Timeouts at every hop, each shorter than the one outside it: the client gives up after 30 s, the load balancer after 25 s, your handler wraps slow work in
asyncio.timeout(20), and everyhttpxcall has its own timeout. Otherwise a slow dependency piles up waiting requests until memory runs out. - Concurrency limits for expensive endpoints. An
asyncio.Semaphore(4)around PDF generation stops 200 simultaneous exports from starving the server. If the semaphore is already full, fail fast with 503 andRetry-Afterrather than queueing forever. That is load shedding: serving some users well beats serving everyone badly. - Brute-force protection on login. Count failures per account and per IP. Add progressive delays or a CAPTCHA after a few failures. Be careful with hard lockouts: if five wrong passwords lock an account for an hour, an attacker can lock out your CEO on purpose. Prefer short, escalating lockouts, notify the user, and let a successful second factor or reset clear them.
When Redis is down
Your limiter now depends on Redis, so decide what happens when Redis does not answer. Fail open (allow the request) keeps the product up, and suits most read endpoints. Fail closed (reject) suits endpoints where unlimited traffic is dangerous: login, OTP verification, sending SMS that costs money. Whichever you choose, give the Redis client short timeouts so a hung connection costs milliseconds, and alert on the errors. SlowAPI has swallow_errors=True to fail open and in_memory_fallback_enabled=True to fall back to approximate per-process limits, which is a sensible middle ground.
Match each endpoint to the key (or keys) it should be limited by.
- rate limit key
- The identity a limit is counted against: IP, user, API key, tenant or target account.
- X-Forwarded-For
- A header each proxy appends the connecting address to. Only entries added by your own proxies can be trusted.
- GCRA
- Generic cell rate algorithm: a token-bucket equivalent that stores one timestamp per key, the theoretical arrival time.
- Lua script
- Code Redis runs atomically on the server, used to read, decide and write a limiter's state in one step.
- quota
- A business allowance over a billing period, such as calls per month, metered for plans and invoices.
- load shedding
- Rejecting some requests quickly, usually with 503, when the system is at capacity, so the rest succeed.
- fail open
- Allowing requests when the limiter itself is unavailable, trading protection for availability.