InterviewHubPRO
Section Overview
Q53

Question 53 of 65

Part 4: Web Frameworks, APIs & FastAPI (41 - 55)

82%
Python & FastAPI•Part 4: Web Frameworks, APIs & FastAPI (41 - 55)

API Rate Limiting with Redis:

In Simple Words: Track request count per IP address in Redis with an expiration window. If count exceeds limit, raise HTTP 429 Too Many Requests.

python
from fastapi import HTTPException
import redis.asyncio as redis

r = redis.from_url("redis://localhost:6379")

async def check_rate_limit(client_ip: str, limit: int = 60):
    key = f"rate:{client_ip}"
    requests = await r.incr(key)
    if requests == 1: await r.expire(key, 60)
    if requests > limit:
        raise HTTPException(status_code=429, detail="Too Many Requests")