Bucket4j is a Java library that implements rate limiting with the token bucket algorithm. You create a bucket with a capacity and a refill rate, then each request must take a token from it. When the bucket is empty the request is rejected or delayed, which protects your service from abuse and traffic spikes.
It is thread-safe, has no mandatory dependencies, and can keep bucket state in memory or in a distributed store (Redis, Hazelcast, Ignite, Infinispan, JCache and relational databases) so limits hold across several application instances.
A bucket holds up to a fixed number of tokens, its capacity. Tokens are added at a steady rate (the refill). Every operation consumes one or more tokens.
This is the main difference from a simple fixed-window counter, which can let through twice the limit around a window boundary.
Bucket4j 8 publishes artifacts per minimum Java version. For Java 17 and later use bucket4j_jdk17-core from the com.bucket4j group; the older bucket4j-core artifact targets Java 8. Check Maven Central for the current release and pin it in a property.
Distributed backends are separate modules, for example bucket4j_jdk17-redis or bucket4j_jdk17-hazelcast.
The builder API below uses the lambda style introduced in the 8.x line (older code used Bandwidth.classic(...), which is deprecated).
The exact wait time depends on timing. tryConsume(1) returns only a boolean, while tryConsumeAndReturnRemaining also reports remaining tokens and the time to wait, which is what you need for a Retry-After header.
| Strategy | Behaviour |
|---|---|
refillGreedy | Adds tokens continuously in small portions as time passes |
refillIntervally | Adds all tokens at once at the end of each interval |
refillIntervallyAligned | Like intervally, but aligned to a fixed time of day |
Greedy refill gives the smoothest traffic. Intervally refill is closer to a classic "100 requests per hour" quota.
You can combine limits, for example a burst limit and a sustained limit. A request must satisfy all of them.
A common pattern is a per-client bucket stored in a ConcurrentHashMap and a servlet filter that rejects excess requests with status 429.
In production, key by an authenticated user or API key rather than IP address, evict idle entries (a cache with expiry instead of a plain map), and be careful with X-Forwarded-For behind a proxy because clients can spoof it.
An in-memory bucket only limits one JVM. With several replicas, use a distributed proxy manager so every instance reads and updates the same bucket state through compare-and-swap operations on the backing store. You build a ProxyManager for your backend (for instance Redis through Lettuce or Jedis), then call builder().build(key, configurationSupplier) to get a bucket bound to a key. Bucket4j also offers a Spring Boot starter that configures limits through properties and annotations; verify its coordinates and Spring Boot support in its documentation before adopting it.
| Option | Strength | Trade-off |
|---|---|---|
| Bucket4j | Library in your code, many backends, precise token bucket | You write the integration |
Resilience4j RateLimiter | Fits with circuit breaker and retry | Simpler model, in-process |
| API gateway limits | No application code | Coarser rules, extra infrastructure |
Guava RateLimiter | Very small | Single JVM, smoothing only |
It limits how often an operation can happen: API requests per user, login attempts, calls to a paid third-party service, or background job throughput.
Yes. Buckets are designed for concurrent use, and operations are lock-free in the local implementation.
Greedy refill adds tokens gradually as time passes. Intervally refill adds the whole amount at the end of each period.
Yes, with a distributed backend such as Redis, Hazelcast or a JDBC database, all instances share one bucket per key.
Bucket4j brings the token bucket algorithm to Java with a small, thread-safe API. Define capacity and refill, call tryConsume or tryConsumeAndReturnRemaining, and return 429 with Retry-After when a request is refused. Use a distributed backend when more than one instance serves traffic.