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.