Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

README.md

65 - Rate Limiting & Throttling

Python Difficulty: Advanced FastAPI Redis

What It Does

A custom implementation of a Sliding Window API Rate Limiter inside FastAPI using Redis. It protects the /api/data endpoint by limiting requests to 5 per 10 seconds per IP address. If a user exceeds the limit, they are blocked with a 429 Too Many Requests response. Includes a simple, unified frontend to test spamming the API.

Project Structure

65-fastapi-rate-limit/
  main.py            # FastAPI Entry point
  rate_limiter.py    # Redis sliding window logic implemented as a Dependency
  index.html         # Unified Frontend (Button spamming tool)
  requirements.txt   # Dependencies
  README.md          # This file

Setup and Run

1. Requirements

You must have Redis installed and running on default port 6379.

2. Install dependencies

pip install -r requirements.txt

3. Start the FastAPI Server

uvicorn main:app --reload

4. Open the Frontend

Open index.html directly in your browser and click "Send Request" as quickly as you can!

Example Output

// After 5 fast requests:
{
  "detail": "Rate limit exceeded. Try again in 10 seconds."
}

Core Concepts

  • Sliding Window Algorithm: Unlike Fixed Window (which resets at the top of the minute), Sliding Window tracks precise timestamps. We use Redis Sorted Sets (ZADD, ZREMRANGEBYSCORE, ZCARD) to atomically log and count request timestamps.
  • FastAPI Dependencies: We inject rate_limit directly into our routes. If the limit is exceeded, the dependency raises an HTTPException(429) before the route logic even begins.
  • request.client.host: Identifying unique users implicitly by IP address (or could be linked to JWTs).