Tuesday 5 July 2022

Bucket4j rate limiting library tutorial

 

Bucket4j is a Java rate-limiting library based on token-bucket algorithm.

 

Bucket4j is thread safe, you can use it in either standalone JVM application or in clustered environment. Bucket4j support clustered usage scenario on top of following backends.

a.   JCache API

b.   Hazelcast

c.    Apache Ignite

d.   Inifinispan

e.   Oracle Coherence

f.     Redis

g.   MySQL

h.   PostgreSQL

i.     DynamoDb

 

Core classes/interfaces in Bucket4j

Bucket interface: Represent the bucket with maximum capacity. Bucket implementations perform rate limiting using Token Bucket algorithm. Bucket interface provide methods to consume tokens, add tokens, and reset all the tokens etc.,

 

Bandwidth class: Bandwidth class is the key building block for a bucket, it specifies the bucket capacity and refill (token regeneration) strategy.

 


Example

Bandwidth limit = Bandwidth.classic(5, Refill.greedy(2, Duration.ofSeconds(30)));

Bucket bucket = Bucket.builder().addLimit(limit).build();

 

Refill class: Refill class specifies the speed of tokens regeneration. For example, we can create a Refill object that does refill of tokens in intervally manner, or we can create a greedy refill object that does refill of tokens in greedy manner etc.,

 

      Rate limiting strategies
      Bucket4j: Hello World application
      Bucket4j: refill the tokens in interval manner
      Bucket4j: refill the tokens in greedy manner
      Bucket4j: Rate limit by pricing plan

 

You can download all the examples of this tutorial from this link.


 

 

References

https://github.com/bucket4j/bucket4j

Previous                                                 Next                                                 Home

No comments:

Post a Comment