Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4DPa89t5pSXDQHE6j
2.3 KiB
2.3 KiB
rate-limiter
Runnable companion for the ankurm.com article Low-Level Design: Rate Limiter in Java (Token Bucket, Sliding Window) + Spring Boot.
Four algorithms behind one interface, a lock-free token bucket, a Redis Lua token bucket (plus the
naive version that over-admits), and a Spring Boot interceptor that answers 429 with Retry-After.
| Component | Version | Verified against |
|---|---|---|
| JDK | 25.0.5+8 (Temurin, LTS) | java -version |
| Spring Boot | 4.1.2 | maven-metadata.xml on Maven Central (latest non-milestone) |
| Jedis | 8.0.2 | maven-metadata.xml (latest non-beta); JedisPooled is gone, RedisClient replaces it |
| JUnit | 6.1.3 | maven-metadata.xml |
| Redis | 7.0.15 | redis-server --version (tests start their own on port 6392) |
export JAVA_HOME=/path/to/jdk-25 && export PATH="$JAVA_HOME/bin:$PATH"
cd rate-limiter
mvn test # 17 tests; Redis tests are skipped if redis-server is not installed
./scripts/run-demo.sh # boundary-burst comparison of the four algorithms
./scripts/run-redis-demo.sh # naive GET+INCR vs Lua script, 200 threads, limit 10
| Source | What it is |
|---|---|
RateLimiter, Decision |
the interface and its answer (allowed, or how long to wait) |
FixedWindowRateLimiter |
two numbers of state; allows 2x the limit across a window boundary |
SlidingWindowLogRateLimiter |
exact; O(limit) memory per key |
SlidingWindowCounterRateLimiter |
weighted previous + current window; O(1) memory, approximate |
TokenBucketRateLimiter, LockFreeTokenBucketRateLimiter |
burst then steady rate; synchronized vs compareAndSet |
KeyedRateLimiter |
one limiter per key via computeIfAbsent |
ManualClock |
move time by hand so tests never sleep |
redis/RedisTokenBucketRateLimiter, token_bucket.lua |
the whole bucket update in one atomic script |
redis/NaiveRedisRateLimiter, redis/RedisRaceDemo |
the wrong answer and the demo that shows it |
web/RateLimitedApp, web/RateLimitInterceptor |
Spring Boot wiring for /api/** |
The race demo's naive count varies per run and per machine: indicative, not asserted. Everything else is deterministic and asserted by the tests.