Rate limiting helps control how many times a user or client can use an API in a set time. It stops overload and keeps the service fair for everyone.
0
0
Rate limiting in FastAPI
Introduction
To prevent a user from sending too many requests and slowing down the server.
To protect an API from being overwhelmed by bots or attackers.
To make sure all users get a fair chance to use the service.
To avoid extra costs from too many requests in cloud services.
Syntax
FastAPI
from fastapi import FastAPI, Request, HTTPException, Depends 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", encoding="utf8", decode_responses=True) await FastAPILimiter.init(redis) @app.get("/items", dependencies=[Depends(RateLimiter(times=5, seconds=60))]) async def read_items(): return {"message": "You can call this 5 times per minute."}
You need Redis running because rate limiting stores counts there.
Use times and seconds to set how many calls are allowed in that time.
Examples
This limits login attempts to 3 per minute to prevent brute force attacks.
FastAPI
from fastapi import FastAPI, Depends from fastapi_limiter.depends import RateLimiter app = FastAPI() @app.get("/login", dependencies=[Depends(RateLimiter(times=3, seconds=60))]) async def login(): return {"message": "Max 3 login attempts per minute."}
This limits data requests to 10 per hour for each user.
FastAPI
from fastapi import FastAPI from fastapi_limiter.depends import RateLimiter app = FastAPI() @app.get("/data", dependencies=[Depends(RateLimiter(times=10, seconds=3600))]) async def get_data(): return {"message": "Max 10 calls per hour."}
Sample Program
This FastAPI app limits the /hello endpoint to 2 calls every 30 seconds per user. If you call it more, it will block you temporarily.
FastAPI
from fastapi import FastAPI, Depends 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", encoding="utf8", decode_responses=True) await FastAPILimiter.init(redis) @app.get("/hello", dependencies=[Depends(RateLimiter(times=2, seconds=30))]) async def say_hello(): return {"message": "Hello! You can call this endpoint 2 times every 30 seconds."}
OutputSuccess
Important Notes
Make sure Redis is installed and running before starting the FastAPI app.
Rate limiting works per client IP or user depending on your setup.
You can customize limits per route using the RateLimiter dependency.
Summary
Rate limiting controls how often users can call API endpoints.
It helps protect your app from overload and abuse.
FastAPI uses external Redis storage to track request counts for limits.