Skip to content

a-rishabh/rate_limiter_api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

API Rate Limiter (FastAPI + Redis)

A production-ready API rate limiter built using FastAPI, Redis, and the Token Bucket algorithm.

This project demonstrates how to protect your APIs from abuse, ensure fair usage across clients, and control server load.


Table of Contents


📝 Overview

This project implements a Token Bucket rate limiter as a middleware in FastAPI.

  • Clients are identified by IP address (can be swapped for API keys).
  • Each client gets a “bucket” of tokens.
  • Each request consumes one token.
  • Tokens refill at a steady rate over time.
  • If the bucket is empty, the client receives a 429 Too Many Requests error.

How It Works

Token Bucket Algorithm

  • Capacity: Maximum number of tokens in the bucket (burst allowance).
  • Rate: Tokens refilled per second (sustained rate).
  • Allow request: If a token is available → consume one → request passes.
  • Reject request: If no tokens available → return 429 Too Many Requests.

This allows bursts of requests while enforcing a steady long-term limit.


Tech Stack

  • FastAPI – API framework
  • Redis – In-memory data store for distributed token tracking
  • Uvicorn – ASGI server for FastAPI
  • python-dotenv – For environment variable management

🚀 Setup & Installation

1. Clone the repo

git clone https://github.com/yourusername/rate_limiter_api.git
cd rate_limiter_api

2. Install dependencies

pip install -r requirements.txt

3. Start Redis

  • Local (Linux/macOS):

    redis-server

4. Create a .env file

REDIS_HOST=<your redis host>
REDIS_PORT=<your redis port>
REDIS_USER=<your redis username>
REDIS_PASS=<your redis password>

Configuration

In main.py:

RATE = 10 / 60   # refill rate (10 requests per 60 seconds)
CAPACITY = 10    # max tokens per bucket

You can adjust these to match your API’s limits:

  • Higher capacity → larger burst allowed.
  • Higher rate → more requests per second allowed.

Running the App

Start the FastAPI app:

uvicorn main:app --reload

Visit in your browser:

After exceeding your request quota, you’ll see:

{
  "detail": "Too Many Requests"
}

Endpoints

  • GET / → Basic test endpoint (rate-limited).
  • GET /data → Example protected API response.

Rate Limiting Details

  • Client Identifier: IP address (request.client.host).
  • Token Storage: Redis (shared across multiple API servers).
  • Rejections: HTTP 429 with JSON error.
  • Customizable: Swap client_ip for API keys or JWT claims.

Use Cases

  • Prevent API abuse – Stop spam, bots, or denial-of-service attempts.
  • Fair usage enforcement – Ensure each user or API key gets equal access.
  • Cost control – If you pay per API call, rate limiting saves $$$.
  • Protect downstream services – Avoid overloading your DB or third-party APIs.
  • Multi-tenant SaaS – Enforce per-tenant request quotas.

Improvements

Some ideas to extend this project:

  • Support multiple strategies (fixed window, sliding window).
  • Allow per-endpoint limits (e.g., stricter for /login).
  • Add headers in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
  • Use API keys or JWT claims instead of IP addresses.
  • Integrate with NGINX/Kong API Gateway for global enforcement.

License

MIT License. Free to use, modify, and distribute.


About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages