Tuesday, 5 July 2022

Bucket4j: Rate limit by pricing plan

In this post, I am going to explain how can we use Bucket4j to rate limit the API based on the pricing plan.

 

Suppose, I have a product P1, which support following price plans.

a.   FREE – 5 requests per hour

b.   BASIC -  400 requests per hour

c.    STANDARD – 1000 requests per hour

d.   PREMIUM – 10000 requests per hour.

 

When a client subscribe to my product P1, we will assign an apiKey to the client based on the price plan. Whenever client send request to the api, he should pass this apiKey. This would help us identify the pricing plan linked with the API client.

 

Step 1: Define the Buckets for each pricing plan.

 

PricingPlan.java

package com.sample.app.enums;

import java.time.Duration;

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

public enum PricingPlan {

	FREE(5), BASIC(400), STANDARD(1000), PREMIUM(10000);

	private int bucketCapacity;

	private PricingPlan(int bucketCapacity) {
		this.bucketCapacity = bucketCapacity;
	}

	public static Bucket resolveBucketApiKey(String apiKey) {
		if (apiKey == null || apiKey.isEmpty()) {
			Bandwidth bandwidth = Bandwidth.classic(PricingPlan.FREE.bucketCapacity,
					Refill.intervally(PricingPlan.FREE.bucketCapacity, Duration.ofHours(1)));
			return Bucket.builder().addLimit(bandwidth).build();

		}

		if (apiKey.startsWith("BASIC-")) {
			Bandwidth bandwidth = Bandwidth.classic(PricingPlan.BASIC.bucketCapacity,
					Refill.intervally(PricingPlan.BASIC.bucketCapacity, Duration.ofHours(1)));
			return Bucket.builder().addLimit(bandwidth).build();
		}

		if (apiKey.startsWith("STANDARD-")) {
			Bandwidth bandwidth = Bandwidth.classic(PricingPlan.STANDARD.bucketCapacity,
					Refill.intervally(PricingPlan.STANDARD.bucketCapacity, Duration.ofHours(1)));
			return Bucket.builder().addLimit(bandwidth).build();
		}

		if (apiKey.startsWith("PREMIUM-")) {
			Bandwidth bandwidth = Bandwidth.classic(PricingPlan.PREMIUM.bucketCapacity,
					Refill.intervally(PricingPlan.PREMIUM.bucketCapacity, Duration.ofHours(1)));
			return Bucket.builder().addLimit(bandwidth).build();
		}

		Bandwidth bandwidth = Bandwidth.classic(PricingPlan.FREE.bucketCapacity,
				Refill.intervally(PricingPlan.FREE.bucketCapacity, Duration.ofHours(1)));
		return Bucket.builder().addLimit(bandwidth).build();

	}
}

Step 2: Define PricePlanDemo class.

 

PricePlanDemo.java

package com.sample.app;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import com.sample.app.enums.PricingPlan;

import io.github.bucket4j.Bucket;

public class PricePlanDemo {

	private static final Map<String, Bucket> BUCKETS_MAP = new ConcurrentHashMap<>();

	private static void getResource(String apiKey) {
		Bucket bucket = null;

		if (BUCKETS_MAP.containsKey(apiKey)) {
			bucket = BUCKETS_MAP.get(apiKey);
		} else {
			bucket = PricingPlan.resolveBucketApiKey(apiKey);
			BUCKETS_MAP.put(apiKey, bucket);
		}

		if (bucket.tryConsume(1)) {
			System.out.println("Resource accessed....");
			return;
		}

		System.err.println("Too Many Requests, all the tokens consumed");
	}

	public static void main(String[] args) throws InterruptedException {
		while (true) {
			TimeUnit.SECONDS.sleep(1);
			getResource("FREE-12easdfgft");
		}

	}

}

Sample Output



 

 

Previous                                                 Next                                                 Home

Bucket4j: refill the tokens in greedy manner

Refill#greedy method Creates the Refill that does refill of tokens in greedy manner, it will try to add the tokens to bucket as soon as possible.

 

For example refill "10 tokens per 1 second" will add 1 token per each 100 millisecond, in other words refill will not wait 1 second to regenerate whole bunch of 10 tokens.

 

Signature

public static Refill greedy(long tokens, Duration period)

Argument 'tokens' specifies amount of tokens and 'period' specifies the period within tokens will be fully regenerated.

 

Note

The three refills bellow do refill of tokens with same speed:

a.   Refill.greedy(600, Duration.ofMinutes(1));

b.   Refill.greedy(10, Duration.ofSeconds(1));

c.    Refill.greedy(1, Duration.ofMillis(100));

 

Find the below working application.

 

HelloWorld.java

package com.sample.app;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

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

public class HelloWorld {

	private static Bucket bucket;

	private static void getResource() {

		if (bucket.tryConsume(1)) {
			System.out.println("Resource accessed....");
			return;
		}

		System.err.println("Too Many Requests, all the tokens consumed");
	}

	public static void main(String[] args) throws InterruptedException {
		Bandwidth limit = Bandwidth.classic(5, Refill.greedy(10, Duration.ofSeconds(30)));
		bucket = Bucket.builder().addLimit(limit).build();

		while (true) {
			TimeUnit.SECONDS.sleep(1);
			getResource();
		}
	}

}

 

Sample output


 

  

Previous                                                 Next                                                 Home

Bucket4j: refill the tokens in interval manner

Refill#intervally method refill the tokens in intervally manner. This refill strategy will wait until whole period will be elapsed before regenerate tokens.

 

Signature

public static Refill intervally(long tokens, Duration period)

'tokens' specifies the amount of tokens and 'period' specifies the period within tokens will be fully regenerated.

 

Example

Bandwidth limit = Bandwidth.classic(5, Refill.intervally(5, Duration.ofSeconds(10)));

Unlike ‘Refill.greedy’ method, Refill.intervally method refills the bucket at the beginning of the time window, in this example, 5 tokens at the start of the 10 seconds.

 

Find the below working application.

 

RefillTokensIntervally.java

package com.sample.app;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

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

public class RefillTokensIntervally {

	private static Bucket bucket;

	private static void getResource() {

		final long noOfTokensLeft = bucket.getAvailableTokens();

		if (noOfTokensLeft == 0L) {
			System.err.println("Number of tokens left : " + bucket.getAvailableTokens());
		} else {
			System.out.println("Number of tokens left : " + bucket.getAvailableTokens());
		}

		if (bucket.tryConsume(1)) {
			System.out.println("Resource accessed....\n");
			return;
		}

		System.err.println("Too Many Requests, all the tokens consumed\n");
	}

	public static void main(String[] args) throws InterruptedException {
		Bandwidth limit = Bandwidth.classic(5, Refill.intervally(5, Duration.ofSeconds(10)));
		bucket = Bucket.builder().addLimit(limit).build();

		while (true) {
			TimeUnit.SECONDS.sleep(1);
			getResource();
		}
	}

}

Output

Number of tokens left : 5
Resource accessed....

Number of tokens left : 4
Resource accessed....

Number of tokens left : 3
Resource accessed....

Number of tokens left : 2
Resource accessed....

Number of tokens left : 1
Resource accessed....

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 5
Resource accessed....

Number of tokens left : 4
Resource accessed....

Number of tokens left : 3
Resource accessed....

Number of tokens left : 2
Resource accessed....

Number of tokens left : 1
Resource accessed....

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 5
Resource accessed....

Number of tokens left : 4
Resource accessed....

Number of tokens left : 3
Resource accessed....

Number of tokens left : 2
Resource accessed....

Number of tokens left : 1
Resource accessed....

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 0
Too Many Requests, all the tokens consumed

Number of tokens left : 5
Resource accessed....

Number of tokens left : 4
Resource accessed....

Number of tokens left : 3
Resource accessed....

Number of tokens left : 2
Resource accessed....

Number of tokens left : 1
Resource accessed....

Number of tokens left : 0
Too Many Requests, all the tokens consumed




 

Previous                                                 Next                                                 Home

Bucket4j: Hello World application

Step 1: Define a Bucket instance.

Bandwidth limit = Bandwidth.classic(5, Refill.greedy(10, Duration.ofSeconds(30)));
Bucket bucket = Bucket.builder().addLimit(limit).build();

 

Above snippet define a bucket with capacity 5 (It can store 5 tokens maximum), and refill the tokens in greedy manner (10 tokens in 30 seconds duration). For example refill "10 tokens per 1 second" will add 1 token per each 100 millisecond, in other words refill will not wait 1 second to regenerate whole bunch of 10 tokens.

 

The three refills bellow do refill of tokens with same speed:

a.   Refill.greedy(600, Duration.ofMinutes(1));

b.   Refill.greedy(10, Duration.ofSeconds(1));

c.    Refill.greedy(1, Duration.ofMillis(100));

 

Step 2: Apply rate limiting on the methods that you are interested.

private static void getResource() {

	if (bucket.tryConsume(1)) {
		System.out.println("Resource accessed....");
		return;
	}

	System.err.println("Too Many Requests, all the tokens consumed");
}

 

‘getResource’ method try to get a token before permitting access to the resource. if it got the token then the resource will be accessed successfully, else some error message is printed to the console.

 

Find the below working application.

 

HelloWorld.java

package com.sample.app;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

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

public class HelloWorld {

	private static Bucket bucket;

	private static void getResource() {

		if (bucket.tryConsume(1)) {
			System.out.println("Resource accessed....");
			return;
		}

		System.err.println("Too Many Requests, all the tokens consumed");
	}

	public static void main(String[] args) throws InterruptedException {
		Bandwidth limit = Bandwidth.classic(5, Refill.greedy(10, Duration.ofSeconds(30)));
		bucket = Bucket.builder().addLimit(limit).build();

		while (true) {
			TimeUnit.SECONDS.sleep(1);
			getResource();
		}
	}

}

Sample output



 

 

 

 

 

 

Previous                                                 Next                                                 Home

Rate limiting strategies

In this post, I am going to explain what is rate limiting, why rate limiting is used, and what are the different strategies/techniques used for rate limiting.

 

What is rate limiting?

Rate limiting is a strategy to limit the network traffic. Rate limiting protect the resources from excessive use. Rate limiting can be applied at both client and server side.

 

When a client receive rate limiting message or error from the server, Client retry the request after certain delay. As a best practice, client can increase this delay exponentially after each failed request.

 

Example of server side rate limiting

we can rate limit the Rest APIs to protect the underlying database.

 

Example of Client side rate limiting

Assume you developed a desktop client to seamlessly collaborate, synchronize and store documents between remote server and your computer. You should apply rate limiting on upload and download speeds at the client application level, otherwise this application end up in using all your internet bandwidth.

 

Example of rate limiting in a distributed computing

You can apply rate limiting to evenly distribute the work between multiple worker nodes. This prevent a worker node from accumulating a huge unprocessed items from the queue.

 

Why rate limiting?

a.   Reduce load on the servers

b.   Constrain some malicious activity like DoS (Denial of Service) and DDoS (Distributed Denial of Service) attacks.

c.    Improve the APIs availability by avoiding resources starvation

d.   Rate limiting can be used to control the cost, for example, my product XYZ has monthly budget of 10000$, then I can use rate limiting to run my application with in this budget.

 

What HTTP status code I can use to convey rate limiting errors?

HTTP status code 429 Too Many Requests, can be used to convey rate limiting errors. While sending the response, server can optionally send a Retry-After header might be included to this response indicating how long to wait before making a new request.

 

Example

HTTP/1.1 429 Too Many Requests
Content-Type: text/html
Retry-After: 1000

 

Following are the widely used rate limiting techniques.

 

a. Fixed window algorithm

In this technique we rate limit number of requests per certain fixed duration like 100 requests/minute, 5000 requests/hour etc., This algorithm is easy to implement.

 

One of the major drawback of this algorithm is, this leads to spikes at the edges of the window.

 

For example, we configured 5000 requests/hour, there is a possibility that all the 5000 requests are made in first 10 minutes and served. This might overwhelm the service and service will send rate limiting error in next 50 minutes (even though there is not much load on the server).

 

Another possibility can be , there is a possibility that all the 5000 requests are made in last 10 minutes (5.50 to 6.00) of the hour for this window, and all the 5000 requests are made the first 10 minutes of the next window (6.00 to 6.10). That means you are getting 10000 requests in 20 minutes (5.50 to 6.10).

 

Sliding window algorithm

It solves the boundaries problem in fixed window algorithm. Let me explain it with an example, Suppose you configured 50 requests/minute sliding algorithm.

 

Whenever a request comes to the server, this algorithm checks the request count in last minute (not the fixed minute). It check how many requests are there is last 1 minute, if the number of requests are < 50, then this request is processed, else failed with some rate limiting error.

 

Token bucket algorithm

A token bucket add or generate tokens at some fixed rate. For example, I can create a token bucket of size 10 and a refill rate of 1 per 10 seconds. This refill happen only when the number of token in the bucket are < 10.

 

Let us try to understand this with below example.

 

Time      Requests    AvailableTokens
5:00:00     0          10 (we have 10 tokens initially)
5:00:10     0          10 (refill attempt failed cause Bucket is full)
5:00:20     0          10 (refill attempt failed cause Bucket is full)
5:00:30     0          10 (refill attempt failed cause Bucket is full)
5:00:40     0          10 (refill attempt failed cause Bucket is full)
5:00:50     0          10 (refill attempt failed cause Bucket is full)
5:00:58     8          2 (10 - 8) 
5:01:00     0          3 (refill 1 token)
5:01:10     0          4 (refill 1 token)
5:01:20     0          5 (refill 1 token)
5:01:30     0          6 (refill 1 token)
5:01:49     4          2 (6 - 4) 
5:01:50     0          3 (refill 1 token)

 

Leaky bucket algorithm

Leaky bucket is easy to implement. In this algorithm rate is limited by size of the queue. If the size of queue is set to 5, at max 5 requests can be sent to this service


 

When a new request received by this API and the queue is full, this API throw the error with response code 429 (rate limiting error).

Previous                                                 Next                                                 Home

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

Monday, 4 July 2022

Atlas client : Delete a type by name

This is continuation to my previous posts. In previous posts, I explained how to create new type ‘tablet’ and update the definition.

 

In this post, I am going to explain how to delete the type by name.

 

AtlasClientV2#deleteTypeByName method is used to delete the type by name. If there are entities created for this type, then this method throws an exception.

 

Create atlas-application.properties file under src/main/resources folder.

 

atlas-application.properties

atlas.client.readTimeoutMSecs=30000
atlas.client.connectTimeoutMSecs=30000

DeleteTypeByName.java

package com.sample.app.types;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;

import com.fasterxml.jackson.core.JsonProcessingException;

public class DeleteTypeByName {
  public static void main(String[] args) throws AtlasServiceException, JsonProcessingException {
    AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
        new String[] { "admin", "admin" });

    String typeToDelete = "tablet";

    boolean isTypeExists = atlasClient.typeWithNameExists(typeToDelete);
    System.out.println("Is type with name '" + typeToDelete + "' exists : " + isTypeExists);

    System.out.println("\nTrying to delete the type : " + typeToDelete);
    atlasClient.deleteTypeByName(typeToDelete);

    isTypeExists = atlasClient.typeWithNameExists(typeToDelete);
    System.out.println("\nIs type with name '" + typeToDelete + "' exists : " + isTypeExists);

  }
}

Output

Is type with name 'tablet' exists : true

Trying to delete the type : tablet

Is type with name 'tablet' exists : false

 

Previous                                                    Next                                                    Home