Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RateGuard – Distributed API Rate Limiter (Spring Boot + Redis)

RateGuard is a production-ready, distributed API rate-limiting service built using Spring Boot, Redis, and Lua scripting.
It demonstrates how modern backend systems enforce request limits reliably under high concurrency and horizontal scaling.


Features

  • Sliding window rate limiting (not fixed window)
  • Distributed enforcement using Redis
  • Atomic rate-limit checks using Redis Lua scripts
  • IP-based rate limiting (proxy-aware)
  • Dynamic rule resolution (pluggable policy engine)
  • Fail-open strategy on Redis failure
  • Cloud-deployed (Railway)

Why this project?

Most rate limiters you see online:

  • Use in-memory counters ❌
  • Break under multiple instances ❌
  • Are inconsistent under concurrency ❌

RateGuard solves all of these by using:

  • Redis Sorted Sets (ZSETs)
  • Lua scripts for atomic operations
  • A clean separation of concerns

This mirrors how real systems (API gateways, CDNs, SaaS backends) work.


Architecture Overview

  • Client
  • Spring Boot Filter
  • RateLimiter Interface
  • RedisSlidingWindowRateLimiter
  • Redis (Lua Script)

Key components:

Component Responsibility
RateLimitFilter Intercepts incoming HTTP requests
RateLimiter Abstraction for rate-limit strategies
RedisSlidingWindowRateLimiter Distributed rate-limit logic
RateLimitRuleResolver Determines limits per request
Redis + Lua Atomic, consistent enforcement

Sliding Window Algorithm

For each request:

  1. Remove timestamps older than the window
  2. Count remaining requests
  3. Reject if count ≥ limit
  4. Insert current timestamp
  5. Set expiry

This avoids burst problems common in fixed-window approaches.


Example Rate Limit Rule

  • 5 requests per 10 seconds per IP

This rule is resolved dynamically via RateLimitRuleResolver.


🛡 Proxy-Aware IP Handling

In production environments behind load balancers or reverse proxies:

  • Client IP is extracted from X-Forwarded-For
  • Fallback to getRemoteAddr() for local usage

This ensures correctness both locally and in cloud deployments.


Tech Stack

  • Java 17+
  • Spring Boot 3.x
  • Spring Web
  • Spring Data Redis (Lettuce)
  • Redis
  • Lua scripting
  • Maven
  • Railway (deployment)

Running Locally

Prerequisites

  • Java 17+
  • Maven
  • Redis (local or Docker)

Start Redis

docker run -d -p 6379:6379 redis:7

#run the application

mvn spring-boot:run

#health endpoint

curl http://localhost:8080/health

#protected endpoint

for i in {1..7}; do curl http://localhost:8080/test; done

Deployment

About

A distributed API rate limiter using Redis and Lua scripts to enforce accurate request limits under high concurrency.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages