Concept Flow - Rate limiting
Incoming Request
Check Rate Limit
Reject
Send 429
When a request arrives, the system checks if the user has exceeded allowed requests. If yes, it rejects with an error; if no, it processes the request.
from fastapi import FastAPI, Request, HTTPException, Depends from fastapi_limiter import FastAPILimiter from fastapi_limiter.depends import RateLimiter from fastapi_limiter.aio.inmemory import InMemoryKeyStorage app = FastAPI() @app.on_event("startup") async def startup(): await FastAPILimiter.init(InMemoryKeyStorage()) @app.get("/items", dependencies=[Depends(RateLimiter(times=2, seconds=10))]) async def read_items(): return {"message": "Success"}
| Step | Request Number | Time (s) | Rate Limit Check | Action | Response |
|---|---|---|---|---|---|
| 1 | 1 | 0 | Allowed (0 < 2) | Process Request | 200 Success |
| 2 | 2 | 5 | Allowed (1 < 2) | Process Request | 200 Success |
| 3 | 3 | 8 | Blocked (2 >= 2) | Reject Request | 429 Too Many Requests |
| 4 | Wait | 11 | Reset Limit (time window passed) | Allow Next Requests | N/A |
| 5 | 4 | 12 | Allowed (0 < 2) | Process Request | 200 Success |
| Variable | Start | After 1 | After 2 | After 3 | After Reset | After 4 |
|---|---|---|---|---|---|---|
| request_count | 0 | 1 | 2 | 2 (blocked) | 0 (reset) | 1 |
| time_seconds | 0 | 0 | 5 | 8 | 11 | 12 |
Rate limiting controls how many requests a user can make in a time window. In FastAPI, use dependencies with RateLimiter(times, seconds). If requests exceed limit, server returns 429 error. Limit resets after the time window passes. This protects servers from overload and abuse.
What is the main purpose of rate limiting in a FastAPI application?
Which of the following is the correct way to import a rate limiter middleware in FastAPI?
from fastapi import FastAPI
from _____ import RateLimiterMiddleware
app = FastAPI()
app.add_middleware(RateLimiterMiddleware, max_requests=5, window_seconds=60)
Given this FastAPI code snippet using fastapi_limiter:
from fastapi import FastAPI
from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter
import aioredis
app = FastAPI()
@app.on_event("startup")
async def startup():
redis = await aioredis.from_url("redis://localhost")
await FastAPILimiter.init(redis)
@app.get("/items", dependencies=[Depends(RateLimiter(times=3, seconds=10))])
async def read_items():
return {"message": "Success"}
What happens if a user calls /items 4 times within 10 seconds?
Identify the error in this FastAPI rate limiting setup:
from fastapi import FastAPI
from fastapi_limiter import FastAPILimiter
import aioredis
app = FastAPI()
@app.on_event("startup")
async def startup():
redis = aioredis.from_url("redis://localhost")
await FastAPILimiter.init(redis)
@app.get("/data", dependencies=[Depends(RateLimiter(times=2, seconds=5))])
async def get_data():
return {"data": "info"}
You want to limit users to 10 requests per minute globally across multiple FastAPI instances behind a load balancer. Which setup is best?
1. Use in-memory counters in each instance
2. Use Redis with fastapi_limiter shared by all instances
3. Use local file storage for counts
4. Disable rate limitingPass the test and this pattern moves unknown