Wednesday, 18 April 2018

How to limit number of requests?

In this post, you are going to learn
         a. What is Rate limiting?
         b. Why should we do Rate limiting?
         c. How to limit number of requests example?
        
What is Rate limiting?
Rate limiting is the process of controlling the rate of traffic sent/received by an application.

Why should we do Rate limiting?
Rate limiting mainly used to address DOS (Denial of Service) attacks. There are different kinds of rate limiting algorithms available. For example, you can rate limit by number of requests per second, you can rate limit by maximum number of requests from a client per second, you can rate limit based on the resource consumption.

How to limit number of requests example?
Guava package provides RateLimiter class to rate limit the requests.

I am using Guava rate limiter api.
  <!-- https://mvnrepository.com/artifact/com.revinate/guava-rate-limiter -->
  <dependency>
   <groupId>com.revinate</groupId>
   <artifactId>guava-rate-limiter</artifactId>
   <version>19.0</version>
  </dependency>

Below statements create an instance of RateLimiter that limit maximum number of requests to 5 per second.
  RateLimiter rateLimiter = RateLimiter.create(5); // 5 requests/second

  boolean isAcquired = rateLimiter.tryAcquire();

  if (!isAcquired) {
   throw new MaximumRequestsExceeded("Maximum number of requests per second are exceeded");
  }

MaximumRequestsExceeded.java
package com.sample.exceptions;

public class MaximumRequestsExceeded extends RuntimeException{

 private static final long serialVersionUID = 1L;

 public MaximumRequestsExceeded(String message){
  super(message);
 }
}


You may like

No comments:

Post a Comment