Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Redis connection (used by Spring Boot)
REDIS_HOST=localhost

# JWT signing key — must be at least 32 characters for HS256
JWT_SIGNING_KEY=my-super-secret-signing-key-which-must-be-32-bytes!

# Optional: override rate limit settings
# RATELIMIT_IP_LIMIT=100
# RATELIMIT_IP_WINDOW_SECONDS=60
# RATELIMIT_ACCOUNT_LIMIT=10
# RATELIMIT_ACCOUNT_WINDOW_SECONDS=60
# RATELIMIT_REDIS_FAILURE_POLICY=FAIL_CLOSED
# RATELIMIT_TRUSTED_PROXIES=10.0.0.1,172.21.0.1
30 changes: 30 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: CI

on:
push:
branches: [main, master]
pull_request:
branches: [main, master]

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Set up JDK 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
cache: maven

- name: Install Maven
run: sudo apt-get update && sudo apt-get install -y maven

- name: Run tests
run: mvn -B verify

- name: Build Docker image
run: docker build -t distributed-rate-limiter:ci .
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ build/
### VS Code ###
.vscode/

mvnw*
.mvn/*
.mvn/wrapper/maven-wrapper.jar
data/
prometheus.exe
*.exe
58 changes: 45 additions & 13 deletions Design.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,9 @@ This section maps logical domains to the project's folder structure to keep conc

Infra and Spring bean configuration:

- AwsConfig
- RedisConfig
- WebFilterConfig
- JwtConfig
- SecurityFilterConfig

Purpose: environment wiring, beans, and external integrations. Keeps deployment details out of business logic.

Expand All @@ -165,6 +164,7 @@ Purpose: HTTP endpoints and request/response shaping only. No rate-limit or secu

Request policing and pipeline guards:

- CorrelationIdFilter
- IpRateLimitFilter
- JwtAuthFilter
- AccountRateLimitFilter
Expand All @@ -185,11 +185,26 @@ Purpose: Algorithmic logic for counting and decisions. Framework-agnostic for ea
Authentication and secrets:

- JwtGen
- JwtSecretService
- SecurityConfig

Purpose: JWT creation/verification and related security utilities. Separated from rate-limiting rules.

### metrics/

Observability:

- RateLimitMetrics

Purpose: Micrometer counters and timers for rate-limit decisions and Redis latency.

### util/

Shared helpers:

- JsonErrorWriter

Purpose: Safe JSON serialization for error responses.

### resources/

Static runtime assets:
Expand Down Expand Up @@ -242,9 +257,10 @@ stops. Production fix:

- **Redis Sentinel** for automatic failover (primary + 2 replicas)
- **Redis Cluster** for horizontal sharding if key space becomes large
- **Fail-open vs fail-closed decision**: current implementation fails open
(requests pass through when Redis is down). For security-critical limiting,
fail-closed is safer but risks availability. This is a deliberate tradeoff.
- **Fail-open vs fail-closed decision**: configurable via `ratelimit.redis.failure-policy`.
Default is **fail-closed** (`503 Service Unavailable`) because a down Redis means
rate limiting is broken. Set `FAIL_OPEN` for availability-first projects where
unprotected traffic is acceptable during outages.

### Sliding Window Log Memory Grows with Traffic

Expand All @@ -268,15 +284,31 @@ Production fix:
- Maintain a distributed token blacklist in Redis for revocation
- This converts per-request cryptographic verification into a Redis lookup

### No Rate Limit Headers in Responses
### Rate Limit Headers

Production rate limiters return headers so clients can self-throttle:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 23
X-RateLimit-Reset: 1714500000
Retry-After: 37
The service returns `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`,
and `Retry-After` on blocked responses. Clients should honor `Retry-After` with
exponential backoff to avoid retry storms.

### Production Secret Management

JWT signing keys must not be committed to source control. This project loads
`JWT_SIGNING_KEY` from environment variables (see `.env.example`).

In production, load secrets from a managed store:

- **AWS Secrets Manager** / **Parameter Store**
- **HashiCorp Vault**
- **Kubernetes Secrets**

Example pattern (not wired in this project — requires a paid AWS account):

```java
// SecretsManagerClient client = ...;
// String key = client.getSecretValue(...).secretString();
```

This reduces unnecessary retry storms from well-behaved clients.
The project intentionally uses env vars for portability and zero cloud cost.

### The Algorithm Tradeoff at Netflix/Stripe Scale

Expand Down
17 changes: 17 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
FROM maven:3.9.6-eclipse-temurin-21-alpine AS builder
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests

FROM eclipse-temurin:21-jre-alpine
RUN apk add --no-cache curl
RUN addgroup -S app && adduser -S app -G app
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
RUN chown -R app:app /app
USER app
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
CMD curl -f http://localhost:8080/actuator/health || exit 1
ENTRYPOINT ["java", "-jar", "app.jar"]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Muhammad Ahmed

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Loading
Loading