Bucket4j Java Guide: Rate Limiting with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Bucket4j for Java: The Complete Rate Limiting Guide

In modern software development, especially when building high-traffic web services and APIs, controlling the rate of incoming requests is critical. Without such control, a single malicious user or a system bug can cause a denial of service (DoS) for all other clients. This is where the concept of Rate Limiting comes in, and the Bucket4j library is one of the most powerful and flexible tools for implementing it on the Java platform.

Bucket4j is a thread-safe, Token Bucket algorithm-based library for Java. It allows developers to easily and efficiently limit the frequency of operations: HTTP API requests, database calls, message sending, and more. Unlike simple counters, the Token Bucket algorithm smooths out load, allowing short traffic bursts while strictly enforcing the average rate over the long term. This makes it an ideal choice for most real-world scenarios.

Why use Bucket4j? First, it protects your backend from overloads and attackers. Second, it enables multi-tiered pricing plans (premium users get more requests per second). Third, the library provides a rich API for fine-tuning, including various token refill strategies, distributed system support via Redis or Hazelcast, and integration with popular frameworks like Spring Boot. Bucket4j isn't just a "stub"—it's a full-fledged production tool.

Installation

Bucket4j is distributed through the Maven Central repository. To add the library to your project, include the dependency in your pom.xml (for Maven) or build.gradle (for Gradle) file.

Maven (pom.xml):

<dependency>
    <groupId>com.github.vladimir-bukhtoyarov</groupId>
    <artifactId>bucket4j-core</artifactId>
    <version>8.7.0</version>
</dependency>

Gradle (build.gradle):

implementation 'com.github.vladimir-bukhtoyarov:bucket4j-core:8.7.0'

Important: Version 8.x requires Java 11 or higher. If you're using Java 8, you'll need version 7.x. For distributed cache support (Redis, Hazelcast), add the corresponding modules, e.g., bucket4j-redis.

Quick Start: Minimal Working Example

Let's create a simple rate limiter that allows no more than 10 operations per second.

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Refill;

import java.time.Duration;

public class QuickStartExample {

    public static void main(String[] args) {
        // 1. Configuration: 10 tokens, refill 10 tokens every second
        Bandwidth limit = Bandwidth.classic(10, Refill.greedy(10, Duration.ofSeconds(1)));

        // 2. Create the bucket
        Bucket bucket = Bucket.builder()
                .addLimit(limit)
                .build();

        // 3. Simulate requests
        for (int i = 1; i <= 15; i++) {
            boolean consumed = bucket.tryConsume(1);
            if (consumed) {
                System.out.println("Request " + i + ": Success (token acquired)");
            } else {
                System.out.println("Request " + i + ": DENIED (limit exceeded)");
            }
        }
    }
}

This code creates a bucket with 10 tokens. Every second, 10 new tokens are added (greedy refill—tokens are added continuously, not in a batch at the end of the interval). The first 10 requests will execute immediately

Recommendations