DEV Community

Cover image for Rate-limiting API Endpoint using Bucket4j in Spring

Posted on

Rate-limiting API Endpoint using Bucket4j in Spring


In this article, you will learn how to implement a rate limit. Our focus will be to implement a rate limit for an endpoint using the Bucket4j library.

Rate-Limiting API

There are different reasons to apply a rate limit to an API endpoint. One of many reasons would be to implement a rate limit based on the subscription plan on a system; another is that the request to login endpoint should be controlled from a unique request source, thereby regulating the number of requests made within a few minutes, as this can allow individuals with bad intent to carry out brute force attacks on your server, thereby leading to a server crash and making your application unavailable to users.

Bucket4J Library

Bucket4j is a Java rate-limiting library that is mainly based on the token-bucket algorithm. The token bucket algorithm enables a network to allow or deny requests based on current traffic. Each bucket holds a certain number of tokens that represent network requests (e.g., attempting to log into an account or sending a message). Whenever a user sends a request, another token gets added to the bucket.

Since the bucket has a set limit on how many tokens it can hold, the algorithm stops operations if users make too many requests in a short time. The network drops all new requests until a "bucket refill" resets the number of allowed tokens.

Using Bucket4j Library to Limit Endpoint

Using the Bucket4j library is very simple, though it might get complex with more needed control. First, we need to setup a Spring application using the Spring initializr. Add the Spring web dependency. One additional dependency is the bucket4j library. Here is snippet to add to pom


Below are a few lines of code that just implemented rate limiting on the home endpoint. This is how simple it can be.

Image description

Code Snippet

public class RateLimiting {
Bucket bucket;
public void initializeBucket() {
Refill refill = Refill.intervally(3, Duration.ofMinutes(1));
Bandwidth limit = Bandwidth.classic(3, refill);
bucket = Bucket.builder()
public ResponseEntity<?> login() {
if(bucket.tryConsume(1)) {
return ResponseEntity.ok("Successful");
} else {
System.out.println("Too many requests");
return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).build();
Enter fullscreen mode Exit fullscreen mode

That is all from me. Happy Holidays to you and your loved ones! Connect with me on LinkedIn.


Top comments (0)