Rate-limiting API Endpoint using Bucket4j in Spring

omoluabidotcom

omoluabidotcom

Posted on December 31, 2023

Rate-limiting API Endpoint using Bucket4j in Spring

Overview

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


com.bucket4j
bucket4j-core
8.1.0

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

@RestController
@RequestMapping
public class RateLimiting {
Bucket bucket;
@GetMapping("/house")
public void initializeBucket() {
Refill refill = Refill.intervally(3, Duration.ofMinutes(1));
Bandwidth limit = Bandwidth.classic(3, refill);
bucket = Bucket.builder()
.addLimit(limit)
.build();
}
@GetMapping("/home")
public ResponseEntity<?> login() {
if(bucket.tryConsume(1)) {
System.out.println("Success");
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.

Credits

https://www.baeldung.com/spring-bucket4j

💖 💪 🙅 🚩
omoluabidotcom
omoluabidotcom

Posted on December 31, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related