SlowAPI Rate Limit Redis Backend

Throttle FastAPI endpoints with SlowAPI using a Redis backend, per-user limits, custom headers, and exempted internal callers.

PythonFastapiResilience

Code

pythonsnippet
42 lines
from fastapi import FastAPI, Request
from slowapi import Limiter, _rate_limit_exceeded
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
from starlette.responses import JSONResponse

limiter = Limiter(
    key_func=get_remote_address,
    storage_uri='redis://localhost:6379/2',
    default_limits=['300/minute'],
    headers_enabled=True,
)

app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded)


def user_key(request: Request) -> str:
    api_key = request.headers.get('x-api-key')
    if api_key:
        return f'key:{api_key}'
    if request.client and request.client.host.startswith('10.'):
        return 'internal'  # 内部调用统一低配额
    return f'ip:{get_remote_address(request)}'


@app.get('/search')
@limiter.limit('60/minute', key_func=user_key)
async def search(request: Request, q: str = ''):
    return {'query': q, 'results': 12}


@app.get('/report')
@limiter.limit('10/hour', key_func=user_key, cost=2)
async def report(request: Request):
    return {'generated': True}


@app.get('/healthz')
async def healthz():
    return {'status': 'up'}  # 未加装饰器:探针不限流

How it works

SlowAPI Rate Limit Redis Backend keeps everything in the functions user_key, search, report and healthz.

Every coroutine is awaited, so exceptions surface at the awaiting line. Reach for fastapi and what you get is FastAPI, Request, Limiter, _rate_limit_exceeded, RateLimitExceeded — that is the whole API contact area.

The return value is newly constructed — inputs are never handed back.

What to watch for

  • Plan for an install step: fastapi, slowapi and starlette are a real dependency, resolved by the package manager.

Using it

The primary signature is def user_key(request: Request) -> str

user_key is what another module would consume; nothing else here is load-bearing for callers.

Key statements

return f'ip:{get_remote_address(request)}'
@app.get('/search')
@limiter.limit('60/minute', key_func=user_key)
async def search(request: Request, q: str = ''):
return {'query': q, 'results': 12}
return {'generated': True}
def user_key(request: Request) -> str:
    api_key = request.headers.get('x-api-key')
    if api_key:
        return f'key:{api_key}'
    if request.client and request.client.host.startswith('10.'):
        return 'internal'  # 内部调用统一低配额
    return f'ip:{get_remote_address(request)}'

Interactive Tools for This Topic

FAQ

Does `user_key` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Which packages must be installed first?
Yes. The imports resolve to `fastapi`, `slowapi` and `starlette`, which the package manager must provide.