Skip to content

java-limiterLock-free rate limiting for Java 8+

One 18 KB jar, six algorithms, zero runtime dependencies, no background threads.

java-limiter

Install ​

xml
<dependency>
    <groupId>io.github.onblog</groupId>
    <artifactId>java-limiter</artifactId>
    <version>1.0.0</version>
</dependency>
groovy
implementation 'io.github.onblog:java-limiter:1.0.0'

First limiter ​

java
import io.github.onblog.limiter.RateLimiter;
import io.github.onblog.limiter.RateLimiters;

import java.time.Duration;

// 100 requests per second on average, bursts of up to 200.
RateLimiter limiter = RateLimiters.tokenBucket("payments", 200, 100, Duration.ofSeconds(1));

if (limiter.tryAcquire()) {
    handleRequest();
} else {
    response.setStatus(429);
}

A rejected request is not an error: tryAcquire returns false, nothing is logged and nothing is thrown.

Pick an algorithm ​

LimiterBehaviourUse it for
TokenBucketLimiterAverage rate plus a burst budget that refills while idlePublic APIs, protecting a dependency that tolerates bursts
LeakyBucketLimiterStrictly even pacing, never accumulates a burstOutbound calls, MQ consumption, anything that must be smooth
SlidingWindowLimiterAt most N permits in any rolling windowLogin attempts, per-minute or per-hour quota with no exploitable boundary
FixedWindowLimiterAt most N permits per aligned window, one AtomicLongVery high traffic with loose accuracy needs
WarmUpTokenBucketLimiterStarts at a third of the rate, ramps up over a warm-up periodServices that are cold right after start-up
ConcurrencyLimiterCaps permits in flight, not permits per secondProtecting thread pools, connection pools, slow downstreams

Read Algorithms for how each one works and what it guarantees under contention.

中文文档 ​

The full documentation is also available in Chinese: 简体中文.