Avatar
1
Bảo Ngô Beginner
Bảo Ngô Beginner
Java Spring rate limiter block specific duration when ratio reached
Currently I have a requirement: Apply rate limiter for an API. If this API get called over 100 times per 5 sec then the API will be blocked for 10 mins. I don't know if there is any java lib can fullfill this requirement. If the requirement is "Allow 100 calls per 5 sec" or "Allow 100 calls per 10 min" then I can either user Bucket4j: <p> </p> <p> </p> <pre> Bandwidth b = Bandwidth.classic(100, Refill.intervally(100, Duration.ofSeconds(5))); //Bandwidth b = Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(10))); Bucket bk = Bucket.builder().addLimit(b).build(); //then if(bk.tryConsume(1)) { //stuff } else { throw } </pre> <p> </p> <p> or Resilence4j: </p> <p> </p> <pre> RateLimiterConfig config = RateLimiterConfig.custom() .limitRefreshPeriod(Duration.ofSeconds(5)) .limitForPeriod(100) .timeoutDuration(Duration.ofSeconds(1)) .build(); RateLimiterRegistry rateLimiterRegistry = RateLimiterRegistry.of(config); RateLimiter rateLimiterWithCustomConfig = rateLimiterRegistry .rateLimiter("name2", config); CheckedRunnable restrictedCall = RateLimiter .decorateCheckedRunnable(rateLimiterWithCustomConfig, this::doStuff); //then Try.run(restrictedCall).onFailure(this::throwEx) </pre> <p> </p> <p> But the requirement is "Allow 100 calls per 5 sec, if more, block 10 min". Is there any lib can work? Please suggest me a solution for this case. Thank you </p>
Answer