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.
- 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
- Go (Golang)
- Chi (HTTP router & middleware)
- Redis (in-memory data store)
.
├── 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
Make sure Redis is running locally on port 6379:
docker run -d -p 6379:6379 redis
go run main.go
Server will start on: http://localhost:8080
Example request:
curl -X POST http://localhost:8080/send-data
-H "Content-Type: application/json"
-d '{"userId": "12345", "name": "John Doe"}'
✅ Success: { "status": "data received" }
❌ Rate limit exceeded: { "error": "rate limit exceeded for user 12345" }
- 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:
- First request → sets both keys (
expwith TTL,incr = 1). - Subsequent requests increment
incr. - If
incr > RateLimit, return HTTP429 Too Many Requests. - When
expexpires, the counter resets.
- Update RateLimit and RateLimitDuration in
ratelimiter/limiter.interface.goif needed. - Requires Redis >= 6.x.
- Logs all connections and errors.
All rights reserved.
This project is for demonstration purposes only.