- Docker
- Go
This project implements a configurable Rate Limiter in Go, capable of limiting
requests by IP or Access Token, using Redis as a persistence mechanism. It is
configured via environment variables or a .env file.
- The rate limiter is injected as middleware into the web server.
- It blocks excessive requests based on configured limits per IP or token.
- Rate limiter control information is stored in Redis, with support for replacement by other storage strategies, following the Strategy pattern.
- Maximum number of requests per second and block time are defined via environment variables.
- Redis is configured to be accessed externally and securely.
- When the limit is exceeded:
- HTTP Status Code:
429 - Message:
You have reached the maximum number of requests or actions allowed within a certain time frame
- HTTP Status Code:
After running the service, the following endpoints will be available:
GET /: Welcome home page.GET /ip?ip=<IP>: Validates and applies limits based on the provided IP address.GET /token?token=<TOKEN>: Validates and applies limits based on the provided access token.GET /health: Checks the service's health.
Create a .env file in the root directory of the project and add the following environment variables:
RATE_LIMITER_ADDR=rate-limiter:8080
REDIS_ADDR=redis:6379
REDIS_PASSWORD=
MAX_REQUESTS_PER_SECOND=5
TOKEN_MAX_REQUESTS=10
BLOCK_DURATION_SECONDS=5
TTL_EXPIRATION_SECONDS=5
USE_MEMORY_STORE=falseRATE_LIMITER_ADDR: Sets the address and port where the server will listen.REDIS_ADDR: Redis address to store and retrieve rate limit data.REDIS_PASSWORD: Password for Redis authentication, if required.MAX_REQUESTS_PER_SECOND: Maximum number of requests per IP per second.TOKEN_MAX_REQUESTS: Request limit per token, which overrides the IP limit.BLOCK_DURATION_SECONDS: Block time in seconds after exceeding the limit.TTL_EXPIRATION_SECONDS: Expiration time for counters in Redis.USE_MEMORY_STORE: Defines whether the system uses Redis (false) or in-memory storage (true).
Run the following command to start all services:
docker-compose up --buildThis will start the following services:
- Redis
- Main application (Rate Limiter)
- Automated tests (unit, integration, and E2E)
- Redis TUI for terminal visualization
-
Unit Tests:
docker logs unit-tests
-
Integration Tests:
docker logs integration-tests
-
End-to-End Tests:
docker logs redis-e2e-tests
The test was performed using Apache Benchmark:
for i in {1..50}; do
ab -n 500 -c 25 "http://localhost:8080/ip?ip=192.168.1.$i" >> ip_stress_test.txt 2>&1 &
ab -n 500 -c 25 -H "API_KEY: token$i" "http://localhost:8080/token" >> token_stress_test.txt 2>&1 &
done
waitResults are stored in the assets folder.
After starting Docker Compose, use the command below to open the TUI:
docker attach redis-tuiThe interface below displays real-time data:
