Skip to content

aaditya0004/rate-limiter-service

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 Distributed Rate Limiter Service

A scalable backend service built using Spring Boot + Redis to control API traffic using a Fixed Window Rate Limiting algorithm.


🧠 What is Rate Limiting?

Rate limiting helps protect APIs from:

  • 🚫 Abuse & spamming
  • 🚫 Server overload
  • 🚫 Brute force attacks

It ensures fair usage by limiting how many requests a client can make within a time window.


✨ Features

  • ✅ Redis-based distributed rate limiting
  • ✅ Fixed window algorithm using TTL
  • ✅ Atomic request counting using Redis
  • ✅ Thread-safe & concurrent request handling
  • ✅ Health check endpoint for monitoring
  • ✅ Clean layered architecture (Controller, Service, DTO, Model)

⚙️ Tech Stack

  • Java 17
  • Spring Boot
  • Redis
  • Docker
  • Maven

🏗️ Architecture

Client → Controller → Service → Redis → Response
  • Controller handles API requests
  • Service applies rate limiting logic
  • Redis stores request counts with expiry

🔥 How It Works

  1. Each request is mapped to a key:

    rate_limit:{clientId}
    
  2. Redis increments count:

    INCR key
    
  3. First request sets TTL (60 seconds)

  4. If count > limit → ❌ Block Else → ✅ Allow


📡 API Endpoints


🔹 1. Rate Limit API

POST /api/rate-limit

Request:

{
  "clientId": "user123"
}

Response:

{
  "allowed": true,
  "remainingRequests": 4
}

🔹 2. Health Check

GET /api/health

Response:

Rate Limiter is running 🚀

🛠️ Setup Guide


🔹 Step 1: Clone Repository

git clone https://github.com/YOUR_USERNAME/rate-limiter-service.git
cd rate-limiter-service

🔹 Step 2: Start Redis (Docker)

docker run -d -p 6379:6379 --name redis-server redis

🔹 Step 3: Configure Application

In application.properties:

spring.redis.host=localhost
spring.redis.port=6379

🔹 Step 4: Run Application

mvn spring-boot:run

🧪 Testing

Use Postman or curl:

curl -X POST http://localhost:8080/api/rate-limit \
-H "Content-Type: application/json" \
-d '{"clientId":"user123"}'

📊 Example Behavior

Request Result
1 ✅ Allowed
2 ✅ Allowed
3 ✅ Allowed
4 ✅ Allowed
5 ✅ Allowed
6 ❌ Blocked

After 60 seconds → counter resets automatically.


🧠 Key Concepts Used

  • Redis INCR (atomic operation)
  • TTL-based window expiration
  • Distributed system design basics
  • Spring Boot dependency injection

📁 Project Structure

ratelimiter/
 ├── controller/
 ├── service/
 ├── dto/
 ├── model/
 ├── config/

🚀 Future Improvements

  • 🔑 API key-based rate limiting
  • 🔐 JWT authentication
  • 📊 Monitoring & metrics
  • ☁️ Cloud deployment (AWS / Render)

👨‍💻 Author

Aaditya Tyagi


⭐ If you like this project, give it a star!

About

Distributed rate limiter using Spring Boot and Redis

Topics

Resources

Stars

Watchers

Forks

Contributors

Languages