A minimal rate limiter in plain Java which...
- supports sliding windows
- supports buckets for partitioning a rate limiter across several domains (e.g. one bucket per user)
- provides information about when the next call will be possible (e.g. for using the
Retry-After
HTTP header) - is thread-safe
// RateLimiter allows three invocations over a sliding window of 10 seconds.
RateLimiter rateLimiter = new RateLimiter(3, Duration.ofSeconds(10));
rateLimiter.guard("1", () -> {
// This code will only run if the rate limit has not been exceeded.
// Otherwise, a RateLimitExceededException is thrown.
});