DEV Community

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

Posted on

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

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay