Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

rate-limiter-service

A simple API rate limiter service built with Go, Chi router, and Redis.
This service restricts the number of API requests per user within a given time window using Redis as a counter.


🚀 Features

  • Rate limiting per user (userId)
  • Configurable limit and time window
  • Redis-based counters with TTL
  • Lightweight HTTP server using go-chi
  • JSON response with proper HTTP status codes

⚙️ Tech Stack

  • Go (Golang)
  • Chi (HTTP router & middleware)
  • Redis (in-memory data store)

📂 Project Structure

. ├── main.go # Entry point
├── ratelimiter/ # Rate limiting logic & handlers
│ ├── limiter.handler.go # HTTP handler for /send-data
│ ├── limiter.service.go # Core rate limiter logic
│ └── limiter.interface.go # Request body + constants
└── redis/ # Redis client wrapper
└── redis.go


⚡ Usage

1. Start Redis

Make sure Redis is running locally on port 6379: docker run -d -p 6379:6379 redis

2. Run the service

go run main.go

Server will start on: http://localhost:8080

3. Send requests

Example request: curl -X POST http://localhost:8080/send-data
-H "Content-Type: application/json"
-d '{"userId": "12345", "name": "John Doe"}'

Example Responses

✅ Success: { "status": "data received" }

❌ Rate limit exceeded: { "error": "rate limit exceeded for user 12345" }


⚖️ Rate Limiting Logic

  • Each user can make up to 3 requests per 60 seconds (RateLimit = 3, RateLimitDuration = 60).
  • Counters are stored in Redis using two keys:
    • exp-{userId} → expiration key (marks the time window)
    • incr-{userId} → request counter

Flow:

  1. First request → sets both keys (exp with TTL, incr = 1).
  2. Subsequent requests increment incr.
  3. If incr > RateLimit, return HTTP 429 Too Many Requests.
  4. When exp expires, the counter resets.

🛠️ Development Notes

  • Update RateLimit and RateLimitDuration in ratelimiter/limiter.interface.go if needed.
  • Requires Redis >= 6.x.
  • Logs all connections and errors.

📜 License

All rights reserved.
This project is for demonstration purposes only.

About

Lightweight API rate limiter service using Go, Chi, and Redis. Restricts requests per user within a time window using Redis counters with TTL for high-performance traffic control.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages